4083c6363c228cec1bafed0b561bd30747b8881b
[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
85 typedef struct symbol *symbolp;
86 DEF_VEC_P (symbolp);
87
88 /* When == 1, print basic high level tracing messages.
89    When > 1, be more verbose.
90    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
91 static unsigned int dwarf_read_debug = 0;
92
93 /* When non-zero, dump DIEs after they are read in.  */
94 static unsigned int dwarf_die_debug = 0;
95
96 /* When non-zero, dump line number entries as they are read in.  */
97 static unsigned int dwarf_line_debug = 0;
98
99 /* When non-zero, cross-check physname against demangler.  */
100 static int check_physname = 0;
101
102 /* When non-zero, do not reject deprecated .gdb_index sections.  */
103 static int use_deprecated_index_sections = 0;
104
105 static const struct objfile_data *dwarf2_objfile_data_key;
106
107 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
108
109 static int dwarf2_locexpr_index;
110 static int dwarf2_loclist_index;
111 static int dwarf2_locexpr_block_index;
112 static int dwarf2_loclist_block_index;
113
114 /* A descriptor for dwarf sections.
115
116    S.ASECTION, SIZE are typically initialized when the objfile is first
117    scanned.  BUFFER, READIN are filled in later when the section is read.
118    If the section contained compressed data then SIZE is updated to record
119    the uncompressed size of the section.
120
121    DWP file format V2 introduces a wrinkle that is easiest to handle by
122    creating the concept of virtual sections contained within a real section.
123    In DWP V2 the sections of the input DWO files are concatenated together
124    into one section, but section offsets are kept relative to the original
125    input section.
126    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
127    the real section this "virtual" section is contained in, and BUFFER,SIZE
128    describe the virtual section.  */
129
130 struct dwarf2_section_info
131 {
132   union
133   {
134     /* If this is a real section, the bfd section.  */
135     asection *section;
136     /* If this is a virtual section, pointer to the containing ("real")
137        section.  */
138     struct dwarf2_section_info *containing_section;
139   } s;
140   /* Pointer to section data, only valid if readin.  */
141   const gdb_byte *buffer;
142   /* The size of the section, real or virtual.  */
143   bfd_size_type size;
144   /* If this is a virtual section, the offset in the real section.
145      Only valid if is_virtual.  */
146   bfd_size_type virtual_offset;
147   /* True if we have tried to read this section.  */
148   char readin;
149   /* True if this is a virtual section, False otherwise.
150      This specifies which of s.section and s.containing_section to use.  */
151   char is_virtual;
152 };
153
154 typedef struct dwarf2_section_info dwarf2_section_info_def;
155 DEF_VEC_O (dwarf2_section_info_def);
156
157 /* All offsets in the index are of this type.  It must be
158    architecture-independent.  */
159 typedef uint32_t offset_type;
160
161 DEF_VEC_I (offset_type);
162
163 /* Ensure only legit values are used.  */
164 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
165   do { \
166     gdb_assert ((unsigned int) (value) <= 1); \
167     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
168   } while (0)
169
170 /* Ensure only legit values are used.  */
171 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
172   do { \
173     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
174                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
175     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
176   } while (0)
177
178 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
179 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
180   do { \
181     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
182     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
183   } while (0)
184
185 /* A description of the mapped index.  The file format is described in
186    a comment by the code that writes the index.  */
187 struct mapped_index
188 {
189   /* Index data format version.  */
190   int version;
191
192   /* The total length of the buffer.  */
193   off_t total_size;
194
195   /* A pointer to the address table data.  */
196   const gdb_byte *address_table;
197
198   /* Size of the address table data in bytes.  */
199   offset_type address_table_size;
200
201   /* The symbol table, implemented as a hash table.  */
202   const offset_type *symbol_table;
203
204   /* Size in slots, each slot is 2 offset_types.  */
205   offset_type symbol_table_slots;
206
207   /* A pointer to the constant pool.  */
208   const char *constant_pool;
209 };
210
211 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
212 DEF_VEC_P (dwarf2_per_cu_ptr);
213
214 struct tu_stats
215 {
216   int nr_uniq_abbrev_tables;
217   int nr_symtabs;
218   int nr_symtab_sharers;
219   int nr_stmt_less_type_units;
220   int nr_all_type_units_reallocs;
221 };
222
223 /* Collection of data recorded per objfile.
224    This hangs off of dwarf2_objfile_data_key.  */
225
226 struct dwarf2_per_objfile
227 {
228   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
229      dwarf2 section names, or is NULL if the standard ELF names are
230      used.  */
231   dwarf2_per_objfile (struct objfile *objfile,
232                       const dwarf2_debug_sections *names);
233
234   ~dwarf2_per_objfile ();
235
236   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
237
238   /* Free all cached compilation units.  */
239   void free_cached_comp_units ();
240 private:
241   /* This function is mapped across the sections and remembers the
242      offset and size of each of the debugging sections we are
243      interested in.  */
244   void locate_sections (bfd *abfd, asection *sectp,
245                         const dwarf2_debug_sections &names);
246
247 public:
248   dwarf2_section_info info {};
249   dwarf2_section_info abbrev {};
250   dwarf2_section_info line {};
251   dwarf2_section_info loc {};
252   dwarf2_section_info loclists {};
253   dwarf2_section_info macinfo {};
254   dwarf2_section_info macro {};
255   dwarf2_section_info str {};
256   dwarf2_section_info line_str {};
257   dwarf2_section_info ranges {};
258   dwarf2_section_info rnglists {};
259   dwarf2_section_info addr {};
260   dwarf2_section_info frame {};
261   dwarf2_section_info eh_frame {};
262   dwarf2_section_info gdb_index {};
263
264   VEC (dwarf2_section_info_def) *types = NULL;
265
266   /* Back link.  */
267   struct objfile *objfile = NULL;
268
269   /* Table of all the compilation units.  This is used to locate
270      the target compilation unit of a particular reference.  */
271   struct dwarf2_per_cu_data **all_comp_units = NULL;
272
273   /* The number of compilation units in ALL_COMP_UNITS.  */
274   int n_comp_units = 0;
275
276   /* The number of .debug_types-related CUs.  */
277   int n_type_units = 0;
278
279   /* The number of elements allocated in all_type_units.
280      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
281   int n_allocated_type_units = 0;
282
283   /* The .debug_types-related CUs (TUs).
284      This is stored in malloc space because we may realloc it.  */
285   struct signatured_type **all_type_units = NULL;
286
287   /* Table of struct type_unit_group objects.
288      The hash key is the DW_AT_stmt_list value.  */
289   htab_t type_unit_groups {};
290
291   /* A table mapping .debug_types signatures to its signatured_type entry.
292      This is NULL if the .debug_types section hasn't been read in yet.  */
293   htab_t signatured_types {};
294
295   /* Type unit statistics, to see how well the scaling improvements
296      are doing.  */
297   struct tu_stats tu_stats {};
298
299   /* A chain of compilation units that are currently read in, so that
300      they can be freed later.  */
301   dwarf2_per_cu_data *read_in_chain = NULL;
302
303   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
304      This is NULL if the table hasn't been allocated yet.  */
305   htab_t dwo_files {};
306
307   /* True if we've checked for whether there is a DWP file.  */
308   bool dwp_checked = false;
309
310   /* The DWP file if there is one, or NULL.  */
311   struct dwp_file *dwp_file = NULL;
312
313   /* The shared '.dwz' file, if one exists.  This is used when the
314      original data was compressed using 'dwz -m'.  */
315   struct dwz_file *dwz_file = NULL;
316
317   /* A flag indicating whether this objfile has a section loaded at a
318      VMA of 0.  */
319   bool has_section_at_zero = false;
320
321   /* True if we are using the mapped index,
322      or we are faking it for OBJF_READNOW's sake.  */
323   bool using_index = false;
324
325   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
326   mapped_index *index_table = NULL;
327
328   /* When using index_table, this keeps track of all quick_file_names entries.
329      TUs typically share line table entries with a CU, so we maintain a
330      separate table of all line table entries to support the sharing.
331      Note that while there can be way more TUs than CUs, we've already
332      sorted all the TUs into "type unit groups", grouped by their
333      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
334      CU and its associated TU group if there is one.  */
335   htab_t quick_file_names_table {};
336
337   /* Set during partial symbol reading, to prevent queueing of full
338      symbols.  */
339   bool reading_partial_symbols = false;
340
341   /* Table mapping type DIEs to their struct type *.
342      This is NULL if not allocated yet.
343      The mapping is done via (CU/TU + DIE offset) -> type.  */
344   htab_t die_type_hash {};
345
346   /* The CUs we recently read.  */
347   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
348
349   /* Table containing line_header indexed by offset and offset_in_dwz.  */
350   htab_t line_header_hash {};
351
352   /* Table containing all filenames.  This is an optional because the
353      table is lazily constructed on first access.  */
354   gdb::optional<filename_seen_cache> filenames_cache;
355 };
356
357 static struct dwarf2_per_objfile *dwarf2_per_objfile;
358
359 /* Default names of the debugging sections.  */
360
361 /* Note that if the debugging section has been compressed, it might
362    have a name like .zdebug_info.  */
363
364 static const struct dwarf2_debug_sections dwarf2_elf_names =
365 {
366   { ".debug_info", ".zdebug_info" },
367   { ".debug_abbrev", ".zdebug_abbrev" },
368   { ".debug_line", ".zdebug_line" },
369   { ".debug_loc", ".zdebug_loc" },
370   { ".debug_loclists", ".zdebug_loclists" },
371   { ".debug_macinfo", ".zdebug_macinfo" },
372   { ".debug_macro", ".zdebug_macro" },
373   { ".debug_str", ".zdebug_str" },
374   { ".debug_line_str", ".zdebug_line_str" },
375   { ".debug_ranges", ".zdebug_ranges" },
376   { ".debug_rnglists", ".zdebug_rnglists" },
377   { ".debug_types", ".zdebug_types" },
378   { ".debug_addr", ".zdebug_addr" },
379   { ".debug_frame", ".zdebug_frame" },
380   { ".eh_frame", NULL },
381   { ".gdb_index", ".zgdb_index" },
382   23
383 };
384
385 /* List of DWO/DWP sections.  */
386
387 static const struct dwop_section_names
388 {
389   struct dwarf2_section_names abbrev_dwo;
390   struct dwarf2_section_names info_dwo;
391   struct dwarf2_section_names line_dwo;
392   struct dwarf2_section_names loc_dwo;
393   struct dwarf2_section_names loclists_dwo;
394   struct dwarf2_section_names macinfo_dwo;
395   struct dwarf2_section_names macro_dwo;
396   struct dwarf2_section_names str_dwo;
397   struct dwarf2_section_names str_offsets_dwo;
398   struct dwarf2_section_names types_dwo;
399   struct dwarf2_section_names cu_index;
400   struct dwarf2_section_names tu_index;
401 }
402 dwop_section_names =
403 {
404   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
405   { ".debug_info.dwo", ".zdebug_info.dwo" },
406   { ".debug_line.dwo", ".zdebug_line.dwo" },
407   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
408   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
409   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
410   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
411   { ".debug_str.dwo", ".zdebug_str.dwo" },
412   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
413   { ".debug_types.dwo", ".zdebug_types.dwo" },
414   { ".debug_cu_index", ".zdebug_cu_index" },
415   { ".debug_tu_index", ".zdebug_tu_index" },
416 };
417
418 /* local data types */
419
420 /* The data in a compilation unit header, after target2host
421    translation, looks like this.  */
422 struct comp_unit_head
423 {
424   unsigned int length;
425   short version;
426   unsigned char addr_size;
427   unsigned char signed_addr_p;
428   sect_offset abbrev_sect_off;
429
430   /* Size of file offsets; either 4 or 8.  */
431   unsigned int offset_size;
432
433   /* Size of the length field; either 4 or 12.  */
434   unsigned int initial_length_size;
435
436   enum dwarf_unit_type unit_type;
437
438   /* Offset to the first byte of this compilation unit header in the
439      .debug_info section, for resolving relative reference dies.  */
440   sect_offset sect_off;
441
442   /* Offset to first die in this cu from the start of the cu.
443      This will be the first byte following the compilation unit header.  */
444   cu_offset first_die_cu_offset;
445
446   /* 64-bit signature of this type unit - it is valid only for
447      UNIT_TYPE DW_UT_type.  */
448   ULONGEST signature;
449
450   /* For types, offset in the type's DIE of the type defined by this TU.  */
451   cu_offset type_cu_offset_in_tu;
452 };
453
454 /* Type used for delaying computation of method physnames.
455    See comments for compute_delayed_physnames.  */
456 struct delayed_method_info
457 {
458   /* The type to which the method is attached, i.e., its parent class.  */
459   struct type *type;
460
461   /* The index of the method in the type's function fieldlists.  */
462   int fnfield_index;
463
464   /* The index of the method in the fieldlist.  */
465   int index;
466
467   /* The name of the DIE.  */
468   const char *name;
469
470   /*  The DIE associated with this method.  */
471   struct die_info *die;
472 };
473
474 typedef struct delayed_method_info delayed_method_info;
475 DEF_VEC_O (delayed_method_info);
476
477 /* Internal state when decoding a particular compilation unit.  */
478 struct dwarf2_cu
479 {
480   /* The objfile containing this compilation unit.  */
481   struct objfile *objfile;
482
483   /* The header of the compilation unit.  */
484   struct comp_unit_head header;
485
486   /* Base address of this compilation unit.  */
487   CORE_ADDR base_address;
488
489   /* Non-zero if base_address has been set.  */
490   int base_known;
491
492   /* The language we are debugging.  */
493   enum language language;
494   const struct language_defn *language_defn;
495
496   const char *producer;
497
498   /* The generic symbol table building routines have separate lists for
499      file scope symbols and all all other scopes (local scopes).  So
500      we need to select the right one to pass to add_symbol_to_list().
501      We do it by keeping a pointer to the correct list in list_in_scope.
502
503      FIXME: The original dwarf code just treated the file scope as the
504      first local scope, and all other local scopes as nested local
505      scopes, and worked fine.  Check to see if we really need to
506      distinguish these in buildsym.c.  */
507   struct pending **list_in_scope;
508
509   /* The abbrev table for this CU.
510      Normally this points to the abbrev table in the objfile.
511      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
512   struct abbrev_table *abbrev_table;
513
514   /* Hash table holding all the loaded partial DIEs
515      with partial_die->offset.SECT_OFF as hash.  */
516   htab_t partial_dies;
517
518   /* Storage for things with the same lifetime as this read-in compilation
519      unit, including partial DIEs.  */
520   struct obstack comp_unit_obstack;
521
522   /* When multiple dwarf2_cu structures are living in memory, this field
523      chains them all together, so that they can be released efficiently.
524      We will probably also want a generation counter so that most-recently-used
525      compilation units are cached...  */
526   struct dwarf2_per_cu_data *read_in_chain;
527
528   /* Backlink to our per_cu entry.  */
529   struct dwarf2_per_cu_data *per_cu;
530
531   /* How many compilation units ago was this CU last referenced?  */
532   int last_used;
533
534   /* A hash table of DIE cu_offset for following references with
535      die_info->offset.sect_off as hash.  */
536   htab_t die_hash;
537
538   /* Full DIEs if read in.  */
539   struct die_info *dies;
540
541   /* A set of pointers to dwarf2_per_cu_data objects for compilation
542      units referenced by this one.  Only set during full symbol processing;
543      partial symbol tables do not have dependencies.  */
544   htab_t dependencies;
545
546   /* Header data from the line table, during full symbol processing.  */
547   struct line_header *line_header;
548   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
549      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
550      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
551      to the line header as long as this DIE is being processed.  See
552      process_die_scope.  */
553   die_info *line_header_die_owner;
554
555   /* A list of methods which need to have physnames computed
556      after all type information has been read.  */
557   VEC (delayed_method_info) *method_list;
558
559   /* To be copied to symtab->call_site_htab.  */
560   htab_t call_site_htab;
561
562   /* Non-NULL if this CU came from a DWO file.
563      There is an invariant here that is important to remember:
564      Except for attributes copied from the top level DIE in the "main"
565      (or "stub") file in preparation for reading the DWO file
566      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
567      Either there isn't a DWO file (in which case this is NULL and the point
568      is moot), or there is and either we're not going to read it (in which
569      case this is NULL) or there is and we are reading it (in which case this
570      is non-NULL).  */
571   struct dwo_unit *dwo_unit;
572
573   /* The DW_AT_addr_base attribute if present, zero otherwise
574      (zero is a valid value though).
575      Note this value comes from the Fission stub CU/TU's DIE.  */
576   ULONGEST addr_base;
577
578   /* The DW_AT_ranges_base attribute if present, zero otherwise
579      (zero is a valid value though).
580      Note this value comes from the Fission stub CU/TU's DIE.
581      Also note that the value is zero in the non-DWO case so this value can
582      be used without needing to know whether DWO files are in use or not.
583      N.B. This does not apply to DW_AT_ranges appearing in
584      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
585      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
586      DW_AT_ranges_base *would* have to be applied, and we'd have to care
587      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
588   ULONGEST ranges_base;
589
590   /* Mark used when releasing cached dies.  */
591   unsigned int mark : 1;
592
593   /* This CU references .debug_loc.  See the symtab->locations_valid field.
594      This test is imperfect as there may exist optimized debug code not using
595      any location list and still facing inlining issues if handled as
596      unoptimized code.  For a future better test see GCC PR other/32998.  */
597   unsigned int has_loclist : 1;
598
599   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
600      if all the producer_is_* fields are valid.  This information is cached
601      because profiling CU expansion showed excessive time spent in
602      producer_is_gxx_lt_4_6.  */
603   unsigned int checked_producer : 1;
604   unsigned int producer_is_gxx_lt_4_6 : 1;
605   unsigned int producer_is_gcc_lt_4_3 : 1;
606   unsigned int producer_is_icc : 1;
607
608   /* When set, the file that we're processing is known to have
609      debugging info for C++ namespaces.  GCC 3.3.x did not produce
610      this information, but later versions do.  */
611
612   unsigned int processing_has_namespace_info : 1;
613 };
614
615 /* Persistent data held for a compilation unit, even when not
616    processing it.  We put a pointer to this structure in the
617    read_symtab_private field of the psymtab.  */
618
619 struct dwarf2_per_cu_data
620 {
621   /* The start offset and length of this compilation unit.
622      NOTE: Unlike comp_unit_head.length, this length includes
623      initial_length_size.
624      If the DIE refers to a DWO file, this is always of the original die,
625      not the DWO file.  */
626   sect_offset sect_off;
627   unsigned int length;
628
629   /* DWARF standard version this data has been read from (such as 4 or 5).  */
630   short dwarf_version;
631
632   /* Flag indicating this compilation unit will be read in before
633      any of the current compilation units are processed.  */
634   unsigned int queued : 1;
635
636   /* This flag will be set when reading partial DIEs if we need to load
637      absolutely all DIEs for this compilation unit, instead of just the ones
638      we think are interesting.  It gets set if we look for a DIE in the
639      hash table and don't find it.  */
640   unsigned int load_all_dies : 1;
641
642   /* Non-zero if this CU is from .debug_types.
643      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
644      this is non-zero.  */
645   unsigned int is_debug_types : 1;
646
647   /* Non-zero if this CU is from the .dwz file.  */
648   unsigned int is_dwz : 1;
649
650   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
651      This flag is only valid if is_debug_types is true.
652      We can't read a CU directly from a DWO file: There are required
653      attributes in the stub.  */
654   unsigned int reading_dwo_directly : 1;
655
656   /* Non-zero if the TU has been read.
657      This is used to assist the "Stay in DWO Optimization" for Fission:
658      When reading a DWO, it's faster to read TUs from the DWO instead of
659      fetching them from random other DWOs (due to comdat folding).
660      If the TU has already been read, the optimization is unnecessary
661      (and unwise - we don't want to change where gdb thinks the TU lives
662      "midflight").
663      This flag is only valid if is_debug_types is true.  */
664   unsigned int tu_read : 1;
665
666   /* The section this CU/TU lives in.
667      If the DIE refers to a DWO file, this is always the original die,
668      not the DWO file.  */
669   struct dwarf2_section_info *section;
670
671   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
672      of the CU cache it gets reset to NULL again.  This is left as NULL for
673      dummy CUs (a CU header, but nothing else).  */
674   struct dwarf2_cu *cu;
675
676   /* The corresponding objfile.
677      Normally we can get the objfile from dwarf2_per_objfile.
678      However we can enter this file with just a "per_cu" handle.  */
679   struct objfile *objfile;
680
681   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
682      is active.  Otherwise, the 'psymtab' field is active.  */
683   union
684   {
685     /* The partial symbol table associated with this compilation unit,
686        or NULL for unread partial units.  */
687     struct partial_symtab *psymtab;
688
689     /* Data needed by the "quick" functions.  */
690     struct dwarf2_per_cu_quick_data *quick;
691   } v;
692
693   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
694      while reading psymtabs, used to compute the psymtab dependencies,
695      and then cleared.  Then it is filled in again while reading full
696      symbols, and only deleted when the objfile is destroyed.
697
698      This is also used to work around a difference between the way gold
699      generates .gdb_index version <=7 and the way gdb does.  Arguably this
700      is a gold bug.  For symbols coming from TUs, gold records in the index
701      the CU that includes the TU instead of the TU itself.  This breaks
702      dw2_lookup_symbol: It assumes that if the index says symbol X lives
703      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
704      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
705      we need to look in TU Z to find X.  Fortunately, this is akin to
706      DW_TAG_imported_unit, so we just use the same mechanism: For
707      .gdb_index version <=7 this also records the TUs that the CU referred
708      to.  Concurrently with this change gdb was modified to emit version 8
709      indices so we only pay a price for gold generated indices.
710      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
711   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
712 };
713
714 /* Entry in the signatured_types hash table.  */
715
716 struct signatured_type
717 {
718   /* The "per_cu" object of this type.
719      This struct is used iff per_cu.is_debug_types.
720      N.B.: This is the first member so that it's easy to convert pointers
721      between them.  */
722   struct dwarf2_per_cu_data per_cu;
723
724   /* The type's signature.  */
725   ULONGEST signature;
726
727   /* Offset in the TU of the type's DIE, as read from the TU header.
728      If this TU is a DWO stub and the definition lives in a DWO file
729      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
730   cu_offset type_offset_in_tu;
731
732   /* Offset in the section of the type's DIE.
733      If the definition lives in a DWO file, this is the offset in the
734      .debug_types.dwo section.
735      The value is zero until the actual value is known.
736      Zero is otherwise not a valid section offset.  */
737   sect_offset type_offset_in_section;
738
739   /* Type units are grouped by their DW_AT_stmt_list entry so that they
740      can share them.  This points to the containing symtab.  */
741   struct type_unit_group *type_unit_group;
742
743   /* The type.
744      The first time we encounter this type we fully read it in and install it
745      in the symbol tables.  Subsequent times we only need the type.  */
746   struct type *type;
747
748   /* Containing DWO unit.
749      This field is valid iff per_cu.reading_dwo_directly.  */
750   struct dwo_unit *dwo_unit;
751 };
752
753 typedef struct signatured_type *sig_type_ptr;
754 DEF_VEC_P (sig_type_ptr);
755
756 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
757    This includes type_unit_group and quick_file_names.  */
758
759 struct stmt_list_hash
760 {
761   /* The DWO unit this table is from or NULL if there is none.  */
762   struct dwo_unit *dwo_unit;
763
764   /* Offset in .debug_line or .debug_line.dwo.  */
765   sect_offset line_sect_off;
766 };
767
768 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
769    an object of this type.  */
770
771 struct type_unit_group
772 {
773   /* dwarf2read.c's main "handle" on a TU symtab.
774      To simplify things we create an artificial CU that "includes" all the
775      type units using this stmt_list so that the rest of the code still has
776      a "per_cu" handle on the symtab.
777      This PER_CU is recognized by having no section.  */
778 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
779   struct dwarf2_per_cu_data per_cu;
780
781   /* The TUs that share this DW_AT_stmt_list entry.
782      This is added to while parsing type units to build partial symtabs,
783      and is deleted afterwards and not used again.  */
784   VEC (sig_type_ptr) *tus;
785
786   /* The compunit symtab.
787      Type units in a group needn't all be defined in the same source file,
788      so we create an essentially anonymous symtab as the compunit symtab.  */
789   struct compunit_symtab *compunit_symtab;
790
791   /* The data used to construct the hash key.  */
792   struct stmt_list_hash hash;
793
794   /* The number of symtabs from the line header.
795      The value here must match line_header.num_file_names.  */
796   unsigned int num_symtabs;
797
798   /* The symbol tables for this TU (obtained from the files listed in
799      DW_AT_stmt_list).
800      WARNING: The order of entries here must match the order of entries
801      in the line header.  After the first TU using this type_unit_group, the
802      line header for the subsequent TUs is recreated from this.  This is done
803      because we need to use the same symtabs for each TU using the same
804      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
805      there's no guarantee the line header doesn't have duplicate entries.  */
806   struct symtab **symtabs;
807 };
808
809 /* These sections are what may appear in a (real or virtual) DWO file.  */
810
811 struct dwo_sections
812 {
813   struct dwarf2_section_info abbrev;
814   struct dwarf2_section_info line;
815   struct dwarf2_section_info loc;
816   struct dwarf2_section_info loclists;
817   struct dwarf2_section_info macinfo;
818   struct dwarf2_section_info macro;
819   struct dwarf2_section_info str;
820   struct dwarf2_section_info str_offsets;
821   /* In the case of a virtual DWO file, these two are unused.  */
822   struct dwarf2_section_info info;
823   VEC (dwarf2_section_info_def) *types;
824 };
825
826 /* CUs/TUs in DWP/DWO files.  */
827
828 struct dwo_unit
829 {
830   /* Backlink to the containing struct dwo_file.  */
831   struct dwo_file *dwo_file;
832
833   /* The "id" that distinguishes this CU/TU.
834      .debug_info calls this "dwo_id", .debug_types calls this "signature".
835      Since signatures came first, we stick with it for consistency.  */
836   ULONGEST signature;
837
838   /* The section this CU/TU lives in, in the DWO file.  */
839   struct dwarf2_section_info *section;
840
841   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
842   sect_offset sect_off;
843   unsigned int length;
844
845   /* For types, offset in the type's DIE of the type defined by this TU.  */
846   cu_offset type_offset_in_tu;
847 };
848
849 /* include/dwarf2.h defines the DWP section codes.
850    It defines a max value but it doesn't define a min value, which we
851    use for error checking, so provide one.  */
852
853 enum dwp_v2_section_ids
854 {
855   DW_SECT_MIN = 1
856 };
857
858 /* Data for one DWO file.
859
860    This includes virtual DWO files (a virtual DWO file is a DWO file as it
861    appears in a DWP file).  DWP files don't really have DWO files per se -
862    comdat folding of types "loses" the DWO file they came from, and from
863    a high level view DWP files appear to contain a mass of random types.
864    However, to maintain consistency with the non-DWP case we pretend DWP
865    files contain virtual DWO files, and we assign each TU with one virtual
866    DWO file (generally based on the line and abbrev section offsets -
867    a heuristic that seems to work in practice).  */
868
869 struct dwo_file
870 {
871   /* The DW_AT_GNU_dwo_name attribute.
872      For virtual DWO files the name is constructed from the section offsets
873      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
874      from related CU+TUs.  */
875   const char *dwo_name;
876
877   /* The DW_AT_comp_dir attribute.  */
878   const char *comp_dir;
879
880   /* The bfd, when the file is open.  Otherwise this is NULL.
881      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
882   bfd *dbfd;
883
884   /* The sections that make up this DWO file.
885      Remember that for virtual DWO files in DWP V2, these are virtual
886      sections (for lack of a better name).  */
887   struct dwo_sections sections;
888
889   /* The CUs in the file.
890      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
891      an extension to handle LLVM's Link Time Optimization output (where
892      multiple source files may be compiled into a single object/dwo pair). */
893   htab_t cus;
894
895   /* Table of TUs in the file.
896      Each element is a struct dwo_unit.  */
897   htab_t tus;
898 };
899
900 /* These sections are what may appear in a DWP file.  */
901
902 struct dwp_sections
903 {
904   /* These are used by both DWP version 1 and 2.  */
905   struct dwarf2_section_info str;
906   struct dwarf2_section_info cu_index;
907   struct dwarf2_section_info tu_index;
908
909   /* These are only used by DWP version 2 files.
910      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
911      sections are referenced by section number, and are not recorded here.
912      In DWP version 2 there is at most one copy of all these sections, each
913      section being (effectively) comprised of the concatenation of all of the
914      individual sections that exist in the version 1 format.
915      To keep the code simple we treat each of these concatenated pieces as a
916      section itself (a virtual section?).  */
917   struct dwarf2_section_info abbrev;
918   struct dwarf2_section_info info;
919   struct dwarf2_section_info line;
920   struct dwarf2_section_info loc;
921   struct dwarf2_section_info macinfo;
922   struct dwarf2_section_info macro;
923   struct dwarf2_section_info str_offsets;
924   struct dwarf2_section_info types;
925 };
926
927 /* These sections are what may appear in a virtual DWO file in DWP version 1.
928    A virtual DWO file is a DWO file as it appears in a DWP file.  */
929
930 struct virtual_v1_dwo_sections
931 {
932   struct dwarf2_section_info abbrev;
933   struct dwarf2_section_info line;
934   struct dwarf2_section_info loc;
935   struct dwarf2_section_info macinfo;
936   struct dwarf2_section_info macro;
937   struct dwarf2_section_info str_offsets;
938   /* Each DWP hash table entry records one CU or one TU.
939      That is recorded here, and copied to dwo_unit.section.  */
940   struct dwarf2_section_info info_or_types;
941 };
942
943 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
944    In version 2, the sections of the DWO files are concatenated together
945    and stored in one section of that name.  Thus each ELF section contains
946    several "virtual" sections.  */
947
948 struct virtual_v2_dwo_sections
949 {
950   bfd_size_type abbrev_offset;
951   bfd_size_type abbrev_size;
952
953   bfd_size_type line_offset;
954   bfd_size_type line_size;
955
956   bfd_size_type loc_offset;
957   bfd_size_type loc_size;
958
959   bfd_size_type macinfo_offset;
960   bfd_size_type macinfo_size;
961
962   bfd_size_type macro_offset;
963   bfd_size_type macro_size;
964
965   bfd_size_type str_offsets_offset;
966   bfd_size_type str_offsets_size;
967
968   /* Each DWP hash table entry records one CU or one TU.
969      That is recorded here, and copied to dwo_unit.section.  */
970   bfd_size_type info_or_types_offset;
971   bfd_size_type info_or_types_size;
972 };
973
974 /* Contents of DWP hash tables.  */
975
976 struct dwp_hash_table
977 {
978   uint32_t version, nr_columns;
979   uint32_t nr_units, nr_slots;
980   const gdb_byte *hash_table, *unit_table;
981   union
982   {
983     struct
984     {
985       const gdb_byte *indices;
986     } v1;
987     struct
988     {
989       /* This is indexed by column number and gives the id of the section
990          in that column.  */
991 #define MAX_NR_V2_DWO_SECTIONS \
992   (1 /* .debug_info or .debug_types */ \
993    + 1 /* .debug_abbrev */ \
994    + 1 /* .debug_line */ \
995    + 1 /* .debug_loc */ \
996    + 1 /* .debug_str_offsets */ \
997    + 1 /* .debug_macro or .debug_macinfo */)
998       int section_ids[MAX_NR_V2_DWO_SECTIONS];
999       const gdb_byte *offsets;
1000       const gdb_byte *sizes;
1001     } v2;
1002   } section_pool;
1003 };
1004
1005 /* Data for one DWP file.  */
1006
1007 struct dwp_file
1008 {
1009   /* Name of the file.  */
1010   const char *name;
1011
1012   /* File format version.  */
1013   int version;
1014
1015   /* The bfd.  */
1016   bfd *dbfd;
1017
1018   /* Section info for this file.  */
1019   struct dwp_sections sections;
1020
1021   /* Table of CUs in the file.  */
1022   const struct dwp_hash_table *cus;
1023
1024   /* Table of TUs in the file.  */
1025   const struct dwp_hash_table *tus;
1026
1027   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1028   htab_t loaded_cus;
1029   htab_t loaded_tus;
1030
1031   /* Table to map ELF section numbers to their sections.
1032      This is only needed for the DWP V1 file format.  */
1033   unsigned int num_sections;
1034   asection **elf_sections;
1035 };
1036
1037 /* This represents a '.dwz' file.  */
1038
1039 struct dwz_file
1040 {
1041   /* A dwz file can only contain a few sections.  */
1042   struct dwarf2_section_info abbrev;
1043   struct dwarf2_section_info info;
1044   struct dwarf2_section_info str;
1045   struct dwarf2_section_info line;
1046   struct dwarf2_section_info macro;
1047   struct dwarf2_section_info gdb_index;
1048
1049   /* The dwz's BFD.  */
1050   bfd *dwz_bfd;
1051 };
1052
1053 /* Struct used to pass misc. parameters to read_die_and_children, et
1054    al.  which are used for both .debug_info and .debug_types dies.
1055    All parameters here are unchanging for the life of the call.  This
1056    struct exists to abstract away the constant parameters of die reading.  */
1057
1058 struct die_reader_specs
1059 {
1060   /* The bfd of die_section.  */
1061   bfd* abfd;
1062
1063   /* The CU of the DIE we are parsing.  */
1064   struct dwarf2_cu *cu;
1065
1066   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1067   struct dwo_file *dwo_file;
1068
1069   /* The section the die comes from.
1070      This is either .debug_info or .debug_types, or the .dwo variants.  */
1071   struct dwarf2_section_info *die_section;
1072
1073   /* die_section->buffer.  */
1074   const gdb_byte *buffer;
1075
1076   /* The end of the buffer.  */
1077   const gdb_byte *buffer_end;
1078
1079   /* The value of the DW_AT_comp_dir attribute.  */
1080   const char *comp_dir;
1081 };
1082
1083 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1084 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1085                                       const gdb_byte *info_ptr,
1086                                       struct die_info *comp_unit_die,
1087                                       int has_children,
1088                                       void *data);
1089
1090 /* A 1-based directory index.  This is a strong typedef to prevent
1091    accidentally using a directory index as a 0-based index into an
1092    array/vector.  */
1093 enum class dir_index : unsigned int {};
1094
1095 /* Likewise, a 1-based file name index.  */
1096 enum class file_name_index : unsigned int {};
1097
1098 struct file_entry
1099 {
1100   file_entry () = default;
1101
1102   file_entry (const char *name_, dir_index d_index_,
1103               unsigned int mod_time_, unsigned int length_)
1104     : name (name_),
1105       d_index (d_index_),
1106       mod_time (mod_time_),
1107       length (length_)
1108   {}
1109
1110   /* Return the include directory at D_INDEX stored in LH.  Returns
1111      NULL if D_INDEX is out of bounds.  */
1112   const char *include_dir (const line_header *lh) const;
1113
1114   /* The file name.  Note this is an observing pointer.  The memory is
1115      owned by debug_line_buffer.  */
1116   const char *name {};
1117
1118   /* The directory index (1-based).  */
1119   dir_index d_index {};
1120
1121   unsigned int mod_time {};
1122
1123   unsigned int length {};
1124
1125   /* True if referenced by the Line Number Program.  */
1126   bool included_p {};
1127
1128   /* The associated symbol table, if any.  */
1129   struct symtab *symtab {};
1130 };
1131
1132 /* The line number information for a compilation unit (found in the
1133    .debug_line section) begins with a "statement program header",
1134    which contains the following information.  */
1135 struct line_header
1136 {
1137   line_header ()
1138     : offset_in_dwz {}
1139   {}
1140
1141   /* Add an entry to the include directory table.  */
1142   void add_include_dir (const char *include_dir);
1143
1144   /* Add an entry to the file name table.  */
1145   void add_file_name (const char *name, dir_index d_index,
1146                       unsigned int mod_time, unsigned int length);
1147
1148   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1149      is out of bounds.  */
1150   const char *include_dir_at (dir_index index) const
1151   {
1152     /* Convert directory index number (1-based) to vector index
1153        (0-based).  */
1154     size_t vec_index = to_underlying (index) - 1;
1155
1156     if (vec_index >= include_dirs.size ())
1157       return NULL;
1158     return include_dirs[vec_index];
1159   }
1160
1161   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1162      is out of bounds.  */
1163   file_entry *file_name_at (file_name_index index)
1164   {
1165     /* Convert file name index number (1-based) to vector index
1166        (0-based).  */
1167     size_t vec_index = to_underlying (index) - 1;
1168
1169     if (vec_index >= file_names.size ())
1170       return NULL;
1171     return &file_names[vec_index];
1172   }
1173
1174   /* Const version of the above.  */
1175   const file_entry *file_name_at (unsigned int index) const
1176   {
1177     if (index >= file_names.size ())
1178       return NULL;
1179     return &file_names[index];
1180   }
1181
1182   /* Offset of line number information in .debug_line section.  */
1183   sect_offset sect_off {};
1184
1185   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1186   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1187
1188   unsigned int total_length {};
1189   unsigned short version {};
1190   unsigned int header_length {};
1191   unsigned char minimum_instruction_length {};
1192   unsigned char maximum_ops_per_instruction {};
1193   unsigned char default_is_stmt {};
1194   int line_base {};
1195   unsigned char line_range {};
1196   unsigned char opcode_base {};
1197
1198   /* standard_opcode_lengths[i] is the number of operands for the
1199      standard opcode whose value is i.  This means that
1200      standard_opcode_lengths[0] is unused, and the last meaningful
1201      element is standard_opcode_lengths[opcode_base - 1].  */
1202   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1203
1204   /* The include_directories table.  Note these are observing
1205      pointers.  The memory is owned by debug_line_buffer.  */
1206   std::vector<const char *> include_dirs;
1207
1208   /* The file_names table.  */
1209   std::vector<file_entry> file_names;
1210
1211   /* The start and end of the statement program following this
1212      header.  These point into dwarf2_per_objfile->line_buffer.  */
1213   const gdb_byte *statement_program_start {}, *statement_program_end {};
1214 };
1215
1216 typedef std::unique_ptr<line_header> line_header_up;
1217
1218 const char *
1219 file_entry::include_dir (const line_header *lh) const
1220 {
1221   return lh->include_dir_at (d_index);
1222 }
1223
1224 /* When we construct a partial symbol table entry we only
1225    need this much information.  */
1226 struct partial_die_info
1227   {
1228     /* Offset of this DIE.  */
1229     sect_offset sect_off;
1230
1231     /* DWARF-2 tag for this DIE.  */
1232     ENUM_BITFIELD(dwarf_tag) tag : 16;
1233
1234     /* Assorted flags describing the data found in this DIE.  */
1235     unsigned int has_children : 1;
1236     unsigned int is_external : 1;
1237     unsigned int is_declaration : 1;
1238     unsigned int has_type : 1;
1239     unsigned int has_specification : 1;
1240     unsigned int has_pc_info : 1;
1241     unsigned int may_be_inlined : 1;
1242
1243     /* This DIE has been marked DW_AT_main_subprogram.  */
1244     unsigned int main_subprogram : 1;
1245
1246     /* Flag set if the SCOPE field of this structure has been
1247        computed.  */
1248     unsigned int scope_set : 1;
1249
1250     /* Flag set if the DIE has a byte_size attribute.  */
1251     unsigned int has_byte_size : 1;
1252
1253     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1254     unsigned int has_const_value : 1;
1255
1256     /* Flag set if any of the DIE's children are template arguments.  */
1257     unsigned int has_template_arguments : 1;
1258
1259     /* Flag set if fixup_partial_die has been called on this die.  */
1260     unsigned int fixup_called : 1;
1261
1262     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1263     unsigned int is_dwz : 1;
1264
1265     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1266     unsigned int spec_is_dwz : 1;
1267
1268     /* The name of this DIE.  Normally the value of DW_AT_name, but
1269        sometimes a default name for unnamed DIEs.  */
1270     const char *name;
1271
1272     /* The linkage name, if present.  */
1273     const char *linkage_name;
1274
1275     /* The scope to prepend to our children.  This is generally
1276        allocated on the comp_unit_obstack, so will disappear
1277        when this compilation unit leaves the cache.  */
1278     const char *scope;
1279
1280     /* Some data associated with the partial DIE.  The tag determines
1281        which field is live.  */
1282     union
1283     {
1284       /* The location description associated with this DIE, if any.  */
1285       struct dwarf_block *locdesc;
1286       /* The offset of an import, for DW_TAG_imported_unit.  */
1287       sect_offset sect_off;
1288     } d;
1289
1290     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1291     CORE_ADDR lowpc;
1292     CORE_ADDR highpc;
1293
1294     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1295        DW_AT_sibling, if any.  */
1296     /* NOTE: This member isn't strictly necessary, read_partial_die could
1297        return DW_AT_sibling values to its caller load_partial_dies.  */
1298     const gdb_byte *sibling;
1299
1300     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1301        DW_AT_specification (or DW_AT_abstract_origin or
1302        DW_AT_extension).  */
1303     sect_offset spec_offset;
1304
1305     /* Pointers to this DIE's parent, first child, and next sibling,
1306        if any.  */
1307     struct partial_die_info *die_parent, *die_child, *die_sibling;
1308   };
1309
1310 /* This data structure holds the information of an abbrev.  */
1311 struct abbrev_info
1312   {
1313     unsigned int number;        /* number identifying abbrev */
1314     enum dwarf_tag tag;         /* dwarf tag */
1315     unsigned short has_children;                /* boolean */
1316     unsigned short num_attrs;   /* number of attributes */
1317     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1318     struct abbrev_info *next;   /* next in chain */
1319   };
1320
1321 struct attr_abbrev
1322   {
1323     ENUM_BITFIELD(dwarf_attribute) name : 16;
1324     ENUM_BITFIELD(dwarf_form) form : 16;
1325
1326     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1327     LONGEST implicit_const;
1328   };
1329
1330 /* Size of abbrev_table.abbrev_hash_table.  */
1331 #define ABBREV_HASH_SIZE 121
1332
1333 /* Top level data structure to contain an abbreviation table.  */
1334
1335 struct abbrev_table
1336 {
1337   /* Where the abbrev table came from.
1338      This is used as a sanity check when the table is used.  */
1339   sect_offset sect_off;
1340
1341   /* Storage for the abbrev table.  */
1342   struct obstack abbrev_obstack;
1343
1344   /* Hash table of abbrevs.
1345      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1346      It could be statically allocated, but the previous code didn't so we
1347      don't either.  */
1348   struct abbrev_info **abbrevs;
1349 };
1350
1351 /* Attributes have a name and a value.  */
1352 struct attribute
1353   {
1354     ENUM_BITFIELD(dwarf_attribute) name : 16;
1355     ENUM_BITFIELD(dwarf_form) form : 15;
1356
1357     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1358        field should be in u.str (existing only for DW_STRING) but it is kept
1359        here for better struct attribute alignment.  */
1360     unsigned int string_is_canonical : 1;
1361
1362     union
1363       {
1364         const char *str;
1365         struct dwarf_block *blk;
1366         ULONGEST unsnd;
1367         LONGEST snd;
1368         CORE_ADDR addr;
1369         ULONGEST signature;
1370       }
1371     u;
1372   };
1373
1374 /* This data structure holds a complete die structure.  */
1375 struct die_info
1376   {
1377     /* DWARF-2 tag for this DIE.  */
1378     ENUM_BITFIELD(dwarf_tag) tag : 16;
1379
1380     /* Number of attributes */
1381     unsigned char num_attrs;
1382
1383     /* True if we're presently building the full type name for the
1384        type derived from this DIE.  */
1385     unsigned char building_fullname : 1;
1386
1387     /* True if this die is in process.  PR 16581.  */
1388     unsigned char in_process : 1;
1389
1390     /* Abbrev number */
1391     unsigned int abbrev;
1392
1393     /* Offset in .debug_info or .debug_types section.  */
1394     sect_offset sect_off;
1395
1396     /* The dies in a compilation unit form an n-ary tree.  PARENT
1397        points to this die's parent; CHILD points to the first child of
1398        this node; and all the children of a given node are chained
1399        together via their SIBLING fields.  */
1400     struct die_info *child;     /* Its first child, if any.  */
1401     struct die_info *sibling;   /* Its next sibling, if any.  */
1402     struct die_info *parent;    /* Its parent, if any.  */
1403
1404     /* An array of attributes, with NUM_ATTRS elements.  There may be
1405        zero, but it's not common and zero-sized arrays are not
1406        sufficiently portable C.  */
1407     struct attribute attrs[1];
1408   };
1409
1410 /* Get at parts of an attribute structure.  */
1411
1412 #define DW_STRING(attr)    ((attr)->u.str)
1413 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1414 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1415 #define DW_BLOCK(attr)     ((attr)->u.blk)
1416 #define DW_SND(attr)       ((attr)->u.snd)
1417 #define DW_ADDR(attr)      ((attr)->u.addr)
1418 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1419
1420 /* Blocks are a bunch of untyped bytes.  */
1421 struct dwarf_block
1422   {
1423     size_t size;
1424
1425     /* Valid only if SIZE is not zero.  */
1426     const gdb_byte *data;
1427   };
1428
1429 #ifndef ATTR_ALLOC_CHUNK
1430 #define ATTR_ALLOC_CHUNK 4
1431 #endif
1432
1433 /* Allocate fields for structs, unions and enums in this size.  */
1434 #ifndef DW_FIELD_ALLOC_CHUNK
1435 #define DW_FIELD_ALLOC_CHUNK 4
1436 #endif
1437
1438 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1439    but this would require a corresponding change in unpack_field_as_long
1440    and friends.  */
1441 static int bits_per_byte = 8;
1442
1443 struct nextfield
1444 {
1445   struct nextfield *next;
1446   int accessibility;
1447   int virtuality;
1448   struct field field;
1449 };
1450
1451 struct nextfnfield
1452 {
1453   struct nextfnfield *next;
1454   struct fn_field fnfield;
1455 };
1456
1457 struct fnfieldlist
1458 {
1459   const char *name;
1460   int length;
1461   struct nextfnfield *head;
1462 };
1463
1464 struct typedef_field_list
1465 {
1466   struct typedef_field field;
1467   struct typedef_field_list *next;
1468 };
1469
1470 /* The routines that read and process dies for a C struct or C++ class
1471    pass lists of data member fields and lists of member function fields
1472    in an instance of a field_info structure, as defined below.  */
1473 struct field_info
1474   {
1475     /* List of data member and baseclasses fields.  */
1476     struct nextfield *fields, *baseclasses;
1477
1478     /* Number of fields (including baseclasses).  */
1479     int nfields;
1480
1481     /* Number of baseclasses.  */
1482     int nbaseclasses;
1483
1484     /* Set if the accesibility of one of the fields is not public.  */
1485     int non_public_fields;
1486
1487     /* Member function fieldlist array, contains name of possibly overloaded
1488        member function, number of overloaded member functions and a pointer
1489        to the head of the member function field chain.  */
1490     struct fnfieldlist *fnfieldlists;
1491
1492     /* Number of entries in the fnfieldlists array.  */
1493     int nfnfields;
1494
1495     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1496        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1497     struct typedef_field_list *typedef_field_list;
1498     unsigned typedef_field_list_count;
1499   };
1500
1501 /* One item on the queue of compilation units to read in full symbols
1502    for.  */
1503 struct dwarf2_queue_item
1504 {
1505   struct dwarf2_per_cu_data *per_cu;
1506   enum language pretend_language;
1507   struct dwarf2_queue_item *next;
1508 };
1509
1510 /* The current queue.  */
1511 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1512
1513 /* Loaded secondary compilation units are kept in memory until they
1514    have not been referenced for the processing of this many
1515    compilation units.  Set this to zero to disable caching.  Cache
1516    sizes of up to at least twenty will improve startup time for
1517    typical inter-CU-reference binaries, at an obvious memory cost.  */
1518 static int dwarf_max_cache_age = 5;
1519 static void
1520 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1521                           struct cmd_list_element *c, const char *value)
1522 {
1523   fprintf_filtered (file, _("The upper bound on the age of cached "
1524                             "DWARF compilation units is %s.\n"),
1525                     value);
1526 }
1527 \f
1528 /* local function prototypes */
1529
1530 static const char *get_section_name (const struct dwarf2_section_info *);
1531
1532 static const char *get_section_file_name (const struct dwarf2_section_info *);
1533
1534 static void dwarf2_find_base_address (struct die_info *die,
1535                                       struct dwarf2_cu *cu);
1536
1537 static struct partial_symtab *create_partial_symtab
1538   (struct dwarf2_per_cu_data *per_cu, const char *name);
1539
1540 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1541                                         const gdb_byte *info_ptr,
1542                                         struct die_info *type_unit_die,
1543                                         int has_children, void *data);
1544
1545 static void dwarf2_build_psymtabs_hard (struct objfile *);
1546
1547 static void scan_partial_symbols (struct partial_die_info *,
1548                                   CORE_ADDR *, CORE_ADDR *,
1549                                   int, struct dwarf2_cu *);
1550
1551 static void add_partial_symbol (struct partial_die_info *,
1552                                 struct dwarf2_cu *);
1553
1554 static void add_partial_namespace (struct partial_die_info *pdi,
1555                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1556                                    int set_addrmap, struct dwarf2_cu *cu);
1557
1558 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1559                                 CORE_ADDR *highpc, int set_addrmap,
1560                                 struct dwarf2_cu *cu);
1561
1562 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1563                                      struct dwarf2_cu *cu);
1564
1565 static void add_partial_subprogram (struct partial_die_info *pdi,
1566                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1567                                     int need_pc, struct dwarf2_cu *cu);
1568
1569 static void dwarf2_read_symtab (struct partial_symtab *,
1570                                 struct objfile *);
1571
1572 static void psymtab_to_symtab_1 (struct partial_symtab *);
1573
1574 static struct abbrev_info *abbrev_table_lookup_abbrev
1575   (const struct abbrev_table *, unsigned int);
1576
1577 static struct abbrev_table *abbrev_table_read_table
1578   (struct dwarf2_section_info *, sect_offset);
1579
1580 static void abbrev_table_free (struct abbrev_table *);
1581
1582 static void abbrev_table_free_cleanup (void *);
1583
1584 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1585                                  struct dwarf2_section_info *);
1586
1587 static void dwarf2_free_abbrev_table (void *);
1588
1589 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1590
1591 static struct partial_die_info *load_partial_dies
1592   (const struct die_reader_specs *, const gdb_byte *, int);
1593
1594 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1595                                          struct partial_die_info *,
1596                                          struct abbrev_info *,
1597                                          unsigned int,
1598                                          const gdb_byte *);
1599
1600 static struct partial_die_info *find_partial_die (sect_offset, int,
1601                                                   struct dwarf2_cu *);
1602
1603 static void fixup_partial_die (struct partial_die_info *,
1604                                struct dwarf2_cu *);
1605
1606 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1607                                        struct attribute *, struct attr_abbrev *,
1608                                        const gdb_byte *);
1609
1610 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1611
1612 static int read_1_signed_byte (bfd *, const gdb_byte *);
1613
1614 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1615
1616 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1617
1618 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1619
1620 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1621                                unsigned int *);
1622
1623 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1624
1625 static LONGEST read_checked_initial_length_and_offset
1626   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1627    unsigned int *, unsigned int *);
1628
1629 static LONGEST read_offset (bfd *, const gdb_byte *,
1630                             const struct comp_unit_head *,
1631                             unsigned int *);
1632
1633 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1634
1635 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1636                                        sect_offset);
1637
1638 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1639
1640 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1641
1642 static const char *read_indirect_string (bfd *, const gdb_byte *,
1643                                          const struct comp_unit_head *,
1644                                          unsigned int *);
1645
1646 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1647                                               const struct comp_unit_head *,
1648                                               unsigned int *);
1649
1650 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1651
1652 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1653
1654 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1655                                               const gdb_byte *,
1656                                               unsigned int *);
1657
1658 static const char *read_str_index (const struct die_reader_specs *reader,
1659                                    ULONGEST str_index);
1660
1661 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1662
1663 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1664                                       struct dwarf2_cu *);
1665
1666 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1667                                                 unsigned int);
1668
1669 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1670                                        struct dwarf2_cu *cu);
1671
1672 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1673                                struct dwarf2_cu *cu);
1674
1675 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1676
1677 static struct die_info *die_specification (struct die_info *die,
1678                                            struct dwarf2_cu **);
1679
1680 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1681                                                 struct dwarf2_cu *cu);
1682
1683 static void dwarf_decode_lines (struct line_header *, const char *,
1684                                 struct dwarf2_cu *, struct partial_symtab *,
1685                                 CORE_ADDR, int decode_mapping);
1686
1687 static void dwarf2_start_subfile (const char *, const char *);
1688
1689 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1690                                                     const char *, const char *,
1691                                                     CORE_ADDR);
1692
1693 static struct symbol *new_symbol (struct die_info *, struct type *,
1694                                   struct dwarf2_cu *);
1695
1696 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1697                                        struct dwarf2_cu *, struct symbol *);
1698
1699 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1700                                 struct dwarf2_cu *);
1701
1702 static void dwarf2_const_value_attr (const struct attribute *attr,
1703                                      struct type *type,
1704                                      const char *name,
1705                                      struct obstack *obstack,
1706                                      struct dwarf2_cu *cu, LONGEST *value,
1707                                      const gdb_byte **bytes,
1708                                      struct dwarf2_locexpr_baton **baton);
1709
1710 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1711
1712 static int need_gnat_info (struct dwarf2_cu *);
1713
1714 static struct type *die_descriptive_type (struct die_info *,
1715                                           struct dwarf2_cu *);
1716
1717 static void set_descriptive_type (struct type *, struct die_info *,
1718                                   struct dwarf2_cu *);
1719
1720 static struct type *die_containing_type (struct die_info *,
1721                                          struct dwarf2_cu *);
1722
1723 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1724                                      struct dwarf2_cu *);
1725
1726 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1727
1728 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1729
1730 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1731
1732 static char *typename_concat (struct obstack *obs, const char *prefix,
1733                               const char *suffix, int physname,
1734                               struct dwarf2_cu *cu);
1735
1736 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1737
1738 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1739
1740 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1741
1742 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1743
1744 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1745
1746 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1747                                struct dwarf2_cu *, struct partial_symtab *);
1748
1749 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1750    values.  Keep the items ordered with increasing constraints compliance.  */
1751 enum pc_bounds_kind
1752 {
1753   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1754   PC_BOUNDS_NOT_PRESENT,
1755
1756   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1757      were present but they do not form a valid range of PC addresses.  */
1758   PC_BOUNDS_INVALID,
1759
1760   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1761   PC_BOUNDS_RANGES,
1762
1763   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1764   PC_BOUNDS_HIGH_LOW,
1765 };
1766
1767 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1768                                                  CORE_ADDR *, CORE_ADDR *,
1769                                                  struct dwarf2_cu *,
1770                                                  struct partial_symtab *);
1771
1772 static void get_scope_pc_bounds (struct die_info *,
1773                                  CORE_ADDR *, CORE_ADDR *,
1774                                  struct dwarf2_cu *);
1775
1776 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1777                                         CORE_ADDR, struct dwarf2_cu *);
1778
1779 static void dwarf2_add_field (struct field_info *, struct die_info *,
1780                               struct dwarf2_cu *);
1781
1782 static void dwarf2_attach_fields_to_type (struct field_info *,
1783                                           struct type *, struct dwarf2_cu *);
1784
1785 static void dwarf2_add_member_fn (struct field_info *,
1786                                   struct die_info *, struct type *,
1787                                   struct dwarf2_cu *);
1788
1789 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1790                                              struct type *,
1791                                              struct dwarf2_cu *);
1792
1793 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1794
1795 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1796
1797 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1798
1799 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1800
1801 static struct using_direct **using_directives (enum language);
1802
1803 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1804
1805 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1806
1807 static struct type *read_module_type (struct die_info *die,
1808                                       struct dwarf2_cu *cu);
1809
1810 static const char *namespace_name (struct die_info *die,
1811                                    int *is_anonymous, struct dwarf2_cu *);
1812
1813 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1814
1815 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1816
1817 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1818                                                        struct dwarf2_cu *);
1819
1820 static struct die_info *read_die_and_siblings_1
1821   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1822    struct die_info *);
1823
1824 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1825                                                const gdb_byte *info_ptr,
1826                                                const gdb_byte **new_info_ptr,
1827                                                struct die_info *parent);
1828
1829 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1830                                         struct die_info **, const gdb_byte *,
1831                                         int *, int);
1832
1833 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1834                                       struct die_info **, const gdb_byte *,
1835                                       int *);
1836
1837 static void process_die (struct die_info *, struct dwarf2_cu *);
1838
1839 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1840                                              struct obstack *);
1841
1842 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1843
1844 static const char *dwarf2_full_name (const char *name,
1845                                      struct die_info *die,
1846                                      struct dwarf2_cu *cu);
1847
1848 static const char *dwarf2_physname (const char *name, struct die_info *die,
1849                                     struct dwarf2_cu *cu);
1850
1851 static struct die_info *dwarf2_extension (struct die_info *die,
1852                                           struct dwarf2_cu **);
1853
1854 static const char *dwarf_tag_name (unsigned int);
1855
1856 static const char *dwarf_attr_name (unsigned int);
1857
1858 static const char *dwarf_form_name (unsigned int);
1859
1860 static const char *dwarf_bool_name (unsigned int);
1861
1862 static const char *dwarf_type_encoding_name (unsigned int);
1863
1864 static struct die_info *sibling_die (struct die_info *);
1865
1866 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1867
1868 static void dump_die_for_error (struct die_info *);
1869
1870 static void dump_die_1 (struct ui_file *, int level, int max_level,
1871                         struct die_info *);
1872
1873 /*static*/ void dump_die (struct die_info *, int max_level);
1874
1875 static void store_in_ref_table (struct die_info *,
1876                                 struct dwarf2_cu *);
1877
1878 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1879
1880 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1881
1882 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1883                                                const struct attribute *,
1884                                                struct dwarf2_cu **);
1885
1886 static struct die_info *follow_die_ref (struct die_info *,
1887                                         const struct attribute *,
1888                                         struct dwarf2_cu **);
1889
1890 static struct die_info *follow_die_sig (struct die_info *,
1891                                         const struct attribute *,
1892                                         struct dwarf2_cu **);
1893
1894 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1895                                          struct dwarf2_cu *);
1896
1897 static struct type *get_DW_AT_signature_type (struct die_info *,
1898                                               const struct attribute *,
1899                                               struct dwarf2_cu *);
1900
1901 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1902
1903 static void read_signatured_type (struct signatured_type *);
1904
1905 static int attr_to_dynamic_prop (const struct attribute *attr,
1906                                  struct die_info *die, struct dwarf2_cu *cu,
1907                                  struct dynamic_prop *prop);
1908
1909 /* memory allocation interface */
1910
1911 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1912
1913 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1914
1915 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1916
1917 static int attr_form_is_block (const struct attribute *);
1918
1919 static int attr_form_is_section_offset (const struct attribute *);
1920
1921 static int attr_form_is_constant (const struct attribute *);
1922
1923 static int attr_form_is_ref (const struct attribute *);
1924
1925 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1926                                    struct dwarf2_loclist_baton *baton,
1927                                    const struct attribute *attr);
1928
1929 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1930                                          struct symbol *sym,
1931                                          struct dwarf2_cu *cu,
1932                                          int is_block);
1933
1934 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1935                                      const gdb_byte *info_ptr,
1936                                      struct abbrev_info *abbrev);
1937
1938 static void free_stack_comp_unit (void *);
1939
1940 static hashval_t partial_die_hash (const void *item);
1941
1942 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1943
1944 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
1945   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
1946
1947 static void init_one_comp_unit (struct dwarf2_cu *cu,
1948                                 struct dwarf2_per_cu_data *per_cu);
1949
1950 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
1951                                    struct die_info *comp_unit_die,
1952                                    enum language pretend_language);
1953
1954 static void free_heap_comp_unit (void *);
1955
1956 static void free_cached_comp_units (void *);
1957
1958 static void age_cached_comp_units (void);
1959
1960 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
1961
1962 static struct type *set_die_type (struct die_info *, struct type *,
1963                                   struct dwarf2_cu *);
1964
1965 static void create_all_comp_units (struct objfile *);
1966
1967 static int create_all_type_units (struct objfile *);
1968
1969 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
1970                                  enum language);
1971
1972 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
1973                                     enum language);
1974
1975 static void process_full_type_unit (struct dwarf2_per_cu_data *,
1976                                     enum language);
1977
1978 static void dwarf2_add_dependence (struct dwarf2_cu *,
1979                                    struct dwarf2_per_cu_data *);
1980
1981 static void dwarf2_mark (struct dwarf2_cu *);
1982
1983 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
1984
1985 static struct type *get_die_type_at_offset (sect_offset,
1986                                             struct dwarf2_per_cu_data *);
1987
1988 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
1989
1990 static void dwarf2_release_queue (void *dummy);
1991
1992 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
1993                              enum language pretend_language);
1994
1995 static void process_queue (void);
1996
1997 /* The return type of find_file_and_directory.  Note, the enclosed
1998    string pointers are only valid while this object is valid.  */
1999
2000 struct file_and_directory
2001 {
2002   /* The filename.  This is never NULL.  */
2003   const char *name;
2004
2005   /* The compilation directory.  NULL if not known.  If we needed to
2006      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2007      points directly to the DW_AT_comp_dir string attribute owned by
2008      the obstack that owns the DIE.  */
2009   const char *comp_dir;
2010
2011   /* If we needed to build a new string for comp_dir, this is what
2012      owns the storage.  */
2013   std::string comp_dir_storage;
2014 };
2015
2016 static file_and_directory find_file_and_directory (struct die_info *die,
2017                                                    struct dwarf2_cu *cu);
2018
2019 static char *file_full_name (int file, struct line_header *lh,
2020                              const char *comp_dir);
2021
2022 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2023 enum class rcuh_kind { COMPILE, TYPE };
2024
2025 static const gdb_byte *read_and_check_comp_unit_head
2026   (struct comp_unit_head *header,
2027    struct dwarf2_section_info *section,
2028    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2029    rcuh_kind section_kind);
2030
2031 static void init_cutu_and_read_dies
2032   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2033    int use_existing_cu, int keep,
2034    die_reader_func_ftype *die_reader_func, void *data);
2035
2036 static void init_cutu_and_read_dies_simple
2037   (struct dwarf2_per_cu_data *this_cu,
2038    die_reader_func_ftype *die_reader_func, void *data);
2039
2040 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2041
2042 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2043
2044 static struct dwo_unit *lookup_dwo_unit_in_dwp
2045   (struct dwp_file *dwp_file, const char *comp_dir,
2046    ULONGEST signature, int is_debug_types);
2047
2048 static struct dwp_file *get_dwp_file (void);
2049
2050 static struct dwo_unit *lookup_dwo_comp_unit
2051   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2052
2053 static struct dwo_unit *lookup_dwo_type_unit
2054   (struct signatured_type *, const char *, const char *);
2055
2056 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2057
2058 static void free_dwo_file_cleanup (void *);
2059
2060 static void process_cu_includes (void);
2061
2062 static void check_producer (struct dwarf2_cu *cu);
2063
2064 static void free_line_header_voidp (void *arg);
2065 \f
2066 /* Various complaints about symbol reading that don't abort the process.  */
2067
2068 static void
2069 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2070 {
2071   complaint (&symfile_complaints,
2072              _("statement list doesn't fit in .debug_line section"));
2073 }
2074
2075 static void
2076 dwarf2_debug_line_missing_file_complaint (void)
2077 {
2078   complaint (&symfile_complaints,
2079              _(".debug_line section has line data without a file"));
2080 }
2081
2082 static void
2083 dwarf2_debug_line_missing_end_sequence_complaint (void)
2084 {
2085   complaint (&symfile_complaints,
2086              _(".debug_line section has line "
2087                "program sequence without an end"));
2088 }
2089
2090 static void
2091 dwarf2_complex_location_expr_complaint (void)
2092 {
2093   complaint (&symfile_complaints, _("location expression too complex"));
2094 }
2095
2096 static void
2097 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2098                                               int arg3)
2099 {
2100   complaint (&symfile_complaints,
2101              _("const value length mismatch for '%s', got %d, expected %d"),
2102              arg1, arg2, arg3);
2103 }
2104
2105 static void
2106 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2107 {
2108   complaint (&symfile_complaints,
2109              _("debug info runs off end of %s section"
2110                " [in module %s]"),
2111              get_section_name (section),
2112              get_section_file_name (section));
2113 }
2114
2115 static void
2116 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2117 {
2118   complaint (&symfile_complaints,
2119              _("macro debug info contains a "
2120                "malformed macro definition:\n`%s'"),
2121              arg1);
2122 }
2123
2124 static void
2125 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2126 {
2127   complaint (&symfile_complaints,
2128              _("invalid attribute class or form for '%s' in '%s'"),
2129              arg1, arg2);
2130 }
2131
2132 /* Hash function for line_header_hash.  */
2133
2134 static hashval_t
2135 line_header_hash (const struct line_header *ofs)
2136 {
2137   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2138 }
2139
2140 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2141
2142 static hashval_t
2143 line_header_hash_voidp (const void *item)
2144 {
2145   const struct line_header *ofs = (const struct line_header *) item;
2146
2147   return line_header_hash (ofs);
2148 }
2149
2150 /* Equality function for line_header_hash.  */
2151
2152 static int
2153 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2154 {
2155   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2156   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2157
2158   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2159           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2160 }
2161
2162 \f
2163 #if WORDS_BIGENDIAN
2164
2165 /* Convert VALUE between big- and little-endian.  */
2166 static offset_type
2167 byte_swap (offset_type value)
2168 {
2169   offset_type result;
2170
2171   result = (value & 0xff) << 24;
2172   result |= (value & 0xff00) << 8;
2173   result |= (value & 0xff0000) >> 8;
2174   result |= (value & 0xff000000) >> 24;
2175   return result;
2176 }
2177
2178 #define MAYBE_SWAP(V)  byte_swap (V)
2179
2180 #else
2181 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
2182 #endif /* WORDS_BIGENDIAN */
2183
2184 /* Read the given attribute value as an address, taking the attribute's
2185    form into account.  */
2186
2187 static CORE_ADDR
2188 attr_value_as_address (struct attribute *attr)
2189 {
2190   CORE_ADDR addr;
2191
2192   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2193     {
2194       /* Aside from a few clearly defined exceptions, attributes that
2195          contain an address must always be in DW_FORM_addr form.
2196          Unfortunately, some compilers happen to be violating this
2197          requirement by encoding addresses using other forms, such
2198          as DW_FORM_data4 for example.  For those broken compilers,
2199          we try to do our best, without any guarantee of success,
2200          to interpret the address correctly.  It would also be nice
2201          to generate a complaint, but that would require us to maintain
2202          a list of legitimate cases where a non-address form is allowed,
2203          as well as update callers to pass in at least the CU's DWARF
2204          version.  This is more overhead than what we're willing to
2205          expand for a pretty rare case.  */
2206       addr = DW_UNSND (attr);
2207     }
2208   else
2209     addr = DW_ADDR (attr);
2210
2211   return addr;
2212 }
2213
2214 /* The suffix for an index file.  */
2215 #define INDEX_SUFFIX ".gdb-index"
2216
2217 /* See declaration.  */
2218
2219 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2220                                         const dwarf2_debug_sections *names)
2221   : objfile (objfile_)
2222 {
2223   if (names == NULL)
2224     names = &dwarf2_elf_names;
2225
2226   bfd *obfd = objfile->obfd;
2227
2228   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2229     locate_sections (obfd, sec, *names);
2230 }
2231
2232 dwarf2_per_objfile::~dwarf2_per_objfile ()
2233 {
2234   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2235   free_cached_comp_units ();
2236
2237   if (quick_file_names_table)
2238     htab_delete (quick_file_names_table);
2239
2240   if (line_header_hash)
2241     htab_delete (line_header_hash);
2242
2243   /* Everything else should be on the objfile obstack.  */
2244 }
2245
2246 /* See declaration.  */
2247
2248 void
2249 dwarf2_per_objfile::free_cached_comp_units ()
2250 {
2251   dwarf2_per_cu_data *per_cu = read_in_chain;
2252   dwarf2_per_cu_data **last_chain = &read_in_chain;
2253   while (per_cu != NULL)
2254     {
2255       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2256
2257       free_heap_comp_unit (per_cu->cu);
2258       *last_chain = next_cu;
2259       per_cu = next_cu;
2260     }
2261 }
2262
2263 /* Try to locate the sections we need for DWARF 2 debugging
2264    information and return true if we have enough to do something.
2265    NAMES points to the dwarf2 section names, or is NULL if the standard
2266    ELF names are used.  */
2267
2268 int
2269 dwarf2_has_info (struct objfile *objfile,
2270                  const struct dwarf2_debug_sections *names)
2271 {
2272   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2273                         objfile_data (objfile, dwarf2_objfile_data_key));
2274   if (!dwarf2_per_objfile)
2275     {
2276       /* Initialize per-objfile state.  */
2277       struct dwarf2_per_objfile *data
2278         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2279
2280       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2281       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2282     }
2283   return (!dwarf2_per_objfile->info.is_virtual
2284           && dwarf2_per_objfile->info.s.section != NULL
2285           && !dwarf2_per_objfile->abbrev.is_virtual
2286           && dwarf2_per_objfile->abbrev.s.section != NULL);
2287 }
2288
2289 /* Return the containing section of virtual section SECTION.  */
2290
2291 static struct dwarf2_section_info *
2292 get_containing_section (const struct dwarf2_section_info *section)
2293 {
2294   gdb_assert (section->is_virtual);
2295   return section->s.containing_section;
2296 }
2297
2298 /* Return the bfd owner of SECTION.  */
2299
2300 static struct bfd *
2301 get_section_bfd_owner (const struct dwarf2_section_info *section)
2302 {
2303   if (section->is_virtual)
2304     {
2305       section = get_containing_section (section);
2306       gdb_assert (!section->is_virtual);
2307     }
2308   return section->s.section->owner;
2309 }
2310
2311 /* Return the bfd section of SECTION.
2312    Returns NULL if the section is not present.  */
2313
2314 static asection *
2315 get_section_bfd_section (const struct dwarf2_section_info *section)
2316 {
2317   if (section->is_virtual)
2318     {
2319       section = get_containing_section (section);
2320       gdb_assert (!section->is_virtual);
2321     }
2322   return section->s.section;
2323 }
2324
2325 /* Return the name of SECTION.  */
2326
2327 static const char *
2328 get_section_name (const struct dwarf2_section_info *section)
2329 {
2330   asection *sectp = get_section_bfd_section (section);
2331
2332   gdb_assert (sectp != NULL);
2333   return bfd_section_name (get_section_bfd_owner (section), sectp);
2334 }
2335
2336 /* Return the name of the file SECTION is in.  */
2337
2338 static const char *
2339 get_section_file_name (const struct dwarf2_section_info *section)
2340 {
2341   bfd *abfd = get_section_bfd_owner (section);
2342
2343   return bfd_get_filename (abfd);
2344 }
2345
2346 /* Return the id of SECTION.
2347    Returns 0 if SECTION doesn't exist.  */
2348
2349 static int
2350 get_section_id (const struct dwarf2_section_info *section)
2351 {
2352   asection *sectp = get_section_bfd_section (section);
2353
2354   if (sectp == NULL)
2355     return 0;
2356   return sectp->id;
2357 }
2358
2359 /* Return the flags of SECTION.
2360    SECTION (or containing section if this is a virtual section) must exist.  */
2361
2362 static int
2363 get_section_flags (const struct dwarf2_section_info *section)
2364 {
2365   asection *sectp = get_section_bfd_section (section);
2366
2367   gdb_assert (sectp != NULL);
2368   return bfd_get_section_flags (sectp->owner, sectp);
2369 }
2370
2371 /* When loading sections, we look either for uncompressed section or for
2372    compressed section names.  */
2373
2374 static int
2375 section_is_p (const char *section_name,
2376               const struct dwarf2_section_names *names)
2377 {
2378   if (names->normal != NULL
2379       && strcmp (section_name, names->normal) == 0)
2380     return 1;
2381   if (names->compressed != NULL
2382       && strcmp (section_name, names->compressed) == 0)
2383     return 1;
2384   return 0;
2385 }
2386
2387 /* See declaration.  */
2388
2389 void
2390 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2391                                      const dwarf2_debug_sections &names)
2392 {
2393   flagword aflag = bfd_get_section_flags (abfd, sectp);
2394
2395   if ((aflag & SEC_HAS_CONTENTS) == 0)
2396     {
2397     }
2398   else if (section_is_p (sectp->name, &names.info))
2399     {
2400       this->info.s.section = sectp;
2401       this->info.size = bfd_get_section_size (sectp);
2402     }
2403   else if (section_is_p (sectp->name, &names.abbrev))
2404     {
2405       this->abbrev.s.section = sectp;
2406       this->abbrev.size = bfd_get_section_size (sectp);
2407     }
2408   else if (section_is_p (sectp->name, &names.line))
2409     {
2410       this->line.s.section = sectp;
2411       this->line.size = bfd_get_section_size (sectp);
2412     }
2413   else if (section_is_p (sectp->name, &names.loc))
2414     {
2415       this->loc.s.section = sectp;
2416       this->loc.size = bfd_get_section_size (sectp);
2417     }
2418   else if (section_is_p (sectp->name, &names.loclists))
2419     {
2420       this->loclists.s.section = sectp;
2421       this->loclists.size = bfd_get_section_size (sectp);
2422     }
2423   else if (section_is_p (sectp->name, &names.macinfo))
2424     {
2425       this->macinfo.s.section = sectp;
2426       this->macinfo.size = bfd_get_section_size (sectp);
2427     }
2428   else if (section_is_p (sectp->name, &names.macro))
2429     {
2430       this->macro.s.section = sectp;
2431       this->macro.size = bfd_get_section_size (sectp);
2432     }
2433   else if (section_is_p (sectp->name, &names.str))
2434     {
2435       this->str.s.section = sectp;
2436       this->str.size = bfd_get_section_size (sectp);
2437     }
2438   else if (section_is_p (sectp->name, &names.line_str))
2439     {
2440       this->line_str.s.section = sectp;
2441       this->line_str.size = bfd_get_section_size (sectp);
2442     }
2443   else if (section_is_p (sectp->name, &names.addr))
2444     {
2445       this->addr.s.section = sectp;
2446       this->addr.size = bfd_get_section_size (sectp);
2447     }
2448   else if (section_is_p (sectp->name, &names.frame))
2449     {
2450       this->frame.s.section = sectp;
2451       this->frame.size = bfd_get_section_size (sectp);
2452     }
2453   else if (section_is_p (sectp->name, &names.eh_frame))
2454     {
2455       this->eh_frame.s.section = sectp;
2456       this->eh_frame.size = bfd_get_section_size (sectp);
2457     }
2458   else if (section_is_p (sectp->name, &names.ranges))
2459     {
2460       this->ranges.s.section = sectp;
2461       this->ranges.size = bfd_get_section_size (sectp);
2462     }
2463   else if (section_is_p (sectp->name, &names.rnglists))
2464     {
2465       this->rnglists.s.section = sectp;
2466       this->rnglists.size = bfd_get_section_size (sectp);
2467     }
2468   else if (section_is_p (sectp->name, &names.types))
2469     {
2470       struct dwarf2_section_info type_section;
2471
2472       memset (&type_section, 0, sizeof (type_section));
2473       type_section.s.section = sectp;
2474       type_section.size = bfd_get_section_size (sectp);
2475
2476       VEC_safe_push (dwarf2_section_info_def, this->types,
2477                      &type_section);
2478     }
2479   else if (section_is_p (sectp->name, &names.gdb_index))
2480     {
2481       this->gdb_index.s.section = sectp;
2482       this->gdb_index.size = bfd_get_section_size (sectp);
2483     }
2484
2485   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2486       && bfd_section_vma (abfd, sectp) == 0)
2487     this->has_section_at_zero = true;
2488 }
2489
2490 /* A helper function that decides whether a section is empty,
2491    or not present.  */
2492
2493 static int
2494 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2495 {
2496   if (section->is_virtual)
2497     return section->size == 0;
2498   return section->s.section == NULL || section->size == 0;
2499 }
2500
2501 /* Read the contents of the section INFO.
2502    OBJFILE is the main object file, but not necessarily the file where
2503    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2504    of the DWO file.
2505    If the section is compressed, uncompress it before returning.  */
2506
2507 static void
2508 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2509 {
2510   asection *sectp;
2511   bfd *abfd;
2512   gdb_byte *buf, *retbuf;
2513
2514   if (info->readin)
2515     return;
2516   info->buffer = NULL;
2517   info->readin = 1;
2518
2519   if (dwarf2_section_empty_p (info))
2520     return;
2521
2522   sectp = get_section_bfd_section (info);
2523
2524   /* If this is a virtual section we need to read in the real one first.  */
2525   if (info->is_virtual)
2526     {
2527       struct dwarf2_section_info *containing_section =
2528         get_containing_section (info);
2529
2530       gdb_assert (sectp != NULL);
2531       if ((sectp->flags & SEC_RELOC) != 0)
2532         {
2533           error (_("Dwarf Error: DWP format V2 with relocations is not"
2534                    " supported in section %s [in module %s]"),
2535                  get_section_name (info), get_section_file_name (info));
2536         }
2537       dwarf2_read_section (objfile, containing_section);
2538       /* Other code should have already caught virtual sections that don't
2539          fit.  */
2540       gdb_assert (info->virtual_offset + info->size
2541                   <= containing_section->size);
2542       /* If the real section is empty or there was a problem reading the
2543          section we shouldn't get here.  */
2544       gdb_assert (containing_section->buffer != NULL);
2545       info->buffer = containing_section->buffer + info->virtual_offset;
2546       return;
2547     }
2548
2549   /* If the section has relocations, we must read it ourselves.
2550      Otherwise we attach it to the BFD.  */
2551   if ((sectp->flags & SEC_RELOC) == 0)
2552     {
2553       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2554       return;
2555     }
2556
2557   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2558   info->buffer = buf;
2559
2560   /* When debugging .o files, we may need to apply relocations; see
2561      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2562      We never compress sections in .o files, so we only need to
2563      try this when the section is not compressed.  */
2564   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2565   if (retbuf != NULL)
2566     {
2567       info->buffer = retbuf;
2568       return;
2569     }
2570
2571   abfd = get_section_bfd_owner (info);
2572   gdb_assert (abfd != NULL);
2573
2574   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2575       || bfd_bread (buf, info->size, abfd) != info->size)
2576     {
2577       error (_("Dwarf Error: Can't read DWARF data"
2578                " in section %s [in module %s]"),
2579              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2580     }
2581 }
2582
2583 /* A helper function that returns the size of a section in a safe way.
2584    If you are positive that the section has been read before using the
2585    size, then it is safe to refer to the dwarf2_section_info object's
2586    "size" field directly.  In other cases, you must call this
2587    function, because for compressed sections the size field is not set
2588    correctly until the section has been read.  */
2589
2590 static bfd_size_type
2591 dwarf2_section_size (struct objfile *objfile,
2592                      struct dwarf2_section_info *info)
2593 {
2594   if (!info->readin)
2595     dwarf2_read_section (objfile, info);
2596   return info->size;
2597 }
2598
2599 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2600    SECTION_NAME.  */
2601
2602 void
2603 dwarf2_get_section_info (struct objfile *objfile,
2604                          enum dwarf2_section_enum sect,
2605                          asection **sectp, const gdb_byte **bufp,
2606                          bfd_size_type *sizep)
2607 {
2608   struct dwarf2_per_objfile *data
2609     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2610                                                   dwarf2_objfile_data_key);
2611   struct dwarf2_section_info *info;
2612
2613   /* We may see an objfile without any DWARF, in which case we just
2614      return nothing.  */
2615   if (data == NULL)
2616     {
2617       *sectp = NULL;
2618       *bufp = NULL;
2619       *sizep = 0;
2620       return;
2621     }
2622   switch (sect)
2623     {
2624     case DWARF2_DEBUG_FRAME:
2625       info = &data->frame;
2626       break;
2627     case DWARF2_EH_FRAME:
2628       info = &data->eh_frame;
2629       break;
2630     default:
2631       gdb_assert_not_reached ("unexpected section");
2632     }
2633
2634   dwarf2_read_section (objfile, info);
2635
2636   *sectp = get_section_bfd_section (info);
2637   *bufp = info->buffer;
2638   *sizep = info->size;
2639 }
2640
2641 /* A helper function to find the sections for a .dwz file.  */
2642
2643 static void
2644 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2645 {
2646   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2647
2648   /* Note that we only support the standard ELF names, because .dwz
2649      is ELF-only (at the time of writing).  */
2650   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2651     {
2652       dwz_file->abbrev.s.section = sectp;
2653       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2654     }
2655   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2656     {
2657       dwz_file->info.s.section = sectp;
2658       dwz_file->info.size = bfd_get_section_size (sectp);
2659     }
2660   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2661     {
2662       dwz_file->str.s.section = sectp;
2663       dwz_file->str.size = bfd_get_section_size (sectp);
2664     }
2665   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2666     {
2667       dwz_file->line.s.section = sectp;
2668       dwz_file->line.size = bfd_get_section_size (sectp);
2669     }
2670   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2671     {
2672       dwz_file->macro.s.section = sectp;
2673       dwz_file->macro.size = bfd_get_section_size (sectp);
2674     }
2675   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2676     {
2677       dwz_file->gdb_index.s.section = sectp;
2678       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2679     }
2680 }
2681
2682 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2683    there is no .gnu_debugaltlink section in the file.  Error if there
2684    is such a section but the file cannot be found.  */
2685
2686 static struct dwz_file *
2687 dwarf2_get_dwz_file (void)
2688 {
2689   char *data;
2690   struct cleanup *cleanup;
2691   const char *filename;
2692   struct dwz_file *result;
2693   bfd_size_type buildid_len_arg;
2694   size_t buildid_len;
2695   bfd_byte *buildid;
2696
2697   if (dwarf2_per_objfile->dwz_file != NULL)
2698     return dwarf2_per_objfile->dwz_file;
2699
2700   bfd_set_error (bfd_error_no_error);
2701   data = bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2702                                       &buildid_len_arg, &buildid);
2703   if (data == NULL)
2704     {
2705       if (bfd_get_error () == bfd_error_no_error)
2706         return NULL;
2707       error (_("could not read '.gnu_debugaltlink' section: %s"),
2708              bfd_errmsg (bfd_get_error ()));
2709     }
2710   cleanup = make_cleanup (xfree, data);
2711   make_cleanup (xfree, buildid);
2712
2713   buildid_len = (size_t) buildid_len_arg;
2714
2715   filename = (const char *) data;
2716
2717   std::string abs_storage;
2718   if (!IS_ABSOLUTE_PATH (filename))
2719     {
2720       gdb::unique_xmalloc_ptr<char> abs
2721         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2722
2723       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2724       filename = abs_storage.c_str ();
2725     }
2726
2727   /* First try the file name given in the section.  If that doesn't
2728      work, try to use the build-id instead.  */
2729   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2730   if (dwz_bfd != NULL)
2731     {
2732       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2733         dwz_bfd.release ();
2734     }
2735
2736   if (dwz_bfd == NULL)
2737     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2738
2739   if (dwz_bfd == NULL)
2740     error (_("could not find '.gnu_debugaltlink' file for %s"),
2741            objfile_name (dwarf2_per_objfile->objfile));
2742
2743   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2744                            struct dwz_file);
2745   result->dwz_bfd = dwz_bfd.release ();
2746
2747   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2748
2749   do_cleanups (cleanup);
2750
2751   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2752   dwarf2_per_objfile->dwz_file = result;
2753   return result;
2754 }
2755 \f
2756 /* DWARF quick_symbols_functions support.  */
2757
2758 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2759    unique line tables, so we maintain a separate table of all .debug_line
2760    derived entries to support the sharing.
2761    All the quick functions need is the list of file names.  We discard the
2762    line_header when we're done and don't need to record it here.  */
2763 struct quick_file_names
2764 {
2765   /* The data used to construct the hash key.  */
2766   struct stmt_list_hash hash;
2767
2768   /* The number of entries in file_names, real_names.  */
2769   unsigned int num_file_names;
2770
2771   /* The file names from the line table, after being run through
2772      file_full_name.  */
2773   const char **file_names;
2774
2775   /* The file names from the line table after being run through
2776      gdb_realpath.  These are computed lazily.  */
2777   const char **real_names;
2778 };
2779
2780 /* When using the index (and thus not using psymtabs), each CU has an
2781    object of this type.  This is used to hold information needed by
2782    the various "quick" methods.  */
2783 struct dwarf2_per_cu_quick_data
2784 {
2785   /* The file table.  This can be NULL if there was no file table
2786      or it's currently not read in.
2787      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2788   struct quick_file_names *file_names;
2789
2790   /* The corresponding symbol table.  This is NULL if symbols for this
2791      CU have not yet been read.  */
2792   struct compunit_symtab *compunit_symtab;
2793
2794   /* A temporary mark bit used when iterating over all CUs in
2795      expand_symtabs_matching.  */
2796   unsigned int mark : 1;
2797
2798   /* True if we've tried to read the file table and found there isn't one.
2799      There will be no point in trying to read it again next time.  */
2800   unsigned int no_file_data : 1;
2801 };
2802
2803 /* Utility hash function for a stmt_list_hash.  */
2804
2805 static hashval_t
2806 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2807 {
2808   hashval_t v = 0;
2809
2810   if (stmt_list_hash->dwo_unit != NULL)
2811     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2812   v += to_underlying (stmt_list_hash->line_sect_off);
2813   return v;
2814 }
2815
2816 /* Utility equality function for a stmt_list_hash.  */
2817
2818 static int
2819 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2820                     const struct stmt_list_hash *rhs)
2821 {
2822   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2823     return 0;
2824   if (lhs->dwo_unit != NULL
2825       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2826     return 0;
2827
2828   return lhs->line_sect_off == rhs->line_sect_off;
2829 }
2830
2831 /* Hash function for a quick_file_names.  */
2832
2833 static hashval_t
2834 hash_file_name_entry (const void *e)
2835 {
2836   const struct quick_file_names *file_data
2837     = (const struct quick_file_names *) e;
2838
2839   return hash_stmt_list_entry (&file_data->hash);
2840 }
2841
2842 /* Equality function for a quick_file_names.  */
2843
2844 static int
2845 eq_file_name_entry (const void *a, const void *b)
2846 {
2847   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2848   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2849
2850   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2851 }
2852
2853 /* Delete function for a quick_file_names.  */
2854
2855 static void
2856 delete_file_name_entry (void *e)
2857 {
2858   struct quick_file_names *file_data = (struct quick_file_names *) e;
2859   int i;
2860
2861   for (i = 0; i < file_data->num_file_names; ++i)
2862     {
2863       xfree ((void*) file_data->file_names[i]);
2864       if (file_data->real_names)
2865         xfree ((void*) file_data->real_names[i]);
2866     }
2867
2868   /* The space for the struct itself lives on objfile_obstack,
2869      so we don't free it here.  */
2870 }
2871
2872 /* Create a quick_file_names hash table.  */
2873
2874 static htab_t
2875 create_quick_file_names_table (unsigned int nr_initial_entries)
2876 {
2877   return htab_create_alloc (nr_initial_entries,
2878                             hash_file_name_entry, eq_file_name_entry,
2879                             delete_file_name_entry, xcalloc, xfree);
2880 }
2881
2882 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2883    have to be created afterwards.  You should call age_cached_comp_units after
2884    processing PER_CU->CU.  dw2_setup must have been already called.  */
2885
2886 static void
2887 load_cu (struct dwarf2_per_cu_data *per_cu)
2888 {
2889   if (per_cu->is_debug_types)
2890     load_full_type_unit (per_cu);
2891   else
2892     load_full_comp_unit (per_cu, language_minimal);
2893
2894   if (per_cu->cu == NULL)
2895     return;  /* Dummy CU.  */
2896
2897   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2898 }
2899
2900 /* Read in the symbols for PER_CU.  */
2901
2902 static void
2903 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2904 {
2905   struct cleanup *back_to;
2906
2907   /* Skip type_unit_groups, reading the type units they contain
2908      is handled elsewhere.  */
2909   if (IS_TYPE_UNIT_GROUP (per_cu))
2910     return;
2911
2912   back_to = make_cleanup (dwarf2_release_queue, NULL);
2913
2914   if (dwarf2_per_objfile->using_index
2915       ? per_cu->v.quick->compunit_symtab == NULL
2916       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2917     {
2918       queue_comp_unit (per_cu, language_minimal);
2919       load_cu (per_cu);
2920
2921       /* If we just loaded a CU from a DWO, and we're working with an index
2922          that may badly handle TUs, load all the TUs in that DWO as well.
2923          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2924       if (!per_cu->is_debug_types
2925           && per_cu->cu != NULL
2926           && per_cu->cu->dwo_unit != NULL
2927           && dwarf2_per_objfile->index_table != NULL
2928           && dwarf2_per_objfile->index_table->version <= 7
2929           /* DWP files aren't supported yet.  */
2930           && get_dwp_file () == NULL)
2931         queue_and_load_all_dwo_tus (per_cu);
2932     }
2933
2934   process_queue ();
2935
2936   /* Age the cache, releasing compilation units that have not
2937      been used recently.  */
2938   age_cached_comp_units ();
2939
2940   do_cleanups (back_to);
2941 }
2942
2943 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2944    the objfile from which this CU came.  Returns the resulting symbol
2945    table.  */
2946
2947 static struct compunit_symtab *
2948 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2949 {
2950   gdb_assert (dwarf2_per_objfile->using_index);
2951   if (!per_cu->v.quick->compunit_symtab)
2952     {
2953       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2954       scoped_restore decrementer = increment_reading_symtab ();
2955       dw2_do_instantiate_symtab (per_cu);
2956       process_cu_includes ();
2957       do_cleanups (back_to);
2958     }
2959
2960   return per_cu->v.quick->compunit_symtab;
2961 }
2962
2963 /* Return the CU/TU given its index.
2964
2965    This is intended for loops like:
2966
2967    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2968                     + dwarf2_per_objfile->n_type_units); ++i)
2969      {
2970        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2971
2972        ...;
2973      }
2974 */
2975
2976 static struct dwarf2_per_cu_data *
2977 dw2_get_cutu (int index)
2978 {
2979   if (index >= dwarf2_per_objfile->n_comp_units)
2980     {
2981       index -= dwarf2_per_objfile->n_comp_units;
2982       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2983       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2984     }
2985
2986   return dwarf2_per_objfile->all_comp_units[index];
2987 }
2988
2989 /* Return the CU given its index.
2990    This differs from dw2_get_cutu in that it's for when you know INDEX
2991    refers to a CU.  */
2992
2993 static struct dwarf2_per_cu_data *
2994 dw2_get_cu (int index)
2995 {
2996   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2997
2998   return dwarf2_per_objfile->all_comp_units[index];
2999 }
3000
3001 /* A helper for create_cus_from_index that handles a given list of
3002    CUs.  */
3003
3004 static void
3005 create_cus_from_index_list (struct objfile *objfile,
3006                             const gdb_byte *cu_list, offset_type n_elements,
3007                             struct dwarf2_section_info *section,
3008                             int is_dwz,
3009                             int base_offset)
3010 {
3011   offset_type i;
3012
3013   for (i = 0; i < n_elements; i += 2)
3014     {
3015       gdb_static_assert (sizeof (ULONGEST) >= 8);
3016
3017       sect_offset sect_off
3018         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3019       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3020       cu_list += 2 * 8;
3021
3022       dwarf2_per_cu_data *the_cu
3023         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3024                           struct dwarf2_per_cu_data);
3025       the_cu->sect_off = sect_off;
3026       the_cu->length = length;
3027       the_cu->objfile = objfile;
3028       the_cu->section = section;
3029       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3030                                         struct dwarf2_per_cu_quick_data);
3031       the_cu->is_dwz = is_dwz;
3032       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3033     }
3034 }
3035
3036 /* Read the CU list from the mapped index, and use it to create all
3037    the CU objects for this objfile.  */
3038
3039 static void
3040 create_cus_from_index (struct objfile *objfile,
3041                        const gdb_byte *cu_list, offset_type cu_list_elements,
3042                        const gdb_byte *dwz_list, offset_type dwz_elements)
3043 {
3044   struct dwz_file *dwz;
3045
3046   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3047   dwarf2_per_objfile->all_comp_units =
3048     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3049                dwarf2_per_objfile->n_comp_units);
3050
3051   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3052                               &dwarf2_per_objfile->info, 0, 0);
3053
3054   if (dwz_elements == 0)
3055     return;
3056
3057   dwz = dwarf2_get_dwz_file ();
3058   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3059                               cu_list_elements / 2);
3060 }
3061
3062 /* Create the signatured type hash table from the index.  */
3063
3064 static void
3065 create_signatured_type_table_from_index (struct objfile *objfile,
3066                                          struct dwarf2_section_info *section,
3067                                          const gdb_byte *bytes,
3068                                          offset_type elements)
3069 {
3070   offset_type i;
3071   htab_t sig_types_hash;
3072
3073   dwarf2_per_objfile->n_type_units
3074     = dwarf2_per_objfile->n_allocated_type_units
3075     = elements / 3;
3076   dwarf2_per_objfile->all_type_units =
3077     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3078
3079   sig_types_hash = allocate_signatured_type_table (objfile);
3080
3081   for (i = 0; i < elements; i += 3)
3082     {
3083       struct signatured_type *sig_type;
3084       ULONGEST signature;
3085       void **slot;
3086       cu_offset type_offset_in_tu;
3087
3088       gdb_static_assert (sizeof (ULONGEST) >= 8);
3089       sect_offset sect_off
3090         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3091       type_offset_in_tu
3092         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3093                                                 BFD_ENDIAN_LITTLE);
3094       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3095       bytes += 3 * 8;
3096
3097       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3098                                  struct signatured_type);
3099       sig_type->signature = signature;
3100       sig_type->type_offset_in_tu = type_offset_in_tu;
3101       sig_type->per_cu.is_debug_types = 1;
3102       sig_type->per_cu.section = section;
3103       sig_type->per_cu.sect_off = sect_off;
3104       sig_type->per_cu.objfile = objfile;
3105       sig_type->per_cu.v.quick
3106         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3107                           struct dwarf2_per_cu_quick_data);
3108
3109       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3110       *slot = sig_type;
3111
3112       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3113     }
3114
3115   dwarf2_per_objfile->signatured_types = sig_types_hash;
3116 }
3117
3118 /* Read the address map data from the mapped index, and use it to
3119    populate the objfile's psymtabs_addrmap.  */
3120
3121 static void
3122 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3123 {
3124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3125   const gdb_byte *iter, *end;
3126   struct addrmap *mutable_map;
3127   CORE_ADDR baseaddr;
3128
3129   auto_obstack temp_obstack;
3130
3131   mutable_map = addrmap_create_mutable (&temp_obstack);
3132
3133   iter = index->address_table;
3134   end = iter + index->address_table_size;
3135
3136   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3137
3138   while (iter < end)
3139     {
3140       ULONGEST hi, lo, cu_index;
3141       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3142       iter += 8;
3143       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3144       iter += 8;
3145       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3146       iter += 4;
3147
3148       if (lo > hi)
3149         {
3150           complaint (&symfile_complaints,
3151                      _(".gdb_index address table has invalid range (%s - %s)"),
3152                      hex_string (lo), hex_string (hi));
3153           continue;
3154         }
3155
3156       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3157         {
3158           complaint (&symfile_complaints,
3159                      _(".gdb_index address table has invalid CU number %u"),
3160                      (unsigned) cu_index);
3161           continue;
3162         }
3163
3164       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3165       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3166       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3167     }
3168
3169   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3170                                                     &objfile->objfile_obstack);
3171 }
3172
3173 /* The hash function for strings in the mapped index.  This is the same as
3174    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3175    implementation.  This is necessary because the hash function is tied to the
3176    format of the mapped index file.  The hash values do not have to match with
3177    SYMBOL_HASH_NEXT.
3178    
3179    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3180
3181 static hashval_t
3182 mapped_index_string_hash (int index_version, const void *p)
3183 {
3184   const unsigned char *str = (const unsigned char *) p;
3185   hashval_t r = 0;
3186   unsigned char c;
3187
3188   while ((c = *str++) != 0)
3189     {
3190       if (index_version >= 5)
3191         c = tolower (c);
3192       r = r * 67 + c - 113;
3193     }
3194
3195   return r;
3196 }
3197
3198 /* Find a slot in the mapped index INDEX for the object named NAME.
3199    If NAME is found, set *VEC_OUT to point to the CU vector in the
3200    constant pool and return 1.  If NAME cannot be found, return 0.  */
3201
3202 static int
3203 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3204                           offset_type **vec_out)
3205 {
3206   struct cleanup *back_to = make_cleanup (null_cleanup, 0);
3207   offset_type hash;
3208   offset_type slot, step;
3209   int (*cmp) (const char *, const char *);
3210
3211   if (current_language->la_language == language_cplus
3212       || current_language->la_language == language_fortran
3213       || current_language->la_language == language_d)
3214     {
3215       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3216          not contain any.  */
3217
3218       if (strchr (name, '(') != NULL)
3219         {
3220           char *without_params = cp_remove_params (name);
3221
3222           if (without_params != NULL)
3223             {
3224               make_cleanup (xfree, without_params);
3225               name = without_params;
3226             }
3227         }
3228     }
3229
3230   /* Index version 4 did not support case insensitive searches.  But the
3231      indices for case insensitive languages are built in lowercase, therefore
3232      simulate our NAME being searched is also lowercased.  */
3233   hash = mapped_index_string_hash ((index->version == 4
3234                                     && case_sensitivity == case_sensitive_off
3235                                     ? 5 : index->version),
3236                                    name);
3237
3238   slot = hash & (index->symbol_table_slots - 1);
3239   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3240   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3241
3242   for (;;)
3243     {
3244       /* Convert a slot number to an offset into the table.  */
3245       offset_type i = 2 * slot;
3246       const char *str;
3247       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3248         {
3249           do_cleanups (back_to);
3250           return 0;
3251         }
3252
3253       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3254       if (!cmp (name, str))
3255         {
3256           *vec_out = (offset_type *) (index->constant_pool
3257                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3258           do_cleanups (back_to);
3259           return 1;
3260         }
3261
3262       slot = (slot + step) & (index->symbol_table_slots - 1);
3263     }
3264 }
3265
3266 /* A helper function that reads the .gdb_index from SECTION and fills
3267    in MAP.  FILENAME is the name of the file containing the section;
3268    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3269    ok to use deprecated sections.
3270
3271    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3272    out parameters that are filled in with information about the CU and
3273    TU lists in the section.
3274
3275    Returns 1 if all went well, 0 otherwise.  */
3276
3277 static int
3278 read_index_from_section (struct objfile *objfile,
3279                          const char *filename,
3280                          int deprecated_ok,
3281                          struct dwarf2_section_info *section,
3282                          struct mapped_index *map,
3283                          const gdb_byte **cu_list,
3284                          offset_type *cu_list_elements,
3285                          const gdb_byte **types_list,
3286                          offset_type *types_list_elements)
3287 {
3288   const gdb_byte *addr;
3289   offset_type version;
3290   offset_type *metadata;
3291   int i;
3292
3293   if (dwarf2_section_empty_p (section))
3294     return 0;
3295
3296   /* Older elfutils strip versions could keep the section in the main
3297      executable while splitting it for the separate debug info file.  */
3298   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3299     return 0;
3300
3301   dwarf2_read_section (objfile, section);
3302
3303   addr = section->buffer;
3304   /* Version check.  */
3305   version = MAYBE_SWAP (*(offset_type *) addr);
3306   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3307      causes the index to behave very poorly for certain requests.  Version 3
3308      contained incomplete addrmap.  So, it seems better to just ignore such
3309      indices.  */
3310   if (version < 4)
3311     {
3312       static int warning_printed = 0;
3313       if (!warning_printed)
3314         {
3315           warning (_("Skipping obsolete .gdb_index section in %s."),
3316                    filename);
3317           warning_printed = 1;
3318         }
3319       return 0;
3320     }
3321   /* Index version 4 uses a different hash function than index version
3322      5 and later.
3323
3324      Versions earlier than 6 did not emit psymbols for inlined
3325      functions.  Using these files will cause GDB not to be able to
3326      set breakpoints on inlined functions by name, so we ignore these
3327      indices unless the user has done
3328      "set use-deprecated-index-sections on".  */
3329   if (version < 6 && !deprecated_ok)
3330     {
3331       static int warning_printed = 0;
3332       if (!warning_printed)
3333         {
3334           warning (_("\
3335 Skipping deprecated .gdb_index section in %s.\n\
3336 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3337 to use the section anyway."),
3338                    filename);
3339           warning_printed = 1;
3340         }
3341       return 0;
3342     }
3343   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3344      of the TU (for symbols coming from TUs),
3345      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3346      Plus gold-generated indices can have duplicate entries for global symbols,
3347      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3348      These are just performance bugs, and we can't distinguish gdb-generated
3349      indices from gold-generated ones, so issue no warning here.  */
3350
3351   /* Indexes with higher version than the one supported by GDB may be no
3352      longer backward compatible.  */
3353   if (version > 8)
3354     return 0;
3355
3356   map->version = version;
3357   map->total_size = section->size;
3358
3359   metadata = (offset_type *) (addr + sizeof (offset_type));
3360
3361   i = 0;
3362   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3363   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3364                        / 8);
3365   ++i;
3366
3367   *types_list = addr + MAYBE_SWAP (metadata[i]);
3368   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3369                            - MAYBE_SWAP (metadata[i]))
3370                           / 8);
3371   ++i;
3372
3373   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3374   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3375                              - MAYBE_SWAP (metadata[i]));
3376   ++i;
3377
3378   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3379   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3380                               - MAYBE_SWAP (metadata[i]))
3381                              / (2 * sizeof (offset_type)));
3382   ++i;
3383
3384   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3385
3386   return 1;
3387 }
3388
3389
3390 /* Read the index file.  If everything went ok, initialize the "quick"
3391    elements of all the CUs and return 1.  Otherwise, return 0.  */
3392
3393 static int
3394 dwarf2_read_index (struct objfile *objfile)
3395 {
3396   struct mapped_index local_map, *map;
3397   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3398   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3399   struct dwz_file *dwz;
3400
3401   if (!read_index_from_section (objfile, objfile_name (objfile),
3402                                 use_deprecated_index_sections,
3403                                 &dwarf2_per_objfile->gdb_index, &local_map,
3404                                 &cu_list, &cu_list_elements,
3405                                 &types_list, &types_list_elements))
3406     return 0;
3407
3408   /* Don't use the index if it's empty.  */
3409   if (local_map.symbol_table_slots == 0)
3410     return 0;
3411
3412   /* If there is a .dwz file, read it so we can get its CU list as
3413      well.  */
3414   dwz = dwarf2_get_dwz_file ();
3415   if (dwz != NULL)
3416     {
3417       struct mapped_index dwz_map;
3418       const gdb_byte *dwz_types_ignore;
3419       offset_type dwz_types_elements_ignore;
3420
3421       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3422                                     1,
3423                                     &dwz->gdb_index, &dwz_map,
3424                                     &dwz_list, &dwz_list_elements,
3425                                     &dwz_types_ignore,
3426                                     &dwz_types_elements_ignore))
3427         {
3428           warning (_("could not read '.gdb_index' section from %s; skipping"),
3429                    bfd_get_filename (dwz->dwz_bfd));
3430           return 0;
3431         }
3432     }
3433
3434   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3435                          dwz_list_elements);
3436
3437   if (types_list_elements)
3438     {
3439       struct dwarf2_section_info *section;
3440
3441       /* We can only handle a single .debug_types when we have an
3442          index.  */
3443       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3444         return 0;
3445
3446       section = VEC_index (dwarf2_section_info_def,
3447                            dwarf2_per_objfile->types, 0);
3448
3449       create_signatured_type_table_from_index (objfile, section, types_list,
3450                                                types_list_elements);
3451     }
3452
3453   create_addrmap_from_index (objfile, &local_map);
3454
3455   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3456   *map = local_map;
3457
3458   dwarf2_per_objfile->index_table = map;
3459   dwarf2_per_objfile->using_index = 1;
3460   dwarf2_per_objfile->quick_file_names_table =
3461     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3462
3463   return 1;
3464 }
3465
3466 /* A helper for the "quick" functions which sets the global
3467    dwarf2_per_objfile according to OBJFILE.  */
3468
3469 static void
3470 dw2_setup (struct objfile *objfile)
3471 {
3472   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3473                         objfile_data (objfile, dwarf2_objfile_data_key));
3474   gdb_assert (dwarf2_per_objfile);
3475 }
3476
3477 /* die_reader_func for dw2_get_file_names.  */
3478
3479 static void
3480 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3481                            const gdb_byte *info_ptr,
3482                            struct die_info *comp_unit_die,
3483                            int has_children,
3484                            void *data)
3485 {
3486   struct dwarf2_cu *cu = reader->cu;
3487   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3488   struct objfile *objfile = dwarf2_per_objfile->objfile;
3489   struct dwarf2_per_cu_data *lh_cu;
3490   struct attribute *attr;
3491   int i;
3492   void **slot;
3493   struct quick_file_names *qfn;
3494
3495   gdb_assert (! this_cu->is_debug_types);
3496
3497   /* Our callers never want to match partial units -- instead they
3498      will match the enclosing full CU.  */
3499   if (comp_unit_die->tag == DW_TAG_partial_unit)
3500     {
3501       this_cu->v.quick->no_file_data = 1;
3502       return;
3503     }
3504
3505   lh_cu = this_cu;
3506   slot = NULL;
3507
3508   line_header_up lh;
3509   sect_offset line_offset {};
3510
3511   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3512   if (attr)
3513     {
3514       struct quick_file_names find_entry;
3515
3516       line_offset = (sect_offset) DW_UNSND (attr);
3517
3518       /* We may have already read in this line header (TU line header sharing).
3519          If we have we're done.  */
3520       find_entry.hash.dwo_unit = cu->dwo_unit;
3521       find_entry.hash.line_sect_off = line_offset;
3522       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3523                              &find_entry, INSERT);
3524       if (*slot != NULL)
3525         {
3526           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3527           return;
3528         }
3529
3530       lh = dwarf_decode_line_header (line_offset, cu);
3531     }
3532   if (lh == NULL)
3533     {
3534       lh_cu->v.quick->no_file_data = 1;
3535       return;
3536     }
3537
3538   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3539   qfn->hash.dwo_unit = cu->dwo_unit;
3540   qfn->hash.line_sect_off = line_offset;
3541   gdb_assert (slot != NULL);
3542   *slot = qfn;
3543
3544   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3545
3546   qfn->num_file_names = lh->file_names.size ();
3547   qfn->file_names =
3548     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3549   for (i = 0; i < lh->file_names.size (); ++i)
3550     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3551   qfn->real_names = NULL;
3552
3553   lh_cu->v.quick->file_names = qfn;
3554 }
3555
3556 /* A helper for the "quick" functions which attempts to read the line
3557    table for THIS_CU.  */
3558
3559 static struct quick_file_names *
3560 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3561 {
3562   /* This should never be called for TUs.  */
3563   gdb_assert (! this_cu->is_debug_types);
3564   /* Nor type unit groups.  */
3565   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3566
3567   if (this_cu->v.quick->file_names != NULL)
3568     return this_cu->v.quick->file_names;
3569   /* If we know there is no line data, no point in looking again.  */
3570   if (this_cu->v.quick->no_file_data)
3571     return NULL;
3572
3573   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3574
3575   if (this_cu->v.quick->no_file_data)
3576     return NULL;
3577   return this_cu->v.quick->file_names;
3578 }
3579
3580 /* A helper for the "quick" functions which computes and caches the
3581    real path for a given file name from the line table.  */
3582
3583 static const char *
3584 dw2_get_real_path (struct objfile *objfile,
3585                    struct quick_file_names *qfn, int index)
3586 {
3587   if (qfn->real_names == NULL)
3588     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3589                                       qfn->num_file_names, const char *);
3590
3591   if (qfn->real_names[index] == NULL)
3592     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3593
3594   return qfn->real_names[index];
3595 }
3596
3597 static struct symtab *
3598 dw2_find_last_source_symtab (struct objfile *objfile)
3599 {
3600   struct compunit_symtab *cust;
3601   int index;
3602
3603   dw2_setup (objfile);
3604   index = dwarf2_per_objfile->n_comp_units - 1;
3605   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3606   if (cust == NULL)
3607     return NULL;
3608   return compunit_primary_filetab (cust);
3609 }
3610
3611 /* Traversal function for dw2_forget_cached_source_info.  */
3612
3613 static int
3614 dw2_free_cached_file_names (void **slot, void *info)
3615 {
3616   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3617
3618   if (file_data->real_names)
3619     {
3620       int i;
3621
3622       for (i = 0; i < file_data->num_file_names; ++i)
3623         {
3624           xfree ((void*) file_data->real_names[i]);
3625           file_data->real_names[i] = NULL;
3626         }
3627     }
3628
3629   return 1;
3630 }
3631
3632 static void
3633 dw2_forget_cached_source_info (struct objfile *objfile)
3634 {
3635   dw2_setup (objfile);
3636
3637   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3638                           dw2_free_cached_file_names, NULL);
3639 }
3640
3641 /* Helper function for dw2_map_symtabs_matching_filename that expands
3642    the symtabs and calls the iterator.  */
3643
3644 static int
3645 dw2_map_expand_apply (struct objfile *objfile,
3646                       struct dwarf2_per_cu_data *per_cu,
3647                       const char *name, const char *real_path,
3648                       gdb::function_view<bool (symtab *)> callback)
3649 {
3650   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3651
3652   /* Don't visit already-expanded CUs.  */
3653   if (per_cu->v.quick->compunit_symtab)
3654     return 0;
3655
3656   /* This may expand more than one symtab, and we want to iterate over
3657      all of them.  */
3658   dw2_instantiate_symtab (per_cu);
3659
3660   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3661                                     last_made, callback);
3662 }
3663
3664 /* Implementation of the map_symtabs_matching_filename method.  */
3665
3666 static bool
3667 dw2_map_symtabs_matching_filename
3668   (struct objfile *objfile, const char *name, const char *real_path,
3669    gdb::function_view<bool (symtab *)> callback)
3670 {
3671   int i;
3672   const char *name_basename = lbasename (name);
3673
3674   dw2_setup (objfile);
3675
3676   /* The rule is CUs specify all the files, including those used by
3677      any TU, so there's no need to scan TUs here.  */
3678
3679   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3680     {
3681       int j;
3682       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3683       struct quick_file_names *file_data;
3684
3685       /* We only need to look at symtabs not already expanded.  */
3686       if (per_cu->v.quick->compunit_symtab)
3687         continue;
3688
3689       file_data = dw2_get_file_names (per_cu);
3690       if (file_data == NULL)
3691         continue;
3692
3693       for (j = 0; j < file_data->num_file_names; ++j)
3694         {
3695           const char *this_name = file_data->file_names[j];
3696           const char *this_real_name;
3697
3698           if (compare_filenames_for_search (this_name, name))
3699             {
3700               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3701                                         callback))
3702                 return true;
3703               continue;
3704             }
3705
3706           /* Before we invoke realpath, which can get expensive when many
3707              files are involved, do a quick comparison of the basenames.  */
3708           if (! basenames_may_differ
3709               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3710             continue;
3711
3712           this_real_name = dw2_get_real_path (objfile, file_data, j);
3713           if (compare_filenames_for_search (this_real_name, name))
3714             {
3715               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3716                                         callback))
3717                 return true;
3718               continue;
3719             }
3720
3721           if (real_path != NULL)
3722             {
3723               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3724               gdb_assert (IS_ABSOLUTE_PATH (name));
3725               if (this_real_name != NULL
3726                   && FILENAME_CMP (real_path, this_real_name) == 0)
3727                 {
3728                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3729                                             callback))
3730                     return true;
3731                   continue;
3732                 }
3733             }
3734         }
3735     }
3736
3737   return false;
3738 }
3739
3740 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3741
3742 struct dw2_symtab_iterator
3743 {
3744   /* The internalized form of .gdb_index.  */
3745   struct mapped_index *index;
3746   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3747   int want_specific_block;
3748   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3749      Unused if !WANT_SPECIFIC_BLOCK.  */
3750   int block_index;
3751   /* The kind of symbol we're looking for.  */
3752   domain_enum domain;
3753   /* The list of CUs from the index entry of the symbol,
3754      or NULL if not found.  */
3755   offset_type *vec;
3756   /* The next element in VEC to look at.  */
3757   int next;
3758   /* The number of elements in VEC, or zero if there is no match.  */
3759   int length;
3760   /* Have we seen a global version of the symbol?
3761      If so we can ignore all further global instances.
3762      This is to work around gold/15646, inefficient gold-generated
3763      indices.  */
3764   int global_seen;
3765 };
3766
3767 /* Initialize the index symtab iterator ITER.
3768    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3769    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3770
3771 static void
3772 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3773                       struct mapped_index *index,
3774                       int want_specific_block,
3775                       int block_index,
3776                       domain_enum domain,
3777                       const char *name)
3778 {
3779   iter->index = index;
3780   iter->want_specific_block = want_specific_block;
3781   iter->block_index = block_index;
3782   iter->domain = domain;
3783   iter->next = 0;
3784   iter->global_seen = 0;
3785
3786   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3787     iter->length = MAYBE_SWAP (*iter->vec);
3788   else
3789     {
3790       iter->vec = NULL;
3791       iter->length = 0;
3792     }
3793 }
3794
3795 /* Return the next matching CU or NULL if there are no more.  */
3796
3797 static struct dwarf2_per_cu_data *
3798 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3799 {
3800   for ( ; iter->next < iter->length; ++iter->next)
3801     {
3802       offset_type cu_index_and_attrs =
3803         MAYBE_SWAP (iter->vec[iter->next + 1]);
3804       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3805       struct dwarf2_per_cu_data *per_cu;
3806       int want_static = iter->block_index != GLOBAL_BLOCK;
3807       /* This value is only valid for index versions >= 7.  */
3808       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3809       gdb_index_symbol_kind symbol_kind =
3810         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3811       /* Only check the symbol attributes if they're present.
3812          Indices prior to version 7 don't record them,
3813          and indices >= 7 may elide them for certain symbols
3814          (gold does this).  */
3815       int attrs_valid =
3816         (iter->index->version >= 7
3817          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3818
3819       /* Don't crash on bad data.  */
3820       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3821                        + dwarf2_per_objfile->n_type_units))
3822         {
3823           complaint (&symfile_complaints,
3824                      _(".gdb_index entry has bad CU index"
3825                        " [in module %s]"),
3826                      objfile_name (dwarf2_per_objfile->objfile));
3827           continue;
3828         }
3829
3830       per_cu = dw2_get_cutu (cu_index);
3831
3832       /* Skip if already read in.  */
3833       if (per_cu->v.quick->compunit_symtab)
3834         continue;
3835
3836       /* Check static vs global.  */
3837       if (attrs_valid)
3838         {
3839           if (iter->want_specific_block
3840               && want_static != is_static)
3841             continue;
3842           /* Work around gold/15646.  */
3843           if (!is_static && iter->global_seen)
3844             continue;
3845           if (!is_static)
3846             iter->global_seen = 1;
3847         }
3848
3849       /* Only check the symbol's kind if it has one.  */
3850       if (attrs_valid)
3851         {
3852           switch (iter->domain)
3853             {
3854             case VAR_DOMAIN:
3855               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3856                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3857                   /* Some types are also in VAR_DOMAIN.  */
3858                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3859                 continue;
3860               break;
3861             case STRUCT_DOMAIN:
3862               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3863                 continue;
3864               break;
3865             case LABEL_DOMAIN:
3866               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3867                 continue;
3868               break;
3869             default:
3870               break;
3871             }
3872         }
3873
3874       ++iter->next;
3875       return per_cu;
3876     }
3877
3878   return NULL;
3879 }
3880
3881 static struct compunit_symtab *
3882 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3883                    const char *name, domain_enum domain)
3884 {
3885   struct compunit_symtab *stab_best = NULL;
3886   struct mapped_index *index;
3887
3888   dw2_setup (objfile);
3889
3890   index = dwarf2_per_objfile->index_table;
3891
3892   /* index is NULL if OBJF_READNOW.  */
3893   if (index)
3894     {
3895       struct dw2_symtab_iterator iter;
3896       struct dwarf2_per_cu_data *per_cu;
3897
3898       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3899
3900       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3901         {
3902           struct symbol *sym, *with_opaque = NULL;
3903           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3904           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3905           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3906
3907           sym = block_find_symbol (block, name, domain,
3908                                    block_find_non_opaque_type_preferred,
3909                                    &with_opaque);
3910
3911           /* Some caution must be observed with overloaded functions
3912              and methods, since the index will not contain any overload
3913              information (but NAME might contain it).  */
3914
3915           if (sym != NULL
3916               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3917             return stab;
3918           if (with_opaque != NULL
3919               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3920             stab_best = stab;
3921
3922           /* Keep looking through other CUs.  */
3923         }
3924     }
3925
3926   return stab_best;
3927 }
3928
3929 static void
3930 dw2_print_stats (struct objfile *objfile)
3931 {
3932   int i, total, count;
3933
3934   dw2_setup (objfile);
3935   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3936   count = 0;
3937   for (i = 0; i < total; ++i)
3938     {
3939       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3940
3941       if (!per_cu->v.quick->compunit_symtab)
3942         ++count;
3943     }
3944   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3945   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3946 }
3947
3948 /* This dumps minimal information about the index.
3949    It is called via "mt print objfiles".
3950    One use is to verify .gdb_index has been loaded by the
3951    gdb.dwarf2/gdb-index.exp testcase.  */
3952
3953 static void
3954 dw2_dump (struct objfile *objfile)
3955 {
3956   dw2_setup (objfile);
3957   gdb_assert (dwarf2_per_objfile->using_index);
3958   printf_filtered (".gdb_index:");
3959   if (dwarf2_per_objfile->index_table != NULL)
3960     {
3961       printf_filtered (" version %d\n",
3962                        dwarf2_per_objfile->index_table->version);
3963     }
3964   else
3965     printf_filtered (" faked for \"readnow\"\n");
3966   printf_filtered ("\n");
3967 }
3968
3969 static void
3970 dw2_relocate (struct objfile *objfile,
3971               const struct section_offsets *new_offsets,
3972               const struct section_offsets *delta)
3973 {
3974   /* There's nothing to relocate here.  */
3975 }
3976
3977 static void
3978 dw2_expand_symtabs_for_function (struct objfile *objfile,
3979                                  const char *func_name)
3980 {
3981   struct mapped_index *index;
3982
3983   dw2_setup (objfile);
3984
3985   index = dwarf2_per_objfile->index_table;
3986
3987   /* index is NULL if OBJF_READNOW.  */
3988   if (index)
3989     {
3990       struct dw2_symtab_iterator iter;
3991       struct dwarf2_per_cu_data *per_cu;
3992
3993       /* Note: It doesn't matter what we pass for block_index here.  */
3994       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3995                             func_name);
3996
3997       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3998         dw2_instantiate_symtab (per_cu);
3999     }
4000 }
4001
4002 static void
4003 dw2_expand_all_symtabs (struct objfile *objfile)
4004 {
4005   int i;
4006
4007   dw2_setup (objfile);
4008
4009   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4010                    + dwarf2_per_objfile->n_type_units); ++i)
4011     {
4012       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4013
4014       dw2_instantiate_symtab (per_cu);
4015     }
4016 }
4017
4018 static void
4019 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4020                                   const char *fullname)
4021 {
4022   int i;
4023
4024   dw2_setup (objfile);
4025
4026   /* We don't need to consider type units here.
4027      This is only called for examining code, e.g. expand_line_sal.
4028      There can be an order of magnitude (or more) more type units
4029      than comp units, and we avoid them if we can.  */
4030
4031   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4032     {
4033       int j;
4034       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4035       struct quick_file_names *file_data;
4036
4037       /* We only need to look at symtabs not already expanded.  */
4038       if (per_cu->v.quick->compunit_symtab)
4039         continue;
4040
4041       file_data = dw2_get_file_names (per_cu);
4042       if (file_data == NULL)
4043         continue;
4044
4045       for (j = 0; j < file_data->num_file_names; ++j)
4046         {
4047           const char *this_fullname = file_data->file_names[j];
4048
4049           if (filename_cmp (this_fullname, fullname) == 0)
4050             {
4051               dw2_instantiate_symtab (per_cu);
4052               break;
4053             }
4054         }
4055     }
4056 }
4057
4058 static void
4059 dw2_map_matching_symbols (struct objfile *objfile,
4060                           const char * name, domain_enum domain,
4061                           int global,
4062                           int (*callback) (struct block *,
4063                                            struct symbol *, void *),
4064                           void *data, symbol_compare_ftype *match,
4065                           symbol_compare_ftype *ordered_compare)
4066 {
4067   /* Currently unimplemented; used for Ada.  The function can be called if the
4068      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4069      does not look for non-Ada symbols this function should just return.  */
4070 }
4071
4072 static void
4073 dw2_expand_symtabs_matching
4074   (struct objfile *objfile,
4075    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4076    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4077    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4078    enum search_domain kind)
4079 {
4080   int i;
4081   offset_type iter;
4082   struct mapped_index *index;
4083
4084   dw2_setup (objfile);
4085
4086   /* index_table is NULL if OBJF_READNOW.  */
4087   if (!dwarf2_per_objfile->index_table)
4088     return;
4089   index = dwarf2_per_objfile->index_table;
4090
4091   if (file_matcher != NULL)
4092     {
4093       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4094                                                 htab_eq_pointer,
4095                                                 NULL, xcalloc, xfree));
4096       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4097                                                     htab_eq_pointer,
4098                                                     NULL, xcalloc, xfree));
4099
4100       /* The rule is CUs specify all the files, including those used by
4101          any TU, so there's no need to scan TUs here.  */
4102
4103       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4104         {
4105           int j;
4106           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4107           struct quick_file_names *file_data;
4108           void **slot;
4109
4110           QUIT;
4111
4112           per_cu->v.quick->mark = 0;
4113
4114           /* We only need to look at symtabs not already expanded.  */
4115           if (per_cu->v.quick->compunit_symtab)
4116             continue;
4117
4118           file_data = dw2_get_file_names (per_cu);
4119           if (file_data == NULL)
4120             continue;
4121
4122           if (htab_find (visited_not_found.get (), file_data) != NULL)
4123             continue;
4124           else if (htab_find (visited_found.get (), file_data) != NULL)
4125             {
4126               per_cu->v.quick->mark = 1;
4127               continue;
4128             }
4129
4130           for (j = 0; j < file_data->num_file_names; ++j)
4131             {
4132               const char *this_real_name;
4133
4134               if (file_matcher (file_data->file_names[j], false))
4135                 {
4136                   per_cu->v.quick->mark = 1;
4137                   break;
4138                 }
4139
4140               /* Before we invoke realpath, which can get expensive when many
4141                  files are involved, do a quick comparison of the basenames.  */
4142               if (!basenames_may_differ
4143                   && !file_matcher (lbasename (file_data->file_names[j]),
4144                                     true))
4145                 continue;
4146
4147               this_real_name = dw2_get_real_path (objfile, file_data, j);
4148               if (file_matcher (this_real_name, false))
4149                 {
4150                   per_cu->v.quick->mark = 1;
4151                   break;
4152                 }
4153             }
4154
4155           slot = htab_find_slot (per_cu->v.quick->mark
4156                                  ? visited_found.get ()
4157                                  : visited_not_found.get (),
4158                                  file_data, INSERT);
4159           *slot = file_data;
4160         }
4161     }
4162
4163   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4164     {
4165       offset_type idx = 2 * iter;
4166       const char *name;
4167       offset_type *vec, vec_len, vec_idx;
4168       int global_seen = 0;
4169
4170       QUIT;
4171
4172       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4173         continue;
4174
4175       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4176
4177       if (!symbol_matcher (name))
4178         continue;
4179
4180       /* The name was matched, now expand corresponding CUs that were
4181          marked.  */
4182       vec = (offset_type *) (index->constant_pool
4183                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4184       vec_len = MAYBE_SWAP (vec[0]);
4185       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4186         {
4187           struct dwarf2_per_cu_data *per_cu;
4188           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4189           /* This value is only valid for index versions >= 7.  */
4190           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4191           gdb_index_symbol_kind symbol_kind =
4192             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4193           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4194           /* Only check the symbol attributes if they're present.
4195              Indices prior to version 7 don't record them,
4196              and indices >= 7 may elide them for certain symbols
4197              (gold does this).  */
4198           int attrs_valid =
4199             (index->version >= 7
4200              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4201
4202           /* Work around gold/15646.  */
4203           if (attrs_valid)
4204             {
4205               if (!is_static && global_seen)
4206                 continue;
4207               if (!is_static)
4208                 global_seen = 1;
4209             }
4210
4211           /* Only check the symbol's kind if it has one.  */
4212           if (attrs_valid)
4213             {
4214               switch (kind)
4215                 {
4216                 case VARIABLES_DOMAIN:
4217                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4218                     continue;
4219                   break;
4220                 case FUNCTIONS_DOMAIN:
4221                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4222                     continue;
4223                   break;
4224                 case TYPES_DOMAIN:
4225                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4226                     continue;
4227                   break;
4228                 default:
4229                   break;
4230                 }
4231             }
4232
4233           /* Don't crash on bad data.  */
4234           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4235                            + dwarf2_per_objfile->n_type_units))
4236             {
4237               complaint (&symfile_complaints,
4238                          _(".gdb_index entry has bad CU index"
4239                            " [in module %s]"), objfile_name (objfile));
4240               continue;
4241             }
4242
4243           per_cu = dw2_get_cutu (cu_index);
4244           if (file_matcher == NULL || per_cu->v.quick->mark)
4245             {
4246               int symtab_was_null =
4247                 (per_cu->v.quick->compunit_symtab == NULL);
4248
4249               dw2_instantiate_symtab (per_cu);
4250
4251               if (expansion_notify != NULL
4252                   && symtab_was_null
4253                   && per_cu->v.quick->compunit_symtab != NULL)
4254                 {
4255                   expansion_notify (per_cu->v.quick->compunit_symtab);
4256                 }
4257             }
4258         }
4259     }
4260 }
4261
4262 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4263    symtab.  */
4264
4265 static struct compunit_symtab *
4266 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4267                                           CORE_ADDR pc)
4268 {
4269   int i;
4270
4271   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4272       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4273     return cust;
4274
4275   if (cust->includes == NULL)
4276     return NULL;
4277
4278   for (i = 0; cust->includes[i]; ++i)
4279     {
4280       struct compunit_symtab *s = cust->includes[i];
4281
4282       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4283       if (s != NULL)
4284         return s;
4285     }
4286
4287   return NULL;
4288 }
4289
4290 static struct compunit_symtab *
4291 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4292                                   struct bound_minimal_symbol msymbol,
4293                                   CORE_ADDR pc,
4294                                   struct obj_section *section,
4295                                   int warn_if_readin)
4296 {
4297   struct dwarf2_per_cu_data *data;
4298   struct compunit_symtab *result;
4299
4300   dw2_setup (objfile);
4301
4302   if (!objfile->psymtabs_addrmap)
4303     return NULL;
4304
4305   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4306                                                      pc);
4307   if (!data)
4308     return NULL;
4309
4310   if (warn_if_readin && data->v.quick->compunit_symtab)
4311     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4312              paddress (get_objfile_arch (objfile), pc));
4313
4314   result
4315     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4316                                                 pc);
4317   gdb_assert (result != NULL);
4318   return result;
4319 }
4320
4321 static void
4322 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4323                           void *data, int need_fullname)
4324 {
4325   dw2_setup (objfile);
4326
4327   if (!dwarf2_per_objfile->filenames_cache)
4328     {
4329       dwarf2_per_objfile->filenames_cache.emplace ();
4330
4331       htab_up visited (htab_create_alloc (10,
4332                                           htab_hash_pointer, htab_eq_pointer,
4333                                           NULL, xcalloc, xfree));
4334
4335       /* The rule is CUs specify all the files, including those used
4336          by any TU, so there's no need to scan TUs here.  We can
4337          ignore file names coming from already-expanded CUs.  */
4338
4339       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4340         {
4341           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4342
4343           if (per_cu->v.quick->compunit_symtab)
4344             {
4345               void **slot = htab_find_slot (visited.get (),
4346                                             per_cu->v.quick->file_names,
4347                                             INSERT);
4348
4349               *slot = per_cu->v.quick->file_names;
4350             }
4351         }
4352
4353       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4354         {
4355           int j;
4356           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4357           struct quick_file_names *file_data;
4358           void **slot;
4359
4360           /* We only need to look at symtabs not already expanded.  */
4361           if (per_cu->v.quick->compunit_symtab)
4362             continue;
4363
4364           file_data = dw2_get_file_names (per_cu);
4365           if (file_data == NULL)
4366             continue;
4367
4368           slot = htab_find_slot (visited.get (), file_data, INSERT);
4369           if (*slot)
4370             {
4371               /* Already visited.  */
4372               continue;
4373             }
4374           *slot = file_data;
4375
4376           for (int j = 0; j < file_data->num_file_names; ++j)
4377             {
4378               const char *filename = file_data->file_names[j];
4379               dwarf2_per_objfile->filenames_cache->seen (filename);
4380             }
4381         }
4382     }
4383
4384   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4385     {
4386       gdb::unique_xmalloc_ptr<char> this_real_name;
4387
4388       if (need_fullname)
4389         this_real_name = gdb_realpath (filename);
4390       (*fun) (filename, this_real_name.get (), data);
4391     });
4392 }
4393
4394 static int
4395 dw2_has_symbols (struct objfile *objfile)
4396 {
4397   return 1;
4398 }
4399
4400 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4401 {
4402   dw2_has_symbols,
4403   dw2_find_last_source_symtab,
4404   dw2_forget_cached_source_info,
4405   dw2_map_symtabs_matching_filename,
4406   dw2_lookup_symbol,
4407   dw2_print_stats,
4408   dw2_dump,
4409   dw2_relocate,
4410   dw2_expand_symtabs_for_function,
4411   dw2_expand_all_symtabs,
4412   dw2_expand_symtabs_with_fullname,
4413   dw2_map_matching_symbols,
4414   dw2_expand_symtabs_matching,
4415   dw2_find_pc_sect_compunit_symtab,
4416   dw2_map_symbol_filenames
4417 };
4418
4419 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4420    file will use psymtabs, or 1 if using the GNU index.  */
4421
4422 int
4423 dwarf2_initialize_objfile (struct objfile *objfile)
4424 {
4425   /* If we're about to read full symbols, don't bother with the
4426      indices.  In this case we also don't care if some other debug
4427      format is making psymtabs, because they are all about to be
4428      expanded anyway.  */
4429   if ((objfile->flags & OBJF_READNOW))
4430     {
4431       int i;
4432
4433       dwarf2_per_objfile->using_index = 1;
4434       create_all_comp_units (objfile);
4435       create_all_type_units (objfile);
4436       dwarf2_per_objfile->quick_file_names_table =
4437         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4438
4439       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4440                        + dwarf2_per_objfile->n_type_units); ++i)
4441         {
4442           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4443
4444           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4445                                             struct dwarf2_per_cu_quick_data);
4446         }
4447
4448       /* Return 1 so that gdb sees the "quick" functions.  However,
4449          these functions will be no-ops because we will have expanded
4450          all symtabs.  */
4451       return 1;
4452     }
4453
4454   if (dwarf2_read_index (objfile))
4455     return 1;
4456
4457   return 0;
4458 }
4459
4460 \f
4461
4462 /* Build a partial symbol table.  */
4463
4464 void
4465 dwarf2_build_psymtabs (struct objfile *objfile)
4466 {
4467
4468   if (objfile->global_psymbols.size == 0 && objfile->static_psymbols.size == 0)
4469     {
4470       init_psymbol_list (objfile, 1024);
4471     }
4472
4473   TRY
4474     {
4475       /* This isn't really ideal: all the data we allocate on the
4476          objfile's obstack is still uselessly kept around.  However,
4477          freeing it seems unsafe.  */
4478       psymtab_discarder psymtabs (objfile);
4479       dwarf2_build_psymtabs_hard (objfile);
4480       psymtabs.keep ();
4481     }
4482   CATCH (except, RETURN_MASK_ERROR)
4483     {
4484       exception_print (gdb_stderr, except);
4485     }
4486   END_CATCH
4487 }
4488
4489 /* Return the total length of the CU described by HEADER.  */
4490
4491 static unsigned int
4492 get_cu_length (const struct comp_unit_head *header)
4493 {
4494   return header->initial_length_size + header->length;
4495 }
4496
4497 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4498
4499 static inline bool
4500 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4501 {
4502   sect_offset bottom = cu_header->sect_off;
4503   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4504
4505   return sect_off >= bottom && sect_off < top;
4506 }
4507
4508 /* Find the base address of the compilation unit for range lists and
4509    location lists.  It will normally be specified by DW_AT_low_pc.
4510    In DWARF-3 draft 4, the base address could be overridden by
4511    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4512    compilation units with discontinuous ranges.  */
4513
4514 static void
4515 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4516 {
4517   struct attribute *attr;
4518
4519   cu->base_known = 0;
4520   cu->base_address = 0;
4521
4522   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4523   if (attr)
4524     {
4525       cu->base_address = attr_value_as_address (attr);
4526       cu->base_known = 1;
4527     }
4528   else
4529     {
4530       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4531       if (attr)
4532         {
4533           cu->base_address = attr_value_as_address (attr);
4534           cu->base_known = 1;
4535         }
4536     }
4537 }
4538
4539 /* Read in the comp unit header information from the debug_info at info_ptr.
4540    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4541    NOTE: This leaves members offset, first_die_offset to be filled in
4542    by the caller.  */
4543
4544 static const gdb_byte *
4545 read_comp_unit_head (struct comp_unit_head *cu_header,
4546                      const gdb_byte *info_ptr,
4547                      struct dwarf2_section_info *section,
4548                      rcuh_kind section_kind)
4549 {
4550   int signed_addr;
4551   unsigned int bytes_read;
4552   const char *filename = get_section_file_name (section);
4553   bfd *abfd = get_section_bfd_owner (section);
4554
4555   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4556   cu_header->initial_length_size = bytes_read;
4557   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4558   info_ptr += bytes_read;
4559   cu_header->version = read_2_bytes (abfd, info_ptr);
4560   info_ptr += 2;
4561   if (cu_header->version < 5)
4562     switch (section_kind)
4563       {
4564       case rcuh_kind::COMPILE:
4565         cu_header->unit_type = DW_UT_compile;
4566         break;
4567       case rcuh_kind::TYPE:
4568         cu_header->unit_type = DW_UT_type;
4569         break;
4570       default:
4571         internal_error (__FILE__, __LINE__,
4572                         _("read_comp_unit_head: invalid section_kind"));
4573       }
4574   else
4575     {
4576       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4577                                                  (read_1_byte (abfd, info_ptr));
4578       info_ptr += 1;
4579       switch (cu_header->unit_type)
4580         {
4581         case DW_UT_compile:
4582           if (section_kind != rcuh_kind::COMPILE)
4583             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4584                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4585                    filename);
4586           break;
4587         case DW_UT_type:
4588           section_kind = rcuh_kind::TYPE;
4589           break;
4590         default:
4591           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4592                  "(is %d, should be %d or %d) [in module %s]"),
4593                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4594         }
4595
4596       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4597       info_ptr += 1;
4598     }
4599   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4600                                                           cu_header,
4601                                                           &bytes_read);
4602   info_ptr += bytes_read;
4603   if (cu_header->version < 5)
4604     {
4605       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4606       info_ptr += 1;
4607     }
4608   signed_addr = bfd_get_sign_extend_vma (abfd);
4609   if (signed_addr < 0)
4610     internal_error (__FILE__, __LINE__,
4611                     _("read_comp_unit_head: dwarf from non elf file"));
4612   cu_header->signed_addr_p = signed_addr;
4613
4614   if (section_kind == rcuh_kind::TYPE)
4615     {
4616       LONGEST type_offset;
4617
4618       cu_header->signature = read_8_bytes (abfd, info_ptr);
4619       info_ptr += 8;
4620
4621       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4622       info_ptr += bytes_read;
4623       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4624       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4625         error (_("Dwarf Error: Too big type_offset in compilation unit "
4626                "header (is %s) [in module %s]"), plongest (type_offset),
4627                filename);
4628     }
4629
4630   return info_ptr;
4631 }
4632
4633 /* Helper function that returns the proper abbrev section for
4634    THIS_CU.  */
4635
4636 static struct dwarf2_section_info *
4637 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4638 {
4639   struct dwarf2_section_info *abbrev;
4640
4641   if (this_cu->is_dwz)
4642     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4643   else
4644     abbrev = &dwarf2_per_objfile->abbrev;
4645
4646   return abbrev;
4647 }
4648
4649 /* Subroutine of read_and_check_comp_unit_head and
4650    read_and_check_type_unit_head to simplify them.
4651    Perform various error checking on the header.  */
4652
4653 static void
4654 error_check_comp_unit_head (struct comp_unit_head *header,
4655                             struct dwarf2_section_info *section,
4656                             struct dwarf2_section_info *abbrev_section)
4657 {
4658   const char *filename = get_section_file_name (section);
4659
4660   if (header->version < 2 || header->version > 5)
4661     error (_("Dwarf Error: wrong version in compilation unit header "
4662            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4663            filename);
4664
4665   if (to_underlying (header->abbrev_sect_off)
4666       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4667     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4668            "(offset 0x%x + 6) [in module %s]"),
4669            to_underlying (header->abbrev_sect_off),
4670            to_underlying (header->sect_off),
4671            filename);
4672
4673   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4674      avoid potential 32-bit overflow.  */
4675   if (((ULONGEST) header->sect_off + get_cu_length (header))
4676       > section->size)
4677     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4678            "(offset 0x%x + 0) [in module %s]"),
4679            header->length, to_underlying (header->sect_off),
4680            filename);
4681 }
4682
4683 /* Read in a CU/TU header and perform some basic error checking.
4684    The contents of the header are stored in HEADER.
4685    The result is a pointer to the start of the first DIE.  */
4686
4687 static const gdb_byte *
4688 read_and_check_comp_unit_head (struct comp_unit_head *header,
4689                                struct dwarf2_section_info *section,
4690                                struct dwarf2_section_info *abbrev_section,
4691                                const gdb_byte *info_ptr,
4692                                rcuh_kind section_kind)
4693 {
4694   const gdb_byte *beg_of_comp_unit = info_ptr;
4695   bfd *abfd = get_section_bfd_owner (section);
4696
4697   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4698
4699   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4700
4701   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4702
4703   error_check_comp_unit_head (header, section, abbrev_section);
4704
4705   return info_ptr;
4706 }
4707
4708 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4709
4710 static sect_offset
4711 read_abbrev_offset (struct dwarf2_section_info *section,
4712                     sect_offset sect_off)
4713 {
4714   bfd *abfd = get_section_bfd_owner (section);
4715   const gdb_byte *info_ptr;
4716   unsigned int initial_length_size, offset_size;
4717   uint16_t version;
4718
4719   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4720   info_ptr = section->buffer + to_underlying (sect_off);
4721   read_initial_length (abfd, info_ptr, &initial_length_size);
4722   offset_size = initial_length_size == 4 ? 4 : 8;
4723   info_ptr += initial_length_size;
4724
4725   version = read_2_bytes (abfd, info_ptr);
4726   info_ptr += 2;
4727   if (version >= 5)
4728     {
4729       /* Skip unit type and address size.  */
4730       info_ptr += 2;
4731     }
4732
4733   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4734 }
4735
4736 /* Allocate a new partial symtab for file named NAME and mark this new
4737    partial symtab as being an include of PST.  */
4738
4739 static void
4740 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4741                                struct objfile *objfile)
4742 {
4743   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4744
4745   if (!IS_ABSOLUTE_PATH (subpst->filename))
4746     {
4747       /* It shares objfile->objfile_obstack.  */
4748       subpst->dirname = pst->dirname;
4749     }
4750
4751   subpst->textlow = 0;
4752   subpst->texthigh = 0;
4753
4754   subpst->dependencies
4755     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4756   subpst->dependencies[0] = pst;
4757   subpst->number_of_dependencies = 1;
4758
4759   subpst->globals_offset = 0;
4760   subpst->n_global_syms = 0;
4761   subpst->statics_offset = 0;
4762   subpst->n_static_syms = 0;
4763   subpst->compunit_symtab = NULL;
4764   subpst->read_symtab = pst->read_symtab;
4765   subpst->readin = 0;
4766
4767   /* No private part is necessary for include psymtabs.  This property
4768      can be used to differentiate between such include psymtabs and
4769      the regular ones.  */
4770   subpst->read_symtab_private = NULL;
4771 }
4772
4773 /* Read the Line Number Program data and extract the list of files
4774    included by the source file represented by PST.  Build an include
4775    partial symtab for each of these included files.  */
4776
4777 static void
4778 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4779                                struct die_info *die,
4780                                struct partial_symtab *pst)
4781 {
4782   line_header_up lh;
4783   struct attribute *attr;
4784
4785   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4786   if (attr)
4787     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4788   if (lh == NULL)
4789     return;  /* No linetable, so no includes.  */
4790
4791   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4792   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4793 }
4794
4795 static hashval_t
4796 hash_signatured_type (const void *item)
4797 {
4798   const struct signatured_type *sig_type
4799     = (const struct signatured_type *) item;
4800
4801   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4802   return sig_type->signature;
4803 }
4804
4805 static int
4806 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4807 {
4808   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4809   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4810
4811   return lhs->signature == rhs->signature;
4812 }
4813
4814 /* Allocate a hash table for signatured types.  */
4815
4816 static htab_t
4817 allocate_signatured_type_table (struct objfile *objfile)
4818 {
4819   return htab_create_alloc_ex (41,
4820                                hash_signatured_type,
4821                                eq_signatured_type,
4822                                NULL,
4823                                &objfile->objfile_obstack,
4824                                hashtab_obstack_allocate,
4825                                dummy_obstack_deallocate);
4826 }
4827
4828 /* A helper function to add a signatured type CU to a table.  */
4829
4830 static int
4831 add_signatured_type_cu_to_table (void **slot, void *datum)
4832 {
4833   struct signatured_type *sigt = (struct signatured_type *) *slot;
4834   struct signatured_type ***datap = (struct signatured_type ***) datum;
4835
4836   **datap = sigt;
4837   ++*datap;
4838
4839   return 1;
4840 }
4841
4842 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4843    and fill them into TYPES_HTAB.  It will process only type units,
4844    therefore DW_UT_type.  */
4845
4846 static void
4847 create_debug_type_hash_table (struct dwo_file *dwo_file,
4848                               dwarf2_section_info *section, htab_t &types_htab,
4849                               rcuh_kind section_kind)
4850 {
4851   struct objfile *objfile = dwarf2_per_objfile->objfile;
4852   struct dwarf2_section_info *abbrev_section;
4853   bfd *abfd;
4854   const gdb_byte *info_ptr, *end_ptr;
4855
4856   abbrev_section = (dwo_file != NULL
4857                     ? &dwo_file->sections.abbrev
4858                     : &dwarf2_per_objfile->abbrev);
4859
4860   if (dwarf_read_debug)
4861     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4862                         get_section_name (section),
4863                         get_section_file_name (abbrev_section));
4864
4865   dwarf2_read_section (objfile, section);
4866   info_ptr = section->buffer;
4867
4868   if (info_ptr == NULL)
4869     return;
4870
4871   /* We can't set abfd until now because the section may be empty or
4872      not present, in which case the bfd is unknown.  */
4873   abfd = get_section_bfd_owner (section);
4874
4875   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4876      because we don't need to read any dies: the signature is in the
4877      header.  */
4878
4879   end_ptr = info_ptr + section->size;
4880   while (info_ptr < end_ptr)
4881     {
4882       struct signatured_type *sig_type;
4883       struct dwo_unit *dwo_tu;
4884       void **slot;
4885       const gdb_byte *ptr = info_ptr;
4886       struct comp_unit_head header;
4887       unsigned int length;
4888
4889       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4890
4891       /* Initialize it due to a false compiler warning.  */
4892       header.signature = -1;
4893       header.type_cu_offset_in_tu = (cu_offset) -1;
4894
4895       /* We need to read the type's signature in order to build the hash
4896          table, but we don't need anything else just yet.  */
4897
4898       ptr = read_and_check_comp_unit_head (&header, section,
4899                                            abbrev_section, ptr, section_kind);
4900
4901       length = get_cu_length (&header);
4902
4903       /* Skip dummy type units.  */
4904       if (ptr >= info_ptr + length
4905           || peek_abbrev_code (abfd, ptr) == 0
4906           || header.unit_type != DW_UT_type)
4907         {
4908           info_ptr += length;
4909           continue;
4910         }
4911
4912       if (types_htab == NULL)
4913         {
4914           if (dwo_file)
4915             types_htab = allocate_dwo_unit_table (objfile);
4916           else
4917             types_htab = allocate_signatured_type_table (objfile);
4918         }
4919
4920       if (dwo_file)
4921         {
4922           sig_type = NULL;
4923           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4924                                    struct dwo_unit);
4925           dwo_tu->dwo_file = dwo_file;
4926           dwo_tu->signature = header.signature;
4927           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4928           dwo_tu->section = section;
4929           dwo_tu->sect_off = sect_off;
4930           dwo_tu->length = length;
4931         }
4932       else
4933         {
4934           /* N.B.: type_offset is not usable if this type uses a DWO file.
4935              The real type_offset is in the DWO file.  */
4936           dwo_tu = NULL;
4937           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4938                                      struct signatured_type);
4939           sig_type->signature = header.signature;
4940           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4941           sig_type->per_cu.objfile = objfile;
4942           sig_type->per_cu.is_debug_types = 1;
4943           sig_type->per_cu.section = section;
4944           sig_type->per_cu.sect_off = sect_off;
4945           sig_type->per_cu.length = length;
4946         }
4947
4948       slot = htab_find_slot (types_htab,
4949                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4950                              INSERT);
4951       gdb_assert (slot != NULL);
4952       if (*slot != NULL)
4953         {
4954           sect_offset dup_sect_off;
4955
4956           if (dwo_file)
4957             {
4958               const struct dwo_unit *dup_tu
4959                 = (const struct dwo_unit *) *slot;
4960
4961               dup_sect_off = dup_tu->sect_off;
4962             }
4963           else
4964             {
4965               const struct signatured_type *dup_tu
4966                 = (const struct signatured_type *) *slot;
4967
4968               dup_sect_off = dup_tu->per_cu.sect_off;
4969             }
4970
4971           complaint (&symfile_complaints,
4972                      _("debug type entry at offset 0x%x is duplicate to"
4973                        " the entry at offset 0x%x, signature %s"),
4974                      to_underlying (sect_off), to_underlying (dup_sect_off),
4975                      hex_string (header.signature));
4976         }
4977       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4978
4979       if (dwarf_read_debug > 1)
4980         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4981                             to_underlying (sect_off),
4982                             hex_string (header.signature));
4983
4984       info_ptr += length;
4985     }
4986 }
4987
4988 /* Create the hash table of all entries in the .debug_types
4989    (or .debug_types.dwo) section(s).
4990    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4991    otherwise it is NULL.
4992
4993    The result is a pointer to the hash table or NULL if there are no types.
4994
4995    Note: This function processes DWO files only, not DWP files.  */
4996
4997 static void
4998 create_debug_types_hash_table (struct dwo_file *dwo_file,
4999                                VEC (dwarf2_section_info_def) *types,
5000                                htab_t &types_htab)
5001 {
5002   int ix;
5003   struct dwarf2_section_info *section;
5004
5005   if (VEC_empty (dwarf2_section_info_def, types))
5006     return;
5007
5008   for (ix = 0;
5009        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5010        ++ix)
5011     create_debug_type_hash_table (dwo_file, section, types_htab,
5012                                   rcuh_kind::TYPE);
5013 }
5014
5015 /* Create the hash table of all entries in the .debug_types section,
5016    and initialize all_type_units.
5017    The result is zero if there is an error (e.g. missing .debug_types section),
5018    otherwise non-zero.  */
5019
5020 static int
5021 create_all_type_units (struct objfile *objfile)
5022 {
5023   htab_t types_htab = NULL;
5024   struct signatured_type **iter;
5025
5026   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5027                                 rcuh_kind::COMPILE);
5028   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5029   if (types_htab == NULL)
5030     {
5031       dwarf2_per_objfile->signatured_types = NULL;
5032       return 0;
5033     }
5034
5035   dwarf2_per_objfile->signatured_types = types_htab;
5036
5037   dwarf2_per_objfile->n_type_units
5038     = dwarf2_per_objfile->n_allocated_type_units
5039     = htab_elements (types_htab);
5040   dwarf2_per_objfile->all_type_units =
5041     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5042   iter = &dwarf2_per_objfile->all_type_units[0];
5043   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5044   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5045               == dwarf2_per_objfile->n_type_units);
5046
5047   return 1;
5048 }
5049
5050 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5051    If SLOT is non-NULL, it is the entry to use in the hash table.
5052    Otherwise we find one.  */
5053
5054 static struct signatured_type *
5055 add_type_unit (ULONGEST sig, void **slot)
5056 {
5057   struct objfile *objfile = dwarf2_per_objfile->objfile;
5058   int n_type_units = dwarf2_per_objfile->n_type_units;
5059   struct signatured_type *sig_type;
5060
5061   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5062   ++n_type_units;
5063   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5064     {
5065       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5066         dwarf2_per_objfile->n_allocated_type_units = 1;
5067       dwarf2_per_objfile->n_allocated_type_units *= 2;
5068       dwarf2_per_objfile->all_type_units
5069         = XRESIZEVEC (struct signatured_type *,
5070                       dwarf2_per_objfile->all_type_units,
5071                       dwarf2_per_objfile->n_allocated_type_units);
5072       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5073     }
5074   dwarf2_per_objfile->n_type_units = n_type_units;
5075
5076   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5077                              struct signatured_type);
5078   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5079   sig_type->signature = sig;
5080   sig_type->per_cu.is_debug_types = 1;
5081   if (dwarf2_per_objfile->using_index)
5082     {
5083       sig_type->per_cu.v.quick =
5084         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5085                         struct dwarf2_per_cu_quick_data);
5086     }
5087
5088   if (slot == NULL)
5089     {
5090       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5091                              sig_type, INSERT);
5092     }
5093   gdb_assert (*slot == NULL);
5094   *slot = sig_type;
5095   /* The rest of sig_type must be filled in by the caller.  */
5096   return sig_type;
5097 }
5098
5099 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5100    Fill in SIG_ENTRY with DWO_ENTRY.  */
5101
5102 static void
5103 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5104                                   struct signatured_type *sig_entry,
5105                                   struct dwo_unit *dwo_entry)
5106 {
5107   /* Make sure we're not clobbering something we don't expect to.  */
5108   gdb_assert (! sig_entry->per_cu.queued);
5109   gdb_assert (sig_entry->per_cu.cu == NULL);
5110   if (dwarf2_per_objfile->using_index)
5111     {
5112       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5113       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5114     }
5115   else
5116       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5117   gdb_assert (sig_entry->signature == dwo_entry->signature);
5118   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5119   gdb_assert (sig_entry->type_unit_group == NULL);
5120   gdb_assert (sig_entry->dwo_unit == NULL);
5121
5122   sig_entry->per_cu.section = dwo_entry->section;
5123   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5124   sig_entry->per_cu.length = dwo_entry->length;
5125   sig_entry->per_cu.reading_dwo_directly = 1;
5126   sig_entry->per_cu.objfile = objfile;
5127   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5128   sig_entry->dwo_unit = dwo_entry;
5129 }
5130
5131 /* Subroutine of lookup_signatured_type.
5132    If we haven't read the TU yet, create the signatured_type data structure
5133    for a TU to be read in directly from a DWO file, bypassing the stub.
5134    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5135    using .gdb_index, then when reading a CU we want to stay in the DWO file
5136    containing that CU.  Otherwise we could end up reading several other DWO
5137    files (due to comdat folding) to process the transitive closure of all the
5138    mentioned TUs, and that can be slow.  The current DWO file will have every
5139    type signature that it needs.
5140    We only do this for .gdb_index because in the psymtab case we already have
5141    to read all the DWOs to build the type unit groups.  */
5142
5143 static struct signatured_type *
5144 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5145 {
5146   struct objfile *objfile = dwarf2_per_objfile->objfile;
5147   struct dwo_file *dwo_file;
5148   struct dwo_unit find_dwo_entry, *dwo_entry;
5149   struct signatured_type find_sig_entry, *sig_entry;
5150   void **slot;
5151
5152   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5153
5154   /* If TU skeletons have been removed then we may not have read in any
5155      TUs yet.  */
5156   if (dwarf2_per_objfile->signatured_types == NULL)
5157     {
5158       dwarf2_per_objfile->signatured_types
5159         = allocate_signatured_type_table (objfile);
5160     }
5161
5162   /* We only ever need to read in one copy of a signatured type.
5163      Use the global signatured_types array to do our own comdat-folding
5164      of types.  If this is the first time we're reading this TU, and
5165      the TU has an entry in .gdb_index, replace the recorded data from
5166      .gdb_index with this TU.  */
5167
5168   find_sig_entry.signature = sig;
5169   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5170                          &find_sig_entry, INSERT);
5171   sig_entry = (struct signatured_type *) *slot;
5172
5173   /* We can get here with the TU already read, *or* in the process of being
5174      read.  Don't reassign the global entry to point to this DWO if that's
5175      the case.  Also note that if the TU is already being read, it may not
5176      have come from a DWO, the program may be a mix of Fission-compiled
5177      code and non-Fission-compiled code.  */
5178
5179   /* Have we already tried to read this TU?
5180      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5181      needn't exist in the global table yet).  */
5182   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5183     return sig_entry;
5184
5185   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5186      dwo_unit of the TU itself.  */
5187   dwo_file = cu->dwo_unit->dwo_file;
5188
5189   /* Ok, this is the first time we're reading this TU.  */
5190   if (dwo_file->tus == NULL)
5191     return NULL;
5192   find_dwo_entry.signature = sig;
5193   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5194   if (dwo_entry == NULL)
5195     return NULL;
5196
5197   /* If the global table doesn't have an entry for this TU, add one.  */
5198   if (sig_entry == NULL)
5199     sig_entry = add_type_unit (sig, slot);
5200
5201   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5202   sig_entry->per_cu.tu_read = 1;
5203   return sig_entry;
5204 }
5205
5206 /* Subroutine of lookup_signatured_type.
5207    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5208    then try the DWP file.  If the TU stub (skeleton) has been removed then
5209    it won't be in .gdb_index.  */
5210
5211 static struct signatured_type *
5212 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5213 {
5214   struct objfile *objfile = dwarf2_per_objfile->objfile;
5215   struct dwp_file *dwp_file = get_dwp_file ();
5216   struct dwo_unit *dwo_entry;
5217   struct signatured_type find_sig_entry, *sig_entry;
5218   void **slot;
5219
5220   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5221   gdb_assert (dwp_file != NULL);
5222
5223   /* If TU skeletons have been removed then we may not have read in any
5224      TUs yet.  */
5225   if (dwarf2_per_objfile->signatured_types == NULL)
5226     {
5227       dwarf2_per_objfile->signatured_types
5228         = allocate_signatured_type_table (objfile);
5229     }
5230
5231   find_sig_entry.signature = sig;
5232   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5233                          &find_sig_entry, INSERT);
5234   sig_entry = (struct signatured_type *) *slot;
5235
5236   /* Have we already tried to read this TU?
5237      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5238      needn't exist in the global table yet).  */
5239   if (sig_entry != NULL)
5240     return sig_entry;
5241
5242   if (dwp_file->tus == NULL)
5243     return NULL;
5244   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5245                                       sig, 1 /* is_debug_types */);
5246   if (dwo_entry == NULL)
5247     return NULL;
5248
5249   sig_entry = add_type_unit (sig, slot);
5250   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5251
5252   return sig_entry;
5253 }
5254
5255 /* Lookup a signature based type for DW_FORM_ref_sig8.
5256    Returns NULL if signature SIG is not present in the table.
5257    It is up to the caller to complain about this.  */
5258
5259 static struct signatured_type *
5260 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5261 {
5262   if (cu->dwo_unit
5263       && dwarf2_per_objfile->using_index)
5264     {
5265       /* We're in a DWO/DWP file, and we're using .gdb_index.
5266          These cases require special processing.  */
5267       if (get_dwp_file () == NULL)
5268         return lookup_dwo_signatured_type (cu, sig);
5269       else
5270         return lookup_dwp_signatured_type (cu, sig);
5271     }
5272   else
5273     {
5274       struct signatured_type find_entry, *entry;
5275
5276       if (dwarf2_per_objfile->signatured_types == NULL)
5277         return NULL;
5278       find_entry.signature = sig;
5279       entry = ((struct signatured_type *)
5280                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5281       return entry;
5282     }
5283 }
5284 \f
5285 /* Low level DIE reading support.  */
5286
5287 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5288
5289 static void
5290 init_cu_die_reader (struct die_reader_specs *reader,
5291                     struct dwarf2_cu *cu,
5292                     struct dwarf2_section_info *section,
5293                     struct dwo_file *dwo_file)
5294 {
5295   gdb_assert (section->readin && section->buffer != NULL);
5296   reader->abfd = get_section_bfd_owner (section);
5297   reader->cu = cu;
5298   reader->dwo_file = dwo_file;
5299   reader->die_section = section;
5300   reader->buffer = section->buffer;
5301   reader->buffer_end = section->buffer + section->size;
5302   reader->comp_dir = NULL;
5303 }
5304
5305 /* Subroutine of init_cutu_and_read_dies to simplify it.
5306    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5307    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5308    already.
5309
5310    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5311    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5312    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5313    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5314    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5315    STUB_COMP_DIR may be non-NULL.
5316    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5317    are filled in with the info of the DIE from the DWO file.
5318    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5319    provided an abbrev table to use.
5320    The result is non-zero if a valid (non-dummy) DIE was found.  */
5321
5322 static int
5323 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5324                         struct dwo_unit *dwo_unit,
5325                         int abbrev_table_provided,
5326                         struct die_info *stub_comp_unit_die,
5327                         const char *stub_comp_dir,
5328                         struct die_reader_specs *result_reader,
5329                         const gdb_byte **result_info_ptr,
5330                         struct die_info **result_comp_unit_die,
5331                         int *result_has_children)
5332 {
5333   struct objfile *objfile = dwarf2_per_objfile->objfile;
5334   struct dwarf2_cu *cu = this_cu->cu;
5335   struct dwarf2_section_info *section;
5336   bfd *abfd;
5337   const gdb_byte *begin_info_ptr, *info_ptr;
5338   ULONGEST signature; /* Or dwo_id.  */
5339   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5340   int i,num_extra_attrs;
5341   struct dwarf2_section_info *dwo_abbrev_section;
5342   struct attribute *attr;
5343   struct die_info *comp_unit_die;
5344
5345   /* At most one of these may be provided.  */
5346   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5347
5348   /* These attributes aren't processed until later:
5349      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5350      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5351      referenced later.  However, these attributes are found in the stub
5352      which we won't have later.  In order to not impose this complication
5353      on the rest of the code, we read them here and copy them to the
5354      DWO CU/TU die.  */
5355
5356   stmt_list = NULL;
5357   low_pc = NULL;
5358   high_pc = NULL;
5359   ranges = NULL;
5360   comp_dir = NULL;
5361
5362   if (stub_comp_unit_die != NULL)
5363     {
5364       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5365          DWO file.  */
5366       if (! this_cu->is_debug_types)
5367         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5368       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5369       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5370       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5371       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5372
5373       /* There should be a DW_AT_addr_base attribute here (if needed).
5374          We need the value before we can process DW_FORM_GNU_addr_index.  */
5375       cu->addr_base = 0;
5376       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5377       if (attr)
5378         cu->addr_base = DW_UNSND (attr);
5379
5380       /* There should be a DW_AT_ranges_base attribute here (if needed).
5381          We need the value before we can process DW_AT_ranges.  */
5382       cu->ranges_base = 0;
5383       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5384       if (attr)
5385         cu->ranges_base = DW_UNSND (attr);
5386     }
5387   else if (stub_comp_dir != NULL)
5388     {
5389       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5390       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5391       comp_dir->name = DW_AT_comp_dir;
5392       comp_dir->form = DW_FORM_string;
5393       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5394       DW_STRING (comp_dir) = stub_comp_dir;
5395     }
5396
5397   /* Set up for reading the DWO CU/TU.  */
5398   cu->dwo_unit = dwo_unit;
5399   section = dwo_unit->section;
5400   dwarf2_read_section (objfile, section);
5401   abfd = get_section_bfd_owner (section);
5402   begin_info_ptr = info_ptr = (section->buffer
5403                                + to_underlying (dwo_unit->sect_off));
5404   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5405   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5406
5407   if (this_cu->is_debug_types)
5408     {
5409       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5410
5411       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5412                                                 dwo_abbrev_section,
5413                                                 info_ptr, rcuh_kind::TYPE);
5414       /* This is not an assert because it can be caused by bad debug info.  */
5415       if (sig_type->signature != cu->header.signature)
5416         {
5417           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5418                    " TU at offset 0x%x [in module %s]"),
5419                  hex_string (sig_type->signature),
5420                  hex_string (cu->header.signature),
5421                  to_underlying (dwo_unit->sect_off),
5422                  bfd_get_filename (abfd));
5423         }
5424       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5425       /* For DWOs coming from DWP files, we don't know the CU length
5426          nor the type's offset in the TU until now.  */
5427       dwo_unit->length = get_cu_length (&cu->header);
5428       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5429
5430       /* Establish the type offset that can be used to lookup the type.
5431          For DWO files, we don't know it until now.  */
5432       sig_type->type_offset_in_section
5433         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5434     }
5435   else
5436     {
5437       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5438                                                 dwo_abbrev_section,
5439                                                 info_ptr, rcuh_kind::COMPILE);
5440       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5441       /* For DWOs coming from DWP files, we don't know the CU length
5442          until now.  */
5443       dwo_unit->length = get_cu_length (&cu->header);
5444     }
5445
5446   /* Replace the CU's original abbrev table with the DWO's.
5447      Reminder: We can't read the abbrev table until we've read the header.  */
5448   if (abbrev_table_provided)
5449     {
5450       /* Don't free the provided abbrev table, the caller of
5451          init_cutu_and_read_dies owns it.  */
5452       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5453       /* Ensure the DWO abbrev table gets freed.  */
5454       make_cleanup (dwarf2_free_abbrev_table, cu);
5455     }
5456   else
5457     {
5458       dwarf2_free_abbrev_table (cu);
5459       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5460       /* Leave any existing abbrev table cleanup as is.  */
5461     }
5462
5463   /* Read in the die, but leave space to copy over the attributes
5464      from the stub.  This has the benefit of simplifying the rest of
5465      the code - all the work to maintain the illusion of a single
5466      DW_TAG_{compile,type}_unit DIE is done here.  */
5467   num_extra_attrs = ((stmt_list != NULL)
5468                      + (low_pc != NULL)
5469                      + (high_pc != NULL)
5470                      + (ranges != NULL)
5471                      + (comp_dir != NULL));
5472   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5473                               result_has_children, num_extra_attrs);
5474
5475   /* Copy over the attributes from the stub to the DIE we just read in.  */
5476   comp_unit_die = *result_comp_unit_die;
5477   i = comp_unit_die->num_attrs;
5478   if (stmt_list != NULL)
5479     comp_unit_die->attrs[i++] = *stmt_list;
5480   if (low_pc != NULL)
5481     comp_unit_die->attrs[i++] = *low_pc;
5482   if (high_pc != NULL)
5483     comp_unit_die->attrs[i++] = *high_pc;
5484   if (ranges != NULL)
5485     comp_unit_die->attrs[i++] = *ranges;
5486   if (comp_dir != NULL)
5487     comp_unit_die->attrs[i++] = *comp_dir;
5488   comp_unit_die->num_attrs += num_extra_attrs;
5489
5490   if (dwarf_die_debug)
5491     {
5492       fprintf_unfiltered (gdb_stdlog,
5493                           "Read die from %s@0x%x of %s:\n",
5494                           get_section_name (section),
5495                           (unsigned) (begin_info_ptr - section->buffer),
5496                           bfd_get_filename (abfd));
5497       dump_die (comp_unit_die, dwarf_die_debug);
5498     }
5499
5500   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5501      TUs by skipping the stub and going directly to the entry in the DWO file.
5502      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5503      to get it via circuitous means.  Blech.  */
5504   if (comp_dir != NULL)
5505     result_reader->comp_dir = DW_STRING (comp_dir);
5506
5507   /* Skip dummy compilation units.  */
5508   if (info_ptr >= begin_info_ptr + dwo_unit->length
5509       || peek_abbrev_code (abfd, info_ptr) == 0)
5510     return 0;
5511
5512   *result_info_ptr = info_ptr;
5513   return 1;
5514 }
5515
5516 /* Subroutine of init_cutu_and_read_dies to simplify it.
5517    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5518    Returns NULL if the specified DWO unit cannot be found.  */
5519
5520 static struct dwo_unit *
5521 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5522                  struct die_info *comp_unit_die)
5523 {
5524   struct dwarf2_cu *cu = this_cu->cu;
5525   struct attribute *attr;
5526   ULONGEST signature;
5527   struct dwo_unit *dwo_unit;
5528   const char *comp_dir, *dwo_name;
5529
5530   gdb_assert (cu != NULL);
5531
5532   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5533   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5534   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5535
5536   if (this_cu->is_debug_types)
5537     {
5538       struct signatured_type *sig_type;
5539
5540       /* Since this_cu is the first member of struct signatured_type,
5541          we can go from a pointer to one to a pointer to the other.  */
5542       sig_type = (struct signatured_type *) this_cu;
5543       signature = sig_type->signature;
5544       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5545     }
5546   else
5547     {
5548       struct attribute *attr;
5549
5550       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5551       if (! attr)
5552         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5553                  " [in module %s]"),
5554                dwo_name, objfile_name (this_cu->objfile));
5555       signature = DW_UNSND (attr);
5556       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5557                                        signature);
5558     }
5559
5560   return dwo_unit;
5561 }
5562
5563 /* Subroutine of init_cutu_and_read_dies to simplify it.
5564    See it for a description of the parameters.
5565    Read a TU directly from a DWO file, bypassing the stub.
5566
5567    Note: This function could be a little bit simpler if we shared cleanups
5568    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5569    to do, so we keep this function self-contained.  Or we could move this
5570    into our caller, but it's complex enough already.  */
5571
5572 static void
5573 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5574                            int use_existing_cu, int keep,
5575                            die_reader_func_ftype *die_reader_func,
5576                            void *data)
5577 {
5578   struct dwarf2_cu *cu;
5579   struct signatured_type *sig_type;
5580   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5581   struct die_reader_specs reader;
5582   const gdb_byte *info_ptr;
5583   struct die_info *comp_unit_die;
5584   int has_children;
5585
5586   /* Verify we can do the following downcast, and that we have the
5587      data we need.  */
5588   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5589   sig_type = (struct signatured_type *) this_cu;
5590   gdb_assert (sig_type->dwo_unit != NULL);
5591
5592   cleanups = make_cleanup (null_cleanup, NULL);
5593
5594   if (use_existing_cu && this_cu->cu != NULL)
5595     {
5596       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5597       cu = this_cu->cu;
5598       /* There's no need to do the rereading_dwo_cu handling that
5599          init_cutu_and_read_dies does since we don't read the stub.  */
5600     }
5601   else
5602     {
5603       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5604       gdb_assert (this_cu->cu == NULL);
5605       cu = XNEW (struct dwarf2_cu);
5606       init_one_comp_unit (cu, this_cu);
5607       /* If an error occurs while loading, release our storage.  */
5608       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5609     }
5610
5611   /* A future optimization, if needed, would be to use an existing
5612      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5613      could share abbrev tables.  */
5614
5615   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5616                               0 /* abbrev_table_provided */,
5617                               NULL /* stub_comp_unit_die */,
5618                               sig_type->dwo_unit->dwo_file->comp_dir,
5619                               &reader, &info_ptr,
5620                               &comp_unit_die, &has_children) == 0)
5621     {
5622       /* Dummy die.  */
5623       do_cleanups (cleanups);
5624       return;
5625     }
5626
5627   /* All the "real" work is done here.  */
5628   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5629
5630   /* This duplicates the code in init_cutu_and_read_dies,
5631      but the alternative is making the latter more complex.
5632      This function is only for the special case of using DWO files directly:
5633      no point in overly complicating the general case just to handle this.  */
5634   if (free_cu_cleanup != NULL)
5635     {
5636       if (keep)
5637         {
5638           /* We've successfully allocated this compilation unit.  Let our
5639              caller clean it up when finished with it.  */
5640           discard_cleanups (free_cu_cleanup);
5641
5642           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5643              So we have to manually free the abbrev table.  */
5644           dwarf2_free_abbrev_table (cu);
5645
5646           /* Link this CU into read_in_chain.  */
5647           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5648           dwarf2_per_objfile->read_in_chain = this_cu;
5649         }
5650       else
5651         do_cleanups (free_cu_cleanup);
5652     }
5653
5654   do_cleanups (cleanups);
5655 }
5656
5657 /* Initialize a CU (or TU) and read its DIEs.
5658    If the CU defers to a DWO file, read the DWO file as well.
5659
5660    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5661    Otherwise the table specified in the comp unit header is read in and used.
5662    This is an optimization for when we already have the abbrev table.
5663
5664    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5665    Otherwise, a new CU is allocated with xmalloc.
5666
5667    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5668    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5669
5670    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5671    linker) then DIE_READER_FUNC will not get called.  */
5672
5673 static void
5674 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5675                          struct abbrev_table *abbrev_table,
5676                          int use_existing_cu, int keep,
5677                          die_reader_func_ftype *die_reader_func,
5678                          void *data)
5679 {
5680   struct objfile *objfile = dwarf2_per_objfile->objfile;
5681   struct dwarf2_section_info *section = this_cu->section;
5682   bfd *abfd = get_section_bfd_owner (section);
5683   struct dwarf2_cu *cu;
5684   const gdb_byte *begin_info_ptr, *info_ptr;
5685   struct die_reader_specs reader;
5686   struct die_info *comp_unit_die;
5687   int has_children;
5688   struct attribute *attr;
5689   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5690   struct signatured_type *sig_type = NULL;
5691   struct dwarf2_section_info *abbrev_section;
5692   /* Non-zero if CU currently points to a DWO file and we need to
5693      reread it.  When this happens we need to reread the skeleton die
5694      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5695   int rereading_dwo_cu = 0;
5696
5697   if (dwarf_die_debug)
5698     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5699                         this_cu->is_debug_types ? "type" : "comp",
5700                         to_underlying (this_cu->sect_off));
5701
5702   if (use_existing_cu)
5703     gdb_assert (keep);
5704
5705   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5706      file (instead of going through the stub), short-circuit all of this.  */
5707   if (this_cu->reading_dwo_directly)
5708     {
5709       /* Narrow down the scope of possibilities to have to understand.  */
5710       gdb_assert (this_cu->is_debug_types);
5711       gdb_assert (abbrev_table == NULL);
5712       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5713                                  die_reader_func, data);
5714       return;
5715     }
5716
5717   cleanups = make_cleanup (null_cleanup, NULL);
5718
5719   /* This is cheap if the section is already read in.  */
5720   dwarf2_read_section (objfile, section);
5721
5722   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5723
5724   abbrev_section = get_abbrev_section_for_cu (this_cu);
5725
5726   if (use_existing_cu && this_cu->cu != NULL)
5727     {
5728       cu = this_cu->cu;
5729       /* If this CU is from a DWO file we need to start over, we need to
5730          refetch the attributes from the skeleton CU.
5731          This could be optimized by retrieving those attributes from when we
5732          were here the first time: the previous comp_unit_die was stored in
5733          comp_unit_obstack.  But there's no data yet that we need this
5734          optimization.  */
5735       if (cu->dwo_unit != NULL)
5736         rereading_dwo_cu = 1;
5737     }
5738   else
5739     {
5740       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5741       gdb_assert (this_cu->cu == NULL);
5742       cu = XNEW (struct dwarf2_cu);
5743       init_one_comp_unit (cu, this_cu);
5744       /* If an error occurs while loading, release our storage.  */
5745       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5746     }
5747
5748   /* Get the header.  */
5749   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5750     {
5751       /* We already have the header, there's no need to read it in again.  */
5752       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5753     }
5754   else
5755     {
5756       if (this_cu->is_debug_types)
5757         {
5758           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5759                                                     abbrev_section, info_ptr,
5760                                                     rcuh_kind::TYPE);
5761
5762           /* Since per_cu is the first member of struct signatured_type,
5763              we can go from a pointer to one to a pointer to the other.  */
5764           sig_type = (struct signatured_type *) this_cu;
5765           gdb_assert (sig_type->signature == cu->header.signature);
5766           gdb_assert (sig_type->type_offset_in_tu
5767                       == cu->header.type_cu_offset_in_tu);
5768           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5769
5770           /* LENGTH has not been set yet for type units if we're
5771              using .gdb_index.  */
5772           this_cu->length = get_cu_length (&cu->header);
5773
5774           /* Establish the type offset that can be used to lookup the type.  */
5775           sig_type->type_offset_in_section =
5776             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5777
5778           this_cu->dwarf_version = cu->header.version;
5779         }
5780       else
5781         {
5782           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5783                                                     abbrev_section,
5784                                                     info_ptr,
5785                                                     rcuh_kind::COMPILE);
5786
5787           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5788           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5789           this_cu->dwarf_version = cu->header.version;
5790         }
5791     }
5792
5793   /* Skip dummy compilation units.  */
5794   if (info_ptr >= begin_info_ptr + this_cu->length
5795       || peek_abbrev_code (abfd, info_ptr) == 0)
5796     {
5797       do_cleanups (cleanups);
5798       return;
5799     }
5800
5801   /* If we don't have them yet, read the abbrevs for this compilation unit.
5802      And if we need to read them now, make sure they're freed when we're
5803      done.  Note that it's important that if the CU had an abbrev table
5804      on entry we don't free it when we're done: Somewhere up the call stack
5805      it may be in use.  */
5806   if (abbrev_table != NULL)
5807     {
5808       gdb_assert (cu->abbrev_table == NULL);
5809       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5810       cu->abbrev_table = abbrev_table;
5811     }
5812   else if (cu->abbrev_table == NULL)
5813     {
5814       dwarf2_read_abbrevs (cu, abbrev_section);
5815       make_cleanup (dwarf2_free_abbrev_table, cu);
5816     }
5817   else if (rereading_dwo_cu)
5818     {
5819       dwarf2_free_abbrev_table (cu);
5820       dwarf2_read_abbrevs (cu, abbrev_section);
5821     }
5822
5823   /* Read the top level CU/TU die.  */
5824   init_cu_die_reader (&reader, cu, section, NULL);
5825   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5826
5827   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5828      from the DWO file.
5829      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5830      DWO CU, that this test will fail (the attribute will not be present).  */
5831   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5832   if (attr)
5833     {
5834       struct dwo_unit *dwo_unit;
5835       struct die_info *dwo_comp_unit_die;
5836
5837       if (has_children)
5838         {
5839           complaint (&symfile_complaints,
5840                      _("compilation unit with DW_AT_GNU_dwo_name"
5841                        " has children (offset 0x%x) [in module %s]"),
5842                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5843         }
5844       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5845       if (dwo_unit != NULL)
5846         {
5847           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5848                                       abbrev_table != NULL,
5849                                       comp_unit_die, NULL,
5850                                       &reader, &info_ptr,
5851                                       &dwo_comp_unit_die, &has_children) == 0)
5852             {
5853               /* Dummy die.  */
5854               do_cleanups (cleanups);
5855               return;
5856             }
5857           comp_unit_die = dwo_comp_unit_die;
5858         }
5859       else
5860         {
5861           /* Yikes, we couldn't find the rest of the DIE, we only have
5862              the stub.  A complaint has already been logged.  There's
5863              not much more we can do except pass on the stub DIE to
5864              die_reader_func.  We don't want to throw an error on bad
5865              debug info.  */
5866         }
5867     }
5868
5869   /* All of the above is setup for this call.  Yikes.  */
5870   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5871
5872   /* Done, clean up.  */
5873   if (free_cu_cleanup != NULL)
5874     {
5875       if (keep)
5876         {
5877           /* We've successfully allocated this compilation unit.  Let our
5878              caller clean it up when finished with it.  */
5879           discard_cleanups (free_cu_cleanup);
5880
5881           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5882              So we have to manually free the abbrev table.  */
5883           dwarf2_free_abbrev_table (cu);
5884
5885           /* Link this CU into read_in_chain.  */
5886           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5887           dwarf2_per_objfile->read_in_chain = this_cu;
5888         }
5889       else
5890         do_cleanups (free_cu_cleanup);
5891     }
5892
5893   do_cleanups (cleanups);
5894 }
5895
5896 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5897    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5898    to have already done the lookup to find the DWO file).
5899
5900    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5901    THIS_CU->is_debug_types, but nothing else.
5902
5903    We fill in THIS_CU->length.
5904
5905    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5906    linker) then DIE_READER_FUNC will not get called.
5907
5908    THIS_CU->cu is always freed when done.
5909    This is done in order to not leave THIS_CU->cu in a state where we have
5910    to care whether it refers to the "main" CU or the DWO CU.  */
5911
5912 static void
5913 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5914                                    struct dwo_file *dwo_file,
5915                                    die_reader_func_ftype *die_reader_func,
5916                                    void *data)
5917 {
5918   struct objfile *objfile = dwarf2_per_objfile->objfile;
5919   struct dwarf2_section_info *section = this_cu->section;
5920   bfd *abfd = get_section_bfd_owner (section);
5921   struct dwarf2_section_info *abbrev_section;
5922   struct dwarf2_cu cu;
5923   const gdb_byte *begin_info_ptr, *info_ptr;
5924   struct die_reader_specs reader;
5925   struct cleanup *cleanups;
5926   struct die_info *comp_unit_die;
5927   int has_children;
5928
5929   if (dwarf_die_debug)
5930     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5931                         this_cu->is_debug_types ? "type" : "comp",
5932                         to_underlying (this_cu->sect_off));
5933
5934   gdb_assert (this_cu->cu == NULL);
5935
5936   abbrev_section = (dwo_file != NULL
5937                     ? &dwo_file->sections.abbrev
5938                     : get_abbrev_section_for_cu (this_cu));
5939
5940   /* This is cheap if the section is already read in.  */
5941   dwarf2_read_section (objfile, section);
5942
5943   init_one_comp_unit (&cu, this_cu);
5944
5945   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5946
5947   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5948   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5949                                             abbrev_section, info_ptr,
5950                                             (this_cu->is_debug_types
5951                                              ? rcuh_kind::TYPE
5952                                              : rcuh_kind::COMPILE));
5953
5954   this_cu->length = get_cu_length (&cu.header);
5955
5956   /* Skip dummy compilation units.  */
5957   if (info_ptr >= begin_info_ptr + this_cu->length
5958       || peek_abbrev_code (abfd, info_ptr) == 0)
5959     {
5960       do_cleanups (cleanups);
5961       return;
5962     }
5963
5964   dwarf2_read_abbrevs (&cu, abbrev_section);
5965   make_cleanup (dwarf2_free_abbrev_table, &cu);
5966
5967   init_cu_die_reader (&reader, &cu, section, dwo_file);
5968   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5969
5970   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5971
5972   do_cleanups (cleanups);
5973 }
5974
5975 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5976    does not lookup the specified DWO file.
5977    This cannot be used to read DWO files.
5978
5979    THIS_CU->cu is always freed when done.
5980    This is done in order to not leave THIS_CU->cu in a state where we have
5981    to care whether it refers to the "main" CU or the DWO CU.
5982    We can revisit this if the data shows there's a performance issue.  */
5983
5984 static void
5985 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5986                                 die_reader_func_ftype *die_reader_func,
5987                                 void *data)
5988 {
5989   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5990 }
5991 \f
5992 /* Type Unit Groups.
5993
5994    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5995    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5996    so that all types coming from the same compilation (.o file) are grouped
5997    together.  A future step could be to put the types in the same symtab as
5998    the CU the types ultimately came from.  */
5999
6000 static hashval_t
6001 hash_type_unit_group (const void *item)
6002 {
6003   const struct type_unit_group *tu_group
6004     = (const struct type_unit_group *) item;
6005
6006   return hash_stmt_list_entry (&tu_group->hash);
6007 }
6008
6009 static int
6010 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6011 {
6012   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6013   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6014
6015   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6016 }
6017
6018 /* Allocate a hash table for type unit groups.  */
6019
6020 static htab_t
6021 allocate_type_unit_groups_table (void)
6022 {
6023   return htab_create_alloc_ex (3,
6024                                hash_type_unit_group,
6025                                eq_type_unit_group,
6026                                NULL,
6027                                &dwarf2_per_objfile->objfile->objfile_obstack,
6028                                hashtab_obstack_allocate,
6029                                dummy_obstack_deallocate);
6030 }
6031
6032 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6033    partial symtabs.  We combine several TUs per psymtab to not let the size
6034    of any one psymtab grow too big.  */
6035 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6036 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6037
6038 /* Helper routine for get_type_unit_group.
6039    Create the type_unit_group object used to hold one or more TUs.  */
6040
6041 static struct type_unit_group *
6042 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6043 {
6044   struct objfile *objfile = dwarf2_per_objfile->objfile;
6045   struct dwarf2_per_cu_data *per_cu;
6046   struct type_unit_group *tu_group;
6047
6048   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6049                              struct type_unit_group);
6050   per_cu = &tu_group->per_cu;
6051   per_cu->objfile = objfile;
6052
6053   if (dwarf2_per_objfile->using_index)
6054     {
6055       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6056                                         struct dwarf2_per_cu_quick_data);
6057     }
6058   else
6059     {
6060       unsigned int line_offset = to_underlying (line_offset_struct);
6061       struct partial_symtab *pst;
6062       char *name;
6063
6064       /* Give the symtab a useful name for debug purposes.  */
6065       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6066         name = xstrprintf ("<type_units_%d>",
6067                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6068       else
6069         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6070
6071       pst = create_partial_symtab (per_cu, name);
6072       pst->anonymous = 1;
6073
6074       xfree (name);
6075     }
6076
6077   tu_group->hash.dwo_unit = cu->dwo_unit;
6078   tu_group->hash.line_sect_off = line_offset_struct;
6079
6080   return tu_group;
6081 }
6082
6083 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6084    STMT_LIST is a DW_AT_stmt_list attribute.  */
6085
6086 static struct type_unit_group *
6087 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6088 {
6089   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6090   struct type_unit_group *tu_group;
6091   void **slot;
6092   unsigned int line_offset;
6093   struct type_unit_group type_unit_group_for_lookup;
6094
6095   if (dwarf2_per_objfile->type_unit_groups == NULL)
6096     {
6097       dwarf2_per_objfile->type_unit_groups =
6098         allocate_type_unit_groups_table ();
6099     }
6100
6101   /* Do we need to create a new group, or can we use an existing one?  */
6102
6103   if (stmt_list)
6104     {
6105       line_offset = DW_UNSND (stmt_list);
6106       ++tu_stats->nr_symtab_sharers;
6107     }
6108   else
6109     {
6110       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6111          We can do various things here like create one group per TU or
6112          spread them over multiple groups to split up the expansion work.
6113          To avoid worst case scenarios (too many groups or too large groups)
6114          we, umm, group them in bunches.  */
6115       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6116                      | (tu_stats->nr_stmt_less_type_units
6117                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6118       ++tu_stats->nr_stmt_less_type_units;
6119     }
6120
6121   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6122   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6123   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6124                          &type_unit_group_for_lookup, INSERT);
6125   if (*slot != NULL)
6126     {
6127       tu_group = (struct type_unit_group *) *slot;
6128       gdb_assert (tu_group != NULL);
6129     }
6130   else
6131     {
6132       sect_offset line_offset_struct = (sect_offset) line_offset;
6133       tu_group = create_type_unit_group (cu, line_offset_struct);
6134       *slot = tu_group;
6135       ++tu_stats->nr_symtabs;
6136     }
6137
6138   return tu_group;
6139 }
6140 \f
6141 /* Partial symbol tables.  */
6142
6143 /* Create a psymtab named NAME and assign it to PER_CU.
6144
6145    The caller must fill in the following details:
6146    dirname, textlow, texthigh.  */
6147
6148 static struct partial_symtab *
6149 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6150 {
6151   struct objfile *objfile = per_cu->objfile;
6152   struct partial_symtab *pst;
6153
6154   pst = start_psymtab_common (objfile, name, 0,
6155                               objfile->global_psymbols.next,
6156                               objfile->static_psymbols.next);
6157
6158   pst->psymtabs_addrmap_supported = 1;
6159
6160   /* This is the glue that links PST into GDB's symbol API.  */
6161   pst->read_symtab_private = per_cu;
6162   pst->read_symtab = dwarf2_read_symtab;
6163   per_cu->v.psymtab = pst;
6164
6165   return pst;
6166 }
6167
6168 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6169    type.  */
6170
6171 struct process_psymtab_comp_unit_data
6172 {
6173   /* True if we are reading a DW_TAG_partial_unit.  */
6174
6175   int want_partial_unit;
6176
6177   /* The "pretend" language that is used if the CU doesn't declare a
6178      language.  */
6179
6180   enum language pretend_language;
6181 };
6182
6183 /* die_reader_func for process_psymtab_comp_unit.  */
6184
6185 static void
6186 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6187                                   const gdb_byte *info_ptr,
6188                                   struct die_info *comp_unit_die,
6189                                   int has_children,
6190                                   void *data)
6191 {
6192   struct dwarf2_cu *cu = reader->cu;
6193   struct objfile *objfile = cu->objfile;
6194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6195   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6196   CORE_ADDR baseaddr;
6197   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6198   struct partial_symtab *pst;
6199   enum pc_bounds_kind cu_bounds_kind;
6200   const char *filename;
6201   struct process_psymtab_comp_unit_data *info
6202     = (struct process_psymtab_comp_unit_data *) data;
6203
6204   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6205     return;
6206
6207   gdb_assert (! per_cu->is_debug_types);
6208
6209   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6210
6211   cu->list_in_scope = &file_symbols;
6212
6213   /* Allocate a new partial symbol table structure.  */
6214   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6215   if (filename == NULL)
6216     filename = "";
6217
6218   pst = create_partial_symtab (per_cu, filename);
6219
6220   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6221   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6222
6223   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6224
6225   dwarf2_find_base_address (comp_unit_die, cu);
6226
6227   /* Possibly set the default values of LOWPC and HIGHPC from
6228      `DW_AT_ranges'.  */
6229   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6230                                          &best_highpc, cu, pst);
6231   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6232     /* Store the contiguous range if it is not empty; it can be empty for
6233        CUs with no code.  */
6234     addrmap_set_empty (objfile->psymtabs_addrmap,
6235                        gdbarch_adjust_dwarf2_addr (gdbarch,
6236                                                    best_lowpc + baseaddr),
6237                        gdbarch_adjust_dwarf2_addr (gdbarch,
6238                                                    best_highpc + baseaddr) - 1,
6239                        pst);
6240
6241   /* Check if comp unit has_children.
6242      If so, read the rest of the partial symbols from this comp unit.
6243      If not, there's no more debug_info for this comp unit.  */
6244   if (has_children)
6245     {
6246       struct partial_die_info *first_die;
6247       CORE_ADDR lowpc, highpc;
6248
6249       lowpc = ((CORE_ADDR) -1);
6250       highpc = ((CORE_ADDR) 0);
6251
6252       first_die = load_partial_dies (reader, info_ptr, 1);
6253
6254       scan_partial_symbols (first_die, &lowpc, &highpc,
6255                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6256
6257       /* If we didn't find a lowpc, set it to highpc to avoid
6258          complaints from `maint check'.  */
6259       if (lowpc == ((CORE_ADDR) -1))
6260         lowpc = highpc;
6261
6262       /* If the compilation unit didn't have an explicit address range,
6263          then use the information extracted from its child dies.  */
6264       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6265         {
6266           best_lowpc = lowpc;
6267           best_highpc = highpc;
6268         }
6269     }
6270   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6271   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6272
6273   end_psymtab_common (objfile, pst);
6274
6275   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6276     {
6277       int i;
6278       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6279       struct dwarf2_per_cu_data *iter;
6280
6281       /* Fill in 'dependencies' here; we fill in 'users' in a
6282          post-pass.  */
6283       pst->number_of_dependencies = len;
6284       pst->dependencies =
6285         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6286       for (i = 0;
6287            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6288                         i, iter);
6289            ++i)
6290         pst->dependencies[i] = iter->v.psymtab;
6291
6292       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6293     }
6294
6295   /* Get the list of files included in the current compilation unit,
6296      and build a psymtab for each of them.  */
6297   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6298
6299   if (dwarf_read_debug)
6300     {
6301       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6302
6303       fprintf_unfiltered (gdb_stdlog,
6304                           "Psymtab for %s unit @0x%x: %s - %s"
6305                           ", %d global, %d static syms\n",
6306                           per_cu->is_debug_types ? "type" : "comp",
6307                           to_underlying (per_cu->sect_off),
6308                           paddress (gdbarch, pst->textlow),
6309                           paddress (gdbarch, pst->texthigh),
6310                           pst->n_global_syms, pst->n_static_syms);
6311     }
6312 }
6313
6314 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6315    Process compilation unit THIS_CU for a psymtab.  */
6316
6317 static void
6318 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6319                            int want_partial_unit,
6320                            enum language pretend_language)
6321 {
6322   /* If this compilation unit was already read in, free the
6323      cached copy in order to read it in again.  This is
6324      necessary because we skipped some symbols when we first
6325      read in the compilation unit (see load_partial_dies).
6326      This problem could be avoided, but the benefit is unclear.  */
6327   if (this_cu->cu != NULL)
6328     free_one_cached_comp_unit (this_cu);
6329
6330   if (this_cu->is_debug_types)
6331     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6332                              NULL);
6333   else
6334     {
6335       process_psymtab_comp_unit_data info;
6336       info.want_partial_unit = want_partial_unit;
6337       info.pretend_language = pretend_language;
6338       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6339                                process_psymtab_comp_unit_reader, &info);
6340     }
6341
6342   /* Age out any secondary CUs.  */
6343   age_cached_comp_units ();
6344 }
6345
6346 /* Reader function for build_type_psymtabs.  */
6347
6348 static void
6349 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6350                             const gdb_byte *info_ptr,
6351                             struct die_info *type_unit_die,
6352                             int has_children,
6353                             void *data)
6354 {
6355   struct objfile *objfile = dwarf2_per_objfile->objfile;
6356   struct dwarf2_cu *cu = reader->cu;
6357   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6358   struct signatured_type *sig_type;
6359   struct type_unit_group *tu_group;
6360   struct attribute *attr;
6361   struct partial_die_info *first_die;
6362   CORE_ADDR lowpc, highpc;
6363   struct partial_symtab *pst;
6364
6365   gdb_assert (data == NULL);
6366   gdb_assert (per_cu->is_debug_types);
6367   sig_type = (struct signatured_type *) per_cu;
6368
6369   if (! has_children)
6370     return;
6371
6372   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6373   tu_group = get_type_unit_group (cu, attr);
6374
6375   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6376
6377   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6378   cu->list_in_scope = &file_symbols;
6379   pst = create_partial_symtab (per_cu, "");
6380   pst->anonymous = 1;
6381
6382   first_die = load_partial_dies (reader, info_ptr, 1);
6383
6384   lowpc = (CORE_ADDR) -1;
6385   highpc = (CORE_ADDR) 0;
6386   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6387
6388   end_psymtab_common (objfile, pst);
6389 }
6390
6391 /* Struct used to sort TUs by their abbreviation table offset.  */
6392
6393 struct tu_abbrev_offset
6394 {
6395   struct signatured_type *sig_type;
6396   sect_offset abbrev_offset;
6397 };
6398
6399 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6400
6401 static int
6402 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6403 {
6404   const struct tu_abbrev_offset * const *a
6405     = (const struct tu_abbrev_offset * const*) ap;
6406   const struct tu_abbrev_offset * const *b
6407     = (const struct tu_abbrev_offset * const*) bp;
6408   sect_offset aoff = (*a)->abbrev_offset;
6409   sect_offset boff = (*b)->abbrev_offset;
6410
6411   return (aoff > boff) - (aoff < boff);
6412 }
6413
6414 /* Efficiently read all the type units.
6415    This does the bulk of the work for build_type_psymtabs.
6416
6417    The efficiency is because we sort TUs by the abbrev table they use and
6418    only read each abbrev table once.  In one program there are 200K TUs
6419    sharing 8K abbrev tables.
6420
6421    The main purpose of this function is to support building the
6422    dwarf2_per_objfile->type_unit_groups table.
6423    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6424    can collapse the search space by grouping them by stmt_list.
6425    The savings can be significant, in the same program from above the 200K TUs
6426    share 8K stmt_list tables.
6427
6428    FUNC is expected to call get_type_unit_group, which will create the
6429    struct type_unit_group if necessary and add it to
6430    dwarf2_per_objfile->type_unit_groups.  */
6431
6432 static void
6433 build_type_psymtabs_1 (void)
6434 {
6435   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6436   struct cleanup *cleanups;
6437   struct abbrev_table *abbrev_table;
6438   sect_offset abbrev_offset;
6439   struct tu_abbrev_offset *sorted_by_abbrev;
6440   int i;
6441
6442   /* It's up to the caller to not call us multiple times.  */
6443   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6444
6445   if (dwarf2_per_objfile->n_type_units == 0)
6446     return;
6447
6448   /* TUs typically share abbrev tables, and there can be way more TUs than
6449      abbrev tables.  Sort by abbrev table to reduce the number of times we
6450      read each abbrev table in.
6451      Alternatives are to punt or to maintain a cache of abbrev tables.
6452      This is simpler and efficient enough for now.
6453
6454      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6455      symtab to use).  Typically TUs with the same abbrev offset have the same
6456      stmt_list value too so in practice this should work well.
6457
6458      The basic algorithm here is:
6459
6460       sort TUs by abbrev table
6461       for each TU with same abbrev table:
6462         read abbrev table if first user
6463         read TU top level DIE
6464           [IWBN if DWO skeletons had DW_AT_stmt_list]
6465         call FUNC  */
6466
6467   if (dwarf_read_debug)
6468     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6469
6470   /* Sort in a separate table to maintain the order of all_type_units
6471      for .gdb_index: TU indices directly index all_type_units.  */
6472   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6473                               dwarf2_per_objfile->n_type_units);
6474   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6475     {
6476       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6477
6478       sorted_by_abbrev[i].sig_type = sig_type;
6479       sorted_by_abbrev[i].abbrev_offset =
6480         read_abbrev_offset (sig_type->per_cu.section,
6481                             sig_type->per_cu.sect_off);
6482     }
6483   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6484   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6485          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6486
6487   abbrev_offset = (sect_offset) ~(unsigned) 0;
6488   abbrev_table = NULL;
6489   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6490
6491   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6492     {
6493       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6494
6495       /* Switch to the next abbrev table if necessary.  */
6496       if (abbrev_table == NULL
6497           || tu->abbrev_offset != abbrev_offset)
6498         {
6499           if (abbrev_table != NULL)
6500             {
6501               abbrev_table_free (abbrev_table);
6502               /* Reset to NULL in case abbrev_table_read_table throws
6503                  an error: abbrev_table_free_cleanup will get called.  */
6504               abbrev_table = NULL;
6505             }
6506           abbrev_offset = tu->abbrev_offset;
6507           abbrev_table =
6508             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6509                                      abbrev_offset);
6510           ++tu_stats->nr_uniq_abbrev_tables;
6511         }
6512
6513       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6514                                build_type_psymtabs_reader, NULL);
6515     }
6516
6517   do_cleanups (cleanups);
6518 }
6519
6520 /* Print collected type unit statistics.  */
6521
6522 static void
6523 print_tu_stats (void)
6524 {
6525   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6526
6527   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6528   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6529                       dwarf2_per_objfile->n_type_units);
6530   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6531                       tu_stats->nr_uniq_abbrev_tables);
6532   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6533                       tu_stats->nr_symtabs);
6534   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6535                       tu_stats->nr_symtab_sharers);
6536   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6537                       tu_stats->nr_stmt_less_type_units);
6538   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6539                       tu_stats->nr_all_type_units_reallocs);
6540 }
6541
6542 /* Traversal function for build_type_psymtabs.  */
6543
6544 static int
6545 build_type_psymtab_dependencies (void **slot, void *info)
6546 {
6547   struct objfile *objfile = dwarf2_per_objfile->objfile;
6548   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6549   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6550   struct partial_symtab *pst = per_cu->v.psymtab;
6551   int len = VEC_length (sig_type_ptr, tu_group->tus);
6552   struct signatured_type *iter;
6553   int i;
6554
6555   gdb_assert (len > 0);
6556   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6557
6558   pst->number_of_dependencies = len;
6559   pst->dependencies =
6560     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6561   for (i = 0;
6562        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6563        ++i)
6564     {
6565       gdb_assert (iter->per_cu.is_debug_types);
6566       pst->dependencies[i] = iter->per_cu.v.psymtab;
6567       iter->type_unit_group = tu_group;
6568     }
6569
6570   VEC_free (sig_type_ptr, tu_group->tus);
6571
6572   return 1;
6573 }
6574
6575 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6576    Build partial symbol tables for the .debug_types comp-units.  */
6577
6578 static void
6579 build_type_psymtabs (struct objfile *objfile)
6580 {
6581   if (! create_all_type_units (objfile))
6582     return;
6583
6584   build_type_psymtabs_1 ();
6585 }
6586
6587 /* Traversal function for process_skeletonless_type_unit.
6588    Read a TU in a DWO file and build partial symbols for it.  */
6589
6590 static int
6591 process_skeletonless_type_unit (void **slot, void *info)
6592 {
6593   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6594   struct objfile *objfile = (struct objfile *) info;
6595   struct signatured_type find_entry, *entry;
6596
6597   /* If this TU doesn't exist in the global table, add it and read it in.  */
6598
6599   if (dwarf2_per_objfile->signatured_types == NULL)
6600     {
6601       dwarf2_per_objfile->signatured_types
6602         = allocate_signatured_type_table (objfile);
6603     }
6604
6605   find_entry.signature = dwo_unit->signature;
6606   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6607                          INSERT);
6608   /* If we've already seen this type there's nothing to do.  What's happening
6609      is we're doing our own version of comdat-folding here.  */
6610   if (*slot != NULL)
6611     return 1;
6612
6613   /* This does the job that create_all_type_units would have done for
6614      this TU.  */
6615   entry = add_type_unit (dwo_unit->signature, slot);
6616   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6617   *slot = entry;
6618
6619   /* This does the job that build_type_psymtabs_1 would have done.  */
6620   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6621                            build_type_psymtabs_reader, NULL);
6622
6623   return 1;
6624 }
6625
6626 /* Traversal function for process_skeletonless_type_units.  */
6627
6628 static int
6629 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6630 {
6631   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6632
6633   if (dwo_file->tus != NULL)
6634     {
6635       htab_traverse_noresize (dwo_file->tus,
6636                               process_skeletonless_type_unit, info);
6637     }
6638
6639   return 1;
6640 }
6641
6642 /* Scan all TUs of DWO files, verifying we've processed them.
6643    This is needed in case a TU was emitted without its skeleton.
6644    Note: This can't be done until we know what all the DWO files are.  */
6645
6646 static void
6647 process_skeletonless_type_units (struct objfile *objfile)
6648 {
6649   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6650   if (get_dwp_file () == NULL
6651       && dwarf2_per_objfile->dwo_files != NULL)
6652     {
6653       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6654                               process_dwo_file_for_skeletonless_type_units,
6655                               objfile);
6656     }
6657 }
6658
6659 /* A cleanup function that clears objfile's psymtabs_addrmap field.  */
6660
6661 static void
6662 psymtabs_addrmap_cleanup (void *o)
6663 {
6664   struct objfile *objfile = (struct objfile *) o;
6665
6666   objfile->psymtabs_addrmap = NULL;
6667 }
6668
6669 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6670
6671 static void
6672 set_partial_user (struct objfile *objfile)
6673 {
6674   int i;
6675
6676   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6677     {
6678       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6679       struct partial_symtab *pst = per_cu->v.psymtab;
6680       int j;
6681
6682       if (pst == NULL)
6683         continue;
6684
6685       for (j = 0; j < pst->number_of_dependencies; ++j)
6686         {
6687           /* Set the 'user' field only if it is not already set.  */
6688           if (pst->dependencies[j]->user == NULL)
6689             pst->dependencies[j]->user = pst;
6690         }
6691     }
6692 }
6693
6694 /* Build the partial symbol table by doing a quick pass through the
6695    .debug_info and .debug_abbrev sections.  */
6696
6697 static void
6698 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6699 {
6700   struct cleanup *back_to, *addrmap_cleanup;
6701   int i;
6702
6703   if (dwarf_read_debug)
6704     {
6705       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6706                           objfile_name (objfile));
6707     }
6708
6709   dwarf2_per_objfile->reading_partial_symbols = 1;
6710
6711   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6712
6713   /* Any cached compilation units will be linked by the per-objfile
6714      read_in_chain.  Make sure to free them when we're done.  */
6715   back_to = make_cleanup (free_cached_comp_units, NULL);
6716
6717   build_type_psymtabs (objfile);
6718
6719   create_all_comp_units (objfile);
6720
6721   /* Create a temporary address map on a temporary obstack.  We later
6722      copy this to the final obstack.  */
6723   auto_obstack temp_obstack;
6724   objfile->psymtabs_addrmap = addrmap_create_mutable (&temp_obstack);
6725   addrmap_cleanup = make_cleanup (psymtabs_addrmap_cleanup, objfile);
6726
6727   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6728     {
6729       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6730
6731       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6732     }
6733
6734   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6735   process_skeletonless_type_units (objfile);
6736
6737   /* Now that all TUs have been processed we can fill in the dependencies.  */
6738   if (dwarf2_per_objfile->type_unit_groups != NULL)
6739     {
6740       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6741                               build_type_psymtab_dependencies, NULL);
6742     }
6743
6744   if (dwarf_read_debug)
6745     print_tu_stats ();
6746
6747   set_partial_user (objfile);
6748
6749   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6750                                                     &objfile->objfile_obstack);
6751   discard_cleanups (addrmap_cleanup);
6752
6753   do_cleanups (back_to);
6754
6755   if (dwarf_read_debug)
6756     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6757                         objfile_name (objfile));
6758 }
6759
6760 /* die_reader_func for load_partial_comp_unit.  */
6761
6762 static void
6763 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6764                                const gdb_byte *info_ptr,
6765                                struct die_info *comp_unit_die,
6766                                int has_children,
6767                                void *data)
6768 {
6769   struct dwarf2_cu *cu = reader->cu;
6770
6771   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6772
6773   /* Check if comp unit has_children.
6774      If so, read the rest of the partial symbols from this comp unit.
6775      If not, there's no more debug_info for this comp unit.  */
6776   if (has_children)
6777     load_partial_dies (reader, info_ptr, 0);
6778 }
6779
6780 /* Load the partial DIEs for a secondary CU into memory.
6781    This is also used when rereading a primary CU with load_all_dies.  */
6782
6783 static void
6784 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6785 {
6786   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6787                            load_partial_comp_unit_reader, NULL);
6788 }
6789
6790 static void
6791 read_comp_units_from_section (struct objfile *objfile,
6792                               struct dwarf2_section_info *section,
6793                               struct dwarf2_section_info *abbrev_section,
6794                               unsigned int is_dwz,
6795                               int *n_allocated,
6796                               int *n_comp_units,
6797                               struct dwarf2_per_cu_data ***all_comp_units)
6798 {
6799   const gdb_byte *info_ptr;
6800   bfd *abfd = get_section_bfd_owner (section);
6801
6802   if (dwarf_read_debug)
6803     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6804                         get_section_name (section),
6805                         get_section_file_name (section));
6806
6807   dwarf2_read_section (objfile, section);
6808
6809   info_ptr = section->buffer;
6810
6811   while (info_ptr < section->buffer + section->size)
6812     {
6813       struct dwarf2_per_cu_data *this_cu;
6814
6815       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6816
6817       comp_unit_head cu_header;
6818       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6819                                      info_ptr, rcuh_kind::COMPILE);
6820
6821       /* Save the compilation unit for later lookup.  */
6822       if (cu_header.unit_type != DW_UT_type)
6823         {
6824           this_cu = XOBNEW (&objfile->objfile_obstack,
6825                             struct dwarf2_per_cu_data);
6826           memset (this_cu, 0, sizeof (*this_cu));
6827         }
6828       else
6829         {
6830           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6831                                   struct signatured_type);
6832           memset (sig_type, 0, sizeof (*sig_type));
6833           sig_type->signature = cu_header.signature;
6834           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6835           this_cu = &sig_type->per_cu;
6836         }
6837       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6838       this_cu->sect_off = sect_off;
6839       this_cu->length = cu_header.length + cu_header.initial_length_size;
6840       this_cu->is_dwz = is_dwz;
6841       this_cu->objfile = objfile;
6842       this_cu->section = section;
6843
6844       if (*n_comp_units == *n_allocated)
6845         {
6846           *n_allocated *= 2;
6847           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6848                                         *all_comp_units, *n_allocated);
6849         }
6850       (*all_comp_units)[*n_comp_units] = this_cu;
6851       ++*n_comp_units;
6852
6853       info_ptr = info_ptr + this_cu->length;
6854     }
6855 }
6856
6857 /* Create a list of all compilation units in OBJFILE.
6858    This is only done for -readnow and building partial symtabs.  */
6859
6860 static void
6861 create_all_comp_units (struct objfile *objfile)
6862 {
6863   int n_allocated;
6864   int n_comp_units;
6865   struct dwarf2_per_cu_data **all_comp_units;
6866   struct dwz_file *dwz;
6867
6868   n_comp_units = 0;
6869   n_allocated = 10;
6870   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6871
6872   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6873                                 &dwarf2_per_objfile->abbrev, 0,
6874                                 &n_allocated, &n_comp_units, &all_comp_units);
6875
6876   dwz = dwarf2_get_dwz_file ();
6877   if (dwz != NULL)
6878     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6879                                   &n_allocated, &n_comp_units,
6880                                   &all_comp_units);
6881
6882   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6883                                                   struct dwarf2_per_cu_data *,
6884                                                   n_comp_units);
6885   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6886           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6887   xfree (all_comp_units);
6888   dwarf2_per_objfile->n_comp_units = n_comp_units;
6889 }
6890
6891 /* Process all loaded DIEs for compilation unit CU, starting at
6892    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6893    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6894    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6895    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6896
6897 static void
6898 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6899                       CORE_ADDR *highpc, int set_addrmap,
6900                       struct dwarf2_cu *cu)
6901 {
6902   struct partial_die_info *pdi;
6903
6904   /* Now, march along the PDI's, descending into ones which have
6905      interesting children but skipping the children of the other ones,
6906      until we reach the end of the compilation unit.  */
6907
6908   pdi = first_die;
6909
6910   while (pdi != NULL)
6911     {
6912       fixup_partial_die (pdi, cu);
6913
6914       /* Anonymous namespaces or modules have no name but have interesting
6915          children, so we need to look at them.  Ditto for anonymous
6916          enums.  */
6917
6918       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6919           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6920           || pdi->tag == DW_TAG_imported_unit)
6921         {
6922           switch (pdi->tag)
6923             {
6924             case DW_TAG_subprogram:
6925               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6926               break;
6927             case DW_TAG_constant:
6928             case DW_TAG_variable:
6929             case DW_TAG_typedef:
6930             case DW_TAG_union_type:
6931               if (!pdi->is_declaration)
6932                 {
6933                   add_partial_symbol (pdi, cu);
6934                 }
6935               break;
6936             case DW_TAG_class_type:
6937             case DW_TAG_interface_type:
6938             case DW_TAG_structure_type:
6939               if (!pdi->is_declaration)
6940                 {
6941                   add_partial_symbol (pdi, cu);
6942                 }
6943               if (cu->language == language_rust && pdi->has_children)
6944                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6945                                       set_addrmap, cu);
6946               break;
6947             case DW_TAG_enumeration_type:
6948               if (!pdi->is_declaration)
6949                 add_partial_enumeration (pdi, cu);
6950               break;
6951             case DW_TAG_base_type:
6952             case DW_TAG_subrange_type:
6953               /* File scope base type definitions are added to the partial
6954                  symbol table.  */
6955               add_partial_symbol (pdi, cu);
6956               break;
6957             case DW_TAG_namespace:
6958               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6959               break;
6960             case DW_TAG_module:
6961               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6962               break;
6963             case DW_TAG_imported_unit:
6964               {
6965                 struct dwarf2_per_cu_data *per_cu;
6966
6967                 /* For now we don't handle imported units in type units.  */
6968                 if (cu->per_cu->is_debug_types)
6969                   {
6970                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6971                              " supported in type units [in module %s]"),
6972                            objfile_name (cu->objfile));
6973                   }
6974
6975                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6976                                                            pdi->is_dwz,
6977                                                            cu->objfile);
6978
6979                 /* Go read the partial unit, if needed.  */
6980                 if (per_cu->v.psymtab == NULL)
6981                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6982
6983                 VEC_safe_push (dwarf2_per_cu_ptr,
6984                                cu->per_cu->imported_symtabs, per_cu);
6985               }
6986               break;
6987             case DW_TAG_imported_declaration:
6988               add_partial_symbol (pdi, cu);
6989               break;
6990             default:
6991               break;
6992             }
6993         }
6994
6995       /* If the die has a sibling, skip to the sibling.  */
6996
6997       pdi = pdi->die_sibling;
6998     }
6999 }
7000
7001 /* Functions used to compute the fully scoped name of a partial DIE.
7002
7003    Normally, this is simple.  For C++, the parent DIE's fully scoped
7004    name is concatenated with "::" and the partial DIE's name.
7005    Enumerators are an exception; they use the scope of their parent
7006    enumeration type, i.e. the name of the enumeration type is not
7007    prepended to the enumerator.
7008
7009    There are two complexities.  One is DW_AT_specification; in this
7010    case "parent" means the parent of the target of the specification,
7011    instead of the direct parent of the DIE.  The other is compilers
7012    which do not emit DW_TAG_namespace; in this case we try to guess
7013    the fully qualified name of structure types from their members'
7014    linkage names.  This must be done using the DIE's children rather
7015    than the children of any DW_AT_specification target.  We only need
7016    to do this for structures at the top level, i.e. if the target of
7017    any DW_AT_specification (if any; otherwise the DIE itself) does not
7018    have a parent.  */
7019
7020 /* Compute the scope prefix associated with PDI's parent, in
7021    compilation unit CU.  The result will be allocated on CU's
7022    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7023    field.  NULL is returned if no prefix is necessary.  */
7024 static const char *
7025 partial_die_parent_scope (struct partial_die_info *pdi,
7026                           struct dwarf2_cu *cu)
7027 {
7028   const char *grandparent_scope;
7029   struct partial_die_info *parent, *real_pdi;
7030
7031   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7032      then this means the parent of the specification DIE.  */
7033
7034   real_pdi = pdi;
7035   while (real_pdi->has_specification)
7036     real_pdi = find_partial_die (real_pdi->spec_offset,
7037                                  real_pdi->spec_is_dwz, cu);
7038
7039   parent = real_pdi->die_parent;
7040   if (parent == NULL)
7041     return NULL;
7042
7043   if (parent->scope_set)
7044     return parent->scope;
7045
7046   fixup_partial_die (parent, cu);
7047
7048   grandparent_scope = partial_die_parent_scope (parent, cu);
7049
7050   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7051      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7052      Work around this problem here.  */
7053   if (cu->language == language_cplus
7054       && parent->tag == DW_TAG_namespace
7055       && strcmp (parent->name, "::") == 0
7056       && grandparent_scope == NULL)
7057     {
7058       parent->scope = NULL;
7059       parent->scope_set = 1;
7060       return NULL;
7061     }
7062
7063   if (pdi->tag == DW_TAG_enumerator)
7064     /* Enumerators should not get the name of the enumeration as a prefix.  */
7065     parent->scope = grandparent_scope;
7066   else if (parent->tag == DW_TAG_namespace
7067       || parent->tag == DW_TAG_module
7068       || parent->tag == DW_TAG_structure_type
7069       || parent->tag == DW_TAG_class_type
7070       || parent->tag == DW_TAG_interface_type
7071       || parent->tag == DW_TAG_union_type
7072       || parent->tag == DW_TAG_enumeration_type)
7073     {
7074       if (grandparent_scope == NULL)
7075         parent->scope = parent->name;
7076       else
7077         parent->scope = typename_concat (&cu->comp_unit_obstack,
7078                                          grandparent_scope,
7079                                          parent->name, 0, cu);
7080     }
7081   else
7082     {
7083       /* FIXME drow/2004-04-01: What should we be doing with
7084          function-local names?  For partial symbols, we should probably be
7085          ignoring them.  */
7086       complaint (&symfile_complaints,
7087                  _("unhandled containing DIE tag %d for DIE at %d"),
7088                  parent->tag, to_underlying (pdi->sect_off));
7089       parent->scope = grandparent_scope;
7090     }
7091
7092   parent->scope_set = 1;
7093   return parent->scope;
7094 }
7095
7096 /* Return the fully scoped name associated with PDI, from compilation unit
7097    CU.  The result will be allocated with malloc.  */
7098
7099 static char *
7100 partial_die_full_name (struct partial_die_info *pdi,
7101                        struct dwarf2_cu *cu)
7102 {
7103   const char *parent_scope;
7104
7105   /* If this is a template instantiation, we can not work out the
7106      template arguments from partial DIEs.  So, unfortunately, we have
7107      to go through the full DIEs.  At least any work we do building
7108      types here will be reused if full symbols are loaded later.  */
7109   if (pdi->has_template_arguments)
7110     {
7111       fixup_partial_die (pdi, cu);
7112
7113       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7114         {
7115           struct die_info *die;
7116           struct attribute attr;
7117           struct dwarf2_cu *ref_cu = cu;
7118
7119           /* DW_FORM_ref_addr is using section offset.  */
7120           attr.name = (enum dwarf_attribute) 0;
7121           attr.form = DW_FORM_ref_addr;
7122           attr.u.unsnd = to_underlying (pdi->sect_off);
7123           die = follow_die_ref (NULL, &attr, &ref_cu);
7124
7125           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7126         }
7127     }
7128
7129   parent_scope = partial_die_parent_scope (pdi, cu);
7130   if (parent_scope == NULL)
7131     return NULL;
7132   else
7133     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7134 }
7135
7136 static void
7137 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7138 {
7139   struct objfile *objfile = cu->objfile;
7140   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7141   CORE_ADDR addr = 0;
7142   const char *actual_name = NULL;
7143   CORE_ADDR baseaddr;
7144   char *built_actual_name;
7145
7146   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7147
7148   built_actual_name = partial_die_full_name (pdi, cu);
7149   if (built_actual_name != NULL)
7150     actual_name = built_actual_name;
7151
7152   if (actual_name == NULL)
7153     actual_name = pdi->name;
7154
7155   switch (pdi->tag)
7156     {
7157     case DW_TAG_subprogram:
7158       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7159       if (pdi->is_external || cu->language == language_ada)
7160         {
7161           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7162              of the global scope.  But in Ada, we want to be able to access
7163              nested procedures globally.  So all Ada subprograms are stored
7164              in the global scope.  */
7165           add_psymbol_to_list (actual_name, strlen (actual_name),
7166                                built_actual_name != NULL,
7167                                VAR_DOMAIN, LOC_BLOCK,
7168                                &objfile->global_psymbols,
7169                                addr, cu->language, objfile);
7170         }
7171       else
7172         {
7173           add_psymbol_to_list (actual_name, strlen (actual_name),
7174                                built_actual_name != NULL,
7175                                VAR_DOMAIN, LOC_BLOCK,
7176                                &objfile->static_psymbols,
7177                                addr, cu->language, objfile);
7178         }
7179
7180       if (pdi->main_subprogram && actual_name != NULL)
7181         set_objfile_main_name (objfile, actual_name, cu->language);
7182       break;
7183     case DW_TAG_constant:
7184       {
7185         struct psymbol_allocation_list *list;
7186
7187         if (pdi->is_external)
7188           list = &objfile->global_psymbols;
7189         else
7190           list = &objfile->static_psymbols;
7191         add_psymbol_to_list (actual_name, strlen (actual_name),
7192                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7193                              list, 0, cu->language, objfile);
7194       }
7195       break;
7196     case DW_TAG_variable:
7197       if (pdi->d.locdesc)
7198         addr = decode_locdesc (pdi->d.locdesc, cu);
7199
7200       if (pdi->d.locdesc
7201           && addr == 0
7202           && !dwarf2_per_objfile->has_section_at_zero)
7203         {
7204           /* A global or static variable may also have been stripped
7205              out by the linker if unused, in which case its address
7206              will be nullified; do not add such variables into partial
7207              symbol table then.  */
7208         }
7209       else if (pdi->is_external)
7210         {
7211           /* Global Variable.
7212              Don't enter into the minimal symbol tables as there is
7213              a minimal symbol table entry from the ELF symbols already.
7214              Enter into partial symbol table if it has a location
7215              descriptor or a type.
7216              If the location descriptor is missing, new_symbol will create
7217              a LOC_UNRESOLVED symbol, the address of the variable will then
7218              be determined from the minimal symbol table whenever the variable
7219              is referenced.
7220              The address for the partial symbol table entry is not
7221              used by GDB, but it comes in handy for debugging partial symbol
7222              table building.  */
7223
7224           if (pdi->d.locdesc || pdi->has_type)
7225             add_psymbol_to_list (actual_name, strlen (actual_name),
7226                                  built_actual_name != NULL,
7227                                  VAR_DOMAIN, LOC_STATIC,
7228                                  &objfile->global_psymbols,
7229                                  addr + baseaddr,
7230                                  cu->language, objfile);
7231         }
7232       else
7233         {
7234           int has_loc = pdi->d.locdesc != NULL;
7235
7236           /* Static Variable.  Skip symbols whose value we cannot know (those
7237              without location descriptors or constant values).  */
7238           if (!has_loc && !pdi->has_const_value)
7239             {
7240               xfree (built_actual_name);
7241               return;
7242             }
7243
7244           add_psymbol_to_list (actual_name, strlen (actual_name),
7245                                built_actual_name != NULL,
7246                                VAR_DOMAIN, LOC_STATIC,
7247                                &objfile->static_psymbols,
7248                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7249                                cu->language, objfile);
7250         }
7251       break;
7252     case DW_TAG_typedef:
7253     case DW_TAG_base_type:
7254     case DW_TAG_subrange_type:
7255       add_psymbol_to_list (actual_name, strlen (actual_name),
7256                            built_actual_name != NULL,
7257                            VAR_DOMAIN, LOC_TYPEDEF,
7258                            &objfile->static_psymbols,
7259                            0, cu->language, objfile);
7260       break;
7261     case DW_TAG_imported_declaration:
7262     case DW_TAG_namespace:
7263       add_psymbol_to_list (actual_name, strlen (actual_name),
7264                            built_actual_name != NULL,
7265                            VAR_DOMAIN, LOC_TYPEDEF,
7266                            &objfile->global_psymbols,
7267                            0, cu->language, objfile);
7268       break;
7269     case DW_TAG_module:
7270       add_psymbol_to_list (actual_name, strlen (actual_name),
7271                            built_actual_name != NULL,
7272                            MODULE_DOMAIN, LOC_TYPEDEF,
7273                            &objfile->global_psymbols,
7274                            0, cu->language, objfile);
7275       break;
7276     case DW_TAG_class_type:
7277     case DW_TAG_interface_type:
7278     case DW_TAG_structure_type:
7279     case DW_TAG_union_type:
7280     case DW_TAG_enumeration_type:
7281       /* Skip external references.  The DWARF standard says in the section
7282          about "Structure, Union, and Class Type Entries": "An incomplete
7283          structure, union or class type is represented by a structure,
7284          union or class entry that does not have a byte size attribute
7285          and that has a DW_AT_declaration attribute."  */
7286       if (!pdi->has_byte_size && pdi->is_declaration)
7287         {
7288           xfree (built_actual_name);
7289           return;
7290         }
7291
7292       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7293          static vs. global.  */
7294       add_psymbol_to_list (actual_name, strlen (actual_name),
7295                            built_actual_name != NULL,
7296                            STRUCT_DOMAIN, LOC_TYPEDEF,
7297                            cu->language == language_cplus
7298                            ? &objfile->global_psymbols
7299                            : &objfile->static_psymbols,
7300                            0, cu->language, objfile);
7301
7302       break;
7303     case DW_TAG_enumerator:
7304       add_psymbol_to_list (actual_name, strlen (actual_name),
7305                            built_actual_name != NULL,
7306                            VAR_DOMAIN, LOC_CONST,
7307                            cu->language == language_cplus
7308                            ? &objfile->global_psymbols
7309                            : &objfile->static_psymbols,
7310                            0, cu->language, objfile);
7311       break;
7312     default:
7313       break;
7314     }
7315
7316   xfree (built_actual_name);
7317 }
7318
7319 /* Read a partial die corresponding to a namespace; also, add a symbol
7320    corresponding to that namespace to the symbol table.  NAMESPACE is
7321    the name of the enclosing namespace.  */
7322
7323 static void
7324 add_partial_namespace (struct partial_die_info *pdi,
7325                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7326                        int set_addrmap, struct dwarf2_cu *cu)
7327 {
7328   /* Add a symbol for the namespace.  */
7329
7330   add_partial_symbol (pdi, cu);
7331
7332   /* Now scan partial symbols in that namespace.  */
7333
7334   if (pdi->has_children)
7335     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7336 }
7337
7338 /* Read a partial die corresponding to a Fortran module.  */
7339
7340 static void
7341 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7342                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7343 {
7344   /* Add a symbol for the namespace.  */
7345
7346   add_partial_symbol (pdi, cu);
7347
7348   /* Now scan partial symbols in that module.  */
7349
7350   if (pdi->has_children)
7351     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7352 }
7353
7354 /* Read a partial die corresponding to a subprogram and create a partial
7355    symbol for that subprogram.  When the CU language allows it, this
7356    routine also defines a partial symbol for each nested subprogram
7357    that this subprogram contains.  If SET_ADDRMAP is true, record the
7358    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7359    and highest PC values found in PDI.
7360
7361    PDI may also be a lexical block, in which case we simply search
7362    recursively for subprograms defined inside that lexical block.
7363    Again, this is only performed when the CU language allows this
7364    type of definitions.  */
7365
7366 static void
7367 add_partial_subprogram (struct partial_die_info *pdi,
7368                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7369                         int set_addrmap, struct dwarf2_cu *cu)
7370 {
7371   if (pdi->tag == DW_TAG_subprogram)
7372     {
7373       if (pdi->has_pc_info)
7374         {
7375           if (pdi->lowpc < *lowpc)
7376             *lowpc = pdi->lowpc;
7377           if (pdi->highpc > *highpc)
7378             *highpc = pdi->highpc;
7379           if (set_addrmap)
7380             {
7381               struct objfile *objfile = cu->objfile;
7382               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7383               CORE_ADDR baseaddr;
7384               CORE_ADDR highpc;
7385               CORE_ADDR lowpc;
7386
7387               baseaddr = ANOFFSET (objfile->section_offsets,
7388                                    SECT_OFF_TEXT (objfile));
7389               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7390                                                   pdi->lowpc + baseaddr);
7391               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7392                                                    pdi->highpc + baseaddr);
7393               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7394                                  cu->per_cu->v.psymtab);
7395             }
7396         }
7397
7398       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7399         {
7400           if (!pdi->is_declaration)
7401             /* Ignore subprogram DIEs that do not have a name, they are
7402                illegal.  Do not emit a complaint at this point, we will
7403                do so when we convert this psymtab into a symtab.  */
7404             if (pdi->name)
7405               add_partial_symbol (pdi, cu);
7406         }
7407     }
7408
7409   if (! pdi->has_children)
7410     return;
7411
7412   if (cu->language == language_ada)
7413     {
7414       pdi = pdi->die_child;
7415       while (pdi != NULL)
7416         {
7417           fixup_partial_die (pdi, cu);
7418           if (pdi->tag == DW_TAG_subprogram
7419               || pdi->tag == DW_TAG_lexical_block)
7420             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7421           pdi = pdi->die_sibling;
7422         }
7423     }
7424 }
7425
7426 /* Read a partial die corresponding to an enumeration type.  */
7427
7428 static void
7429 add_partial_enumeration (struct partial_die_info *enum_pdi,
7430                          struct dwarf2_cu *cu)
7431 {
7432   struct partial_die_info *pdi;
7433
7434   if (enum_pdi->name != NULL)
7435     add_partial_symbol (enum_pdi, cu);
7436
7437   pdi = enum_pdi->die_child;
7438   while (pdi)
7439     {
7440       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7441         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7442       else
7443         add_partial_symbol (pdi, cu);
7444       pdi = pdi->die_sibling;
7445     }
7446 }
7447
7448 /* Return the initial uleb128 in the die at INFO_PTR.  */
7449
7450 static unsigned int
7451 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7452 {
7453   unsigned int bytes_read;
7454
7455   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7456 }
7457
7458 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7459    Return the corresponding abbrev, or NULL if the number is zero (indicating
7460    an empty DIE).  In either case *BYTES_READ will be set to the length of
7461    the initial number.  */
7462
7463 static struct abbrev_info *
7464 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7465                  struct dwarf2_cu *cu)
7466 {
7467   bfd *abfd = cu->objfile->obfd;
7468   unsigned int abbrev_number;
7469   struct abbrev_info *abbrev;
7470
7471   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7472
7473   if (abbrev_number == 0)
7474     return NULL;
7475
7476   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7477   if (!abbrev)
7478     {
7479       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7480                " at offset 0x%x [in module %s]"),
7481              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7482              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7483     }
7484
7485   return abbrev;
7486 }
7487
7488 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7489    Returns a pointer to the end of a series of DIEs, terminated by an empty
7490    DIE.  Any children of the skipped DIEs will also be skipped.  */
7491
7492 static const gdb_byte *
7493 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7494 {
7495   struct dwarf2_cu *cu = reader->cu;
7496   struct abbrev_info *abbrev;
7497   unsigned int bytes_read;
7498
7499   while (1)
7500     {
7501       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7502       if (abbrev == NULL)
7503         return info_ptr + bytes_read;
7504       else
7505         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7506     }
7507 }
7508
7509 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7510    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7511    abbrev corresponding to that skipped uleb128 should be passed in
7512    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7513    children.  */
7514
7515 static const gdb_byte *
7516 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7517               struct abbrev_info *abbrev)
7518 {
7519   unsigned int bytes_read;
7520   struct attribute attr;
7521   bfd *abfd = reader->abfd;
7522   struct dwarf2_cu *cu = reader->cu;
7523   const gdb_byte *buffer = reader->buffer;
7524   const gdb_byte *buffer_end = reader->buffer_end;
7525   unsigned int form, i;
7526
7527   for (i = 0; i < abbrev->num_attrs; i++)
7528     {
7529       /* The only abbrev we care about is DW_AT_sibling.  */
7530       if (abbrev->attrs[i].name == DW_AT_sibling)
7531         {
7532           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7533           if (attr.form == DW_FORM_ref_addr)
7534             complaint (&symfile_complaints,
7535                        _("ignoring absolute DW_AT_sibling"));
7536           else
7537             {
7538               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7539               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7540
7541               if (sibling_ptr < info_ptr)
7542                 complaint (&symfile_complaints,
7543                            _("DW_AT_sibling points backwards"));
7544               else if (sibling_ptr > reader->buffer_end)
7545                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7546               else
7547                 return sibling_ptr;
7548             }
7549         }
7550
7551       /* If it isn't DW_AT_sibling, skip this attribute.  */
7552       form = abbrev->attrs[i].form;
7553     skip_attribute:
7554       switch (form)
7555         {
7556         case DW_FORM_ref_addr:
7557           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7558              and later it is offset sized.  */
7559           if (cu->header.version == 2)
7560             info_ptr += cu->header.addr_size;
7561           else
7562             info_ptr += cu->header.offset_size;
7563           break;
7564         case DW_FORM_GNU_ref_alt:
7565           info_ptr += cu->header.offset_size;
7566           break;
7567         case DW_FORM_addr:
7568           info_ptr += cu->header.addr_size;
7569           break;
7570         case DW_FORM_data1:
7571         case DW_FORM_ref1:
7572         case DW_FORM_flag:
7573           info_ptr += 1;
7574           break;
7575         case DW_FORM_flag_present:
7576         case DW_FORM_implicit_const:
7577           break;
7578         case DW_FORM_data2:
7579         case DW_FORM_ref2:
7580           info_ptr += 2;
7581           break;
7582         case DW_FORM_data4:
7583         case DW_FORM_ref4:
7584           info_ptr += 4;
7585           break;
7586         case DW_FORM_data8:
7587         case DW_FORM_ref8:
7588         case DW_FORM_ref_sig8:
7589           info_ptr += 8;
7590           break;
7591         case DW_FORM_data16:
7592           info_ptr += 16;
7593           break;
7594         case DW_FORM_string:
7595           read_direct_string (abfd, info_ptr, &bytes_read);
7596           info_ptr += bytes_read;
7597           break;
7598         case DW_FORM_sec_offset:
7599         case DW_FORM_strp:
7600         case DW_FORM_GNU_strp_alt:
7601           info_ptr += cu->header.offset_size;
7602           break;
7603         case DW_FORM_exprloc:
7604         case DW_FORM_block:
7605           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7606           info_ptr += bytes_read;
7607           break;
7608         case DW_FORM_block1:
7609           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7610           break;
7611         case DW_FORM_block2:
7612           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7613           break;
7614         case DW_FORM_block4:
7615           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7616           break;
7617         case DW_FORM_sdata:
7618         case DW_FORM_udata:
7619         case DW_FORM_ref_udata:
7620         case DW_FORM_GNU_addr_index:
7621         case DW_FORM_GNU_str_index:
7622           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7623           break;
7624         case DW_FORM_indirect:
7625           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7626           info_ptr += bytes_read;
7627           /* We need to continue parsing from here, so just go back to
7628              the top.  */
7629           goto skip_attribute;
7630
7631         default:
7632           error (_("Dwarf Error: Cannot handle %s "
7633                    "in DWARF reader [in module %s]"),
7634                  dwarf_form_name (form),
7635                  bfd_get_filename (abfd));
7636         }
7637     }
7638
7639   if (abbrev->has_children)
7640     return skip_children (reader, info_ptr);
7641   else
7642     return info_ptr;
7643 }
7644
7645 /* Locate ORIG_PDI's sibling.
7646    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7647
7648 static const gdb_byte *
7649 locate_pdi_sibling (const struct die_reader_specs *reader,
7650                     struct partial_die_info *orig_pdi,
7651                     const gdb_byte *info_ptr)
7652 {
7653   /* Do we know the sibling already?  */
7654
7655   if (orig_pdi->sibling)
7656     return orig_pdi->sibling;
7657
7658   /* Are there any children to deal with?  */
7659
7660   if (!orig_pdi->has_children)
7661     return info_ptr;
7662
7663   /* Skip the children the long way.  */
7664
7665   return skip_children (reader, info_ptr);
7666 }
7667
7668 /* Expand this partial symbol table into a full symbol table.  SELF is
7669    not NULL.  */
7670
7671 static void
7672 dwarf2_read_symtab (struct partial_symtab *self,
7673                     struct objfile *objfile)
7674 {
7675   if (self->readin)
7676     {
7677       warning (_("bug: psymtab for %s is already read in."),
7678                self->filename);
7679     }
7680   else
7681     {
7682       if (info_verbose)
7683         {
7684           printf_filtered (_("Reading in symbols for %s..."),
7685                            self->filename);
7686           gdb_flush (gdb_stdout);
7687         }
7688
7689       /* Restore our global data.  */
7690       dwarf2_per_objfile
7691         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7692                                                       dwarf2_objfile_data_key);
7693
7694       /* If this psymtab is constructed from a debug-only objfile, the
7695          has_section_at_zero flag will not necessarily be correct.  We
7696          can get the correct value for this flag by looking at the data
7697          associated with the (presumably stripped) associated objfile.  */
7698       if (objfile->separate_debug_objfile_backlink)
7699         {
7700           struct dwarf2_per_objfile *dpo_backlink
7701             = ((struct dwarf2_per_objfile *)
7702                objfile_data (objfile->separate_debug_objfile_backlink,
7703                              dwarf2_objfile_data_key));
7704
7705           dwarf2_per_objfile->has_section_at_zero
7706             = dpo_backlink->has_section_at_zero;
7707         }
7708
7709       dwarf2_per_objfile->reading_partial_symbols = 0;
7710
7711       psymtab_to_symtab_1 (self);
7712
7713       /* Finish up the debug error message.  */
7714       if (info_verbose)
7715         printf_filtered (_("done.\n"));
7716     }
7717
7718   process_cu_includes ();
7719 }
7720 \f
7721 /* Reading in full CUs.  */
7722
7723 /* Add PER_CU to the queue.  */
7724
7725 static void
7726 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7727                  enum language pretend_language)
7728 {
7729   struct dwarf2_queue_item *item;
7730
7731   per_cu->queued = 1;
7732   item = XNEW (struct dwarf2_queue_item);
7733   item->per_cu = per_cu;
7734   item->pretend_language = pretend_language;
7735   item->next = NULL;
7736
7737   if (dwarf2_queue == NULL)
7738     dwarf2_queue = item;
7739   else
7740     dwarf2_queue_tail->next = item;
7741
7742   dwarf2_queue_tail = item;
7743 }
7744
7745 /* If PER_CU is not yet queued, add it to the queue.
7746    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7747    dependency.
7748    The result is non-zero if PER_CU was queued, otherwise the result is zero
7749    meaning either PER_CU is already queued or it is already loaded.
7750
7751    N.B. There is an invariant here that if a CU is queued then it is loaded.
7752    The caller is required to load PER_CU if we return non-zero.  */
7753
7754 static int
7755 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7756                        struct dwarf2_per_cu_data *per_cu,
7757                        enum language pretend_language)
7758 {
7759   /* We may arrive here during partial symbol reading, if we need full
7760      DIEs to process an unusual case (e.g. template arguments).  Do
7761      not queue PER_CU, just tell our caller to load its DIEs.  */
7762   if (dwarf2_per_objfile->reading_partial_symbols)
7763     {
7764       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7765         return 1;
7766       return 0;
7767     }
7768
7769   /* Mark the dependence relation so that we don't flush PER_CU
7770      too early.  */
7771   if (dependent_cu != NULL)
7772     dwarf2_add_dependence (dependent_cu, per_cu);
7773
7774   /* If it's already on the queue, we have nothing to do.  */
7775   if (per_cu->queued)
7776     return 0;
7777
7778   /* If the compilation unit is already loaded, just mark it as
7779      used.  */
7780   if (per_cu->cu != NULL)
7781     {
7782       per_cu->cu->last_used = 0;
7783       return 0;
7784     }
7785
7786   /* Add it to the queue.  */
7787   queue_comp_unit (per_cu, pretend_language);
7788
7789   return 1;
7790 }
7791
7792 /* Process the queue.  */
7793
7794 static void
7795 process_queue (void)
7796 {
7797   struct dwarf2_queue_item *item, *next_item;
7798
7799   if (dwarf_read_debug)
7800     {
7801       fprintf_unfiltered (gdb_stdlog,
7802                           "Expanding one or more symtabs of objfile %s ...\n",
7803                           objfile_name (dwarf2_per_objfile->objfile));
7804     }
7805
7806   /* The queue starts out with one item, but following a DIE reference
7807      may load a new CU, adding it to the end of the queue.  */
7808   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7809     {
7810       if ((dwarf2_per_objfile->using_index
7811            ? !item->per_cu->v.quick->compunit_symtab
7812            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7813           /* Skip dummy CUs.  */
7814           && item->per_cu->cu != NULL)
7815         {
7816           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7817           unsigned int debug_print_threshold;
7818           char buf[100];
7819
7820           if (per_cu->is_debug_types)
7821             {
7822               struct signatured_type *sig_type =
7823                 (struct signatured_type *) per_cu;
7824
7825               sprintf (buf, "TU %s at offset 0x%x",
7826                        hex_string (sig_type->signature),
7827                        to_underlying (per_cu->sect_off));
7828               /* There can be 100s of TUs.
7829                  Only print them in verbose mode.  */
7830               debug_print_threshold = 2;
7831             }
7832           else
7833             {
7834               sprintf (buf, "CU at offset 0x%x",
7835                        to_underlying (per_cu->sect_off));
7836               debug_print_threshold = 1;
7837             }
7838
7839           if (dwarf_read_debug >= debug_print_threshold)
7840             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7841
7842           if (per_cu->is_debug_types)
7843             process_full_type_unit (per_cu, item->pretend_language);
7844           else
7845             process_full_comp_unit (per_cu, item->pretend_language);
7846
7847           if (dwarf_read_debug >= debug_print_threshold)
7848             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7849         }
7850
7851       item->per_cu->queued = 0;
7852       next_item = item->next;
7853       xfree (item);
7854     }
7855
7856   dwarf2_queue_tail = NULL;
7857
7858   if (dwarf_read_debug)
7859     {
7860       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7861                           objfile_name (dwarf2_per_objfile->objfile));
7862     }
7863 }
7864
7865 /* Free all allocated queue entries.  This function only releases anything if
7866    an error was thrown; if the queue was processed then it would have been
7867    freed as we went along.  */
7868
7869 static void
7870 dwarf2_release_queue (void *dummy)
7871 {
7872   struct dwarf2_queue_item *item, *last;
7873
7874   item = dwarf2_queue;
7875   while (item)
7876     {
7877       /* Anything still marked queued is likely to be in an
7878          inconsistent state, so discard it.  */
7879       if (item->per_cu->queued)
7880         {
7881           if (item->per_cu->cu != NULL)
7882             free_one_cached_comp_unit (item->per_cu);
7883           item->per_cu->queued = 0;
7884         }
7885
7886       last = item;
7887       item = item->next;
7888       xfree (last);
7889     }
7890
7891   dwarf2_queue = dwarf2_queue_tail = NULL;
7892 }
7893
7894 /* Read in full symbols for PST, and anything it depends on.  */
7895
7896 static void
7897 psymtab_to_symtab_1 (struct partial_symtab *pst)
7898 {
7899   struct dwarf2_per_cu_data *per_cu;
7900   int i;
7901
7902   if (pst->readin)
7903     return;
7904
7905   for (i = 0; i < pst->number_of_dependencies; i++)
7906     if (!pst->dependencies[i]->readin
7907         && pst->dependencies[i]->user == NULL)
7908       {
7909         /* Inform about additional files that need to be read in.  */
7910         if (info_verbose)
7911           {
7912             /* FIXME: i18n: Need to make this a single string.  */
7913             fputs_filtered (" ", gdb_stdout);
7914             wrap_here ("");
7915             fputs_filtered ("and ", gdb_stdout);
7916             wrap_here ("");
7917             printf_filtered ("%s...", pst->dependencies[i]->filename);
7918             wrap_here ("");     /* Flush output.  */
7919             gdb_flush (gdb_stdout);
7920           }
7921         psymtab_to_symtab_1 (pst->dependencies[i]);
7922       }
7923
7924   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7925
7926   if (per_cu == NULL)
7927     {
7928       /* It's an include file, no symbols to read for it.
7929          Everything is in the parent symtab.  */
7930       pst->readin = 1;
7931       return;
7932     }
7933
7934   dw2_do_instantiate_symtab (per_cu);
7935 }
7936
7937 /* Trivial hash function for die_info: the hash value of a DIE
7938    is its offset in .debug_info for this objfile.  */
7939
7940 static hashval_t
7941 die_hash (const void *item)
7942 {
7943   const struct die_info *die = (const struct die_info *) item;
7944
7945   return to_underlying (die->sect_off);
7946 }
7947
7948 /* Trivial comparison function for die_info structures: two DIEs
7949    are equal if they have the same offset.  */
7950
7951 static int
7952 die_eq (const void *item_lhs, const void *item_rhs)
7953 {
7954   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7955   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7956
7957   return die_lhs->sect_off == die_rhs->sect_off;
7958 }
7959
7960 /* die_reader_func for load_full_comp_unit.
7961    This is identical to read_signatured_type_reader,
7962    but is kept separate for now.  */
7963
7964 static void
7965 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7966                             const gdb_byte *info_ptr,
7967                             struct die_info *comp_unit_die,
7968                             int has_children,
7969                             void *data)
7970 {
7971   struct dwarf2_cu *cu = reader->cu;
7972   enum language *language_ptr = (enum language *) data;
7973
7974   gdb_assert (cu->die_hash == NULL);
7975   cu->die_hash =
7976     htab_create_alloc_ex (cu->header.length / 12,
7977                           die_hash,
7978                           die_eq,
7979                           NULL,
7980                           &cu->comp_unit_obstack,
7981                           hashtab_obstack_allocate,
7982                           dummy_obstack_deallocate);
7983
7984   if (has_children)
7985     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7986                                                   &info_ptr, comp_unit_die);
7987   cu->dies = comp_unit_die;
7988   /* comp_unit_die is not stored in die_hash, no need.  */
7989
7990   /* We try not to read any attributes in this function, because not
7991      all CUs needed for references have been loaded yet, and symbol
7992      table processing isn't initialized.  But we have to set the CU language,
7993      or we won't be able to build types correctly.
7994      Similarly, if we do not read the producer, we can not apply
7995      producer-specific interpretation.  */
7996   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7997 }
7998
7999 /* Load the DIEs associated with PER_CU into memory.  */
8000
8001 static void
8002 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8003                      enum language pretend_language)
8004 {
8005   gdb_assert (! this_cu->is_debug_types);
8006
8007   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8008                            load_full_comp_unit_reader, &pretend_language);
8009 }
8010
8011 /* Add a DIE to the delayed physname list.  */
8012
8013 static void
8014 add_to_method_list (struct type *type, int fnfield_index, int index,
8015                     const char *name, struct die_info *die,
8016                     struct dwarf2_cu *cu)
8017 {
8018   struct delayed_method_info mi;
8019   mi.type = type;
8020   mi.fnfield_index = fnfield_index;
8021   mi.index = index;
8022   mi.name = name;
8023   mi.die = die;
8024   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8025 }
8026
8027 /* A cleanup for freeing the delayed method list.  */
8028
8029 static void
8030 free_delayed_list (void *ptr)
8031 {
8032   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8033   if (cu->method_list != NULL)
8034     {
8035       VEC_free (delayed_method_info, cu->method_list);
8036       cu->method_list = NULL;
8037     }
8038 }
8039
8040 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8041    "const" / "volatile".  If so, decrements LEN by the length of the
8042    modifier and return true.  Otherwise return false.  */
8043
8044 template<size_t N>
8045 static bool
8046 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8047 {
8048   size_t mod_len = sizeof (mod) - 1;
8049   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8050     {
8051       len -= mod_len;
8052       return true;
8053     }
8054   return false;
8055 }
8056
8057 /* Compute the physnames of any methods on the CU's method list.
8058
8059    The computation of method physnames is delayed in order to avoid the
8060    (bad) condition that one of the method's formal parameters is of an as yet
8061    incomplete type.  */
8062
8063 static void
8064 compute_delayed_physnames (struct dwarf2_cu *cu)
8065 {
8066   int i;
8067   struct delayed_method_info *mi;
8068
8069   /* Only C++ delays computing physnames.  */
8070   if (VEC_empty (delayed_method_info, cu->method_list))
8071     return;
8072   gdb_assert (cu->language == language_cplus);
8073
8074   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8075     {
8076       const char *physname;
8077       struct fn_fieldlist *fn_flp
8078         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8079       physname = dwarf2_physname (mi->name, mi->die, cu);
8080       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8081         = physname ? physname : "";
8082
8083       /* Since there's no tag to indicate whether a method is a
8084          const/volatile overload, extract that information out of the
8085          demangled name.  */
8086       if (physname != NULL)
8087         {
8088           size_t len = strlen (physname);
8089
8090           while (1)
8091             {
8092               if (physname[len] == ')') /* shortcut */
8093                 break;
8094               else if (check_modifier (physname, len, " const"))
8095                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8096               else if (check_modifier (physname, len, " volatile"))
8097                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8098               else
8099                 break;
8100             }
8101         }
8102     }
8103 }
8104
8105 /* Go objects should be embedded in a DW_TAG_module DIE,
8106    and it's not clear if/how imported objects will appear.
8107    To keep Go support simple until that's worked out,
8108    go back through what we've read and create something usable.
8109    We could do this while processing each DIE, and feels kinda cleaner,
8110    but that way is more invasive.
8111    This is to, for example, allow the user to type "p var" or "b main"
8112    without having to specify the package name, and allow lookups
8113    of module.object to work in contexts that use the expression
8114    parser.  */
8115
8116 static void
8117 fixup_go_packaging (struct dwarf2_cu *cu)
8118 {
8119   char *package_name = NULL;
8120   struct pending *list;
8121   int i;
8122
8123   for (list = global_symbols; list != NULL; list = list->next)
8124     {
8125       for (i = 0; i < list->nsyms; ++i)
8126         {
8127           struct symbol *sym = list->symbol[i];
8128
8129           if (SYMBOL_LANGUAGE (sym) == language_go
8130               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8131             {
8132               char *this_package_name = go_symbol_package_name (sym);
8133
8134               if (this_package_name == NULL)
8135                 continue;
8136               if (package_name == NULL)
8137                 package_name = this_package_name;
8138               else
8139                 {
8140                   if (strcmp (package_name, this_package_name) != 0)
8141                     complaint (&symfile_complaints,
8142                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8143                                (symbol_symtab (sym) != NULL
8144                                 ? symtab_to_filename_for_display
8145                                     (symbol_symtab (sym))
8146                                 : objfile_name (cu->objfile)),
8147                                this_package_name, package_name);
8148                   xfree (this_package_name);
8149                 }
8150             }
8151         }
8152     }
8153
8154   if (package_name != NULL)
8155     {
8156       struct objfile *objfile = cu->objfile;
8157       const char *saved_package_name
8158         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8159                                         package_name,
8160                                         strlen (package_name));
8161       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8162                                      saved_package_name);
8163       struct symbol *sym;
8164
8165       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8166
8167       sym = allocate_symbol (objfile);
8168       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8169       SYMBOL_SET_NAMES (sym, saved_package_name,
8170                         strlen (saved_package_name), 0, objfile);
8171       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8172          e.g., "main" finds the "main" module and not C's main().  */
8173       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8174       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8175       SYMBOL_TYPE (sym) = type;
8176
8177       add_symbol_to_list (sym, &global_symbols);
8178
8179       xfree (package_name);
8180     }
8181 }
8182
8183 /* Return the symtab for PER_CU.  This works properly regardless of
8184    whether we're using the index or psymtabs.  */
8185
8186 static struct compunit_symtab *
8187 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8188 {
8189   return (dwarf2_per_objfile->using_index
8190           ? per_cu->v.quick->compunit_symtab
8191           : per_cu->v.psymtab->compunit_symtab);
8192 }
8193
8194 /* A helper function for computing the list of all symbol tables
8195    included by PER_CU.  */
8196
8197 static void
8198 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8199                                 htab_t all_children, htab_t all_type_symtabs,
8200                                 struct dwarf2_per_cu_data *per_cu,
8201                                 struct compunit_symtab *immediate_parent)
8202 {
8203   void **slot;
8204   int ix;
8205   struct compunit_symtab *cust;
8206   struct dwarf2_per_cu_data *iter;
8207
8208   slot = htab_find_slot (all_children, per_cu, INSERT);
8209   if (*slot != NULL)
8210     {
8211       /* This inclusion and its children have been processed.  */
8212       return;
8213     }
8214
8215   *slot = per_cu;
8216   /* Only add a CU if it has a symbol table.  */
8217   cust = get_compunit_symtab (per_cu);
8218   if (cust != NULL)
8219     {
8220       /* If this is a type unit only add its symbol table if we haven't
8221          seen it yet (type unit per_cu's can share symtabs).  */
8222       if (per_cu->is_debug_types)
8223         {
8224           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8225           if (*slot == NULL)
8226             {
8227               *slot = cust;
8228               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8229               if (cust->user == NULL)
8230                 cust->user = immediate_parent;
8231             }
8232         }
8233       else
8234         {
8235           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8236           if (cust->user == NULL)
8237             cust->user = immediate_parent;
8238         }
8239     }
8240
8241   for (ix = 0;
8242        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8243        ++ix)
8244     {
8245       recursively_compute_inclusions (result, all_children,
8246                                       all_type_symtabs, iter, cust);
8247     }
8248 }
8249
8250 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8251    PER_CU.  */
8252
8253 static void
8254 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8255 {
8256   gdb_assert (! per_cu->is_debug_types);
8257
8258   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8259     {
8260       int ix, len;
8261       struct dwarf2_per_cu_data *per_cu_iter;
8262       struct compunit_symtab *compunit_symtab_iter;
8263       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8264       htab_t all_children, all_type_symtabs;
8265       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8266
8267       /* If we don't have a symtab, we can just skip this case.  */
8268       if (cust == NULL)
8269         return;
8270
8271       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8272                                         NULL, xcalloc, xfree);
8273       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8274                                             NULL, xcalloc, xfree);
8275
8276       for (ix = 0;
8277            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8278                         ix, per_cu_iter);
8279            ++ix)
8280         {
8281           recursively_compute_inclusions (&result_symtabs, all_children,
8282                                           all_type_symtabs, per_cu_iter,
8283                                           cust);
8284         }
8285
8286       /* Now we have a transitive closure of all the included symtabs.  */
8287       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8288       cust->includes
8289         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8290                      struct compunit_symtab *, len + 1);
8291       for (ix = 0;
8292            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8293                         compunit_symtab_iter);
8294            ++ix)
8295         cust->includes[ix] = compunit_symtab_iter;
8296       cust->includes[len] = NULL;
8297
8298       VEC_free (compunit_symtab_ptr, result_symtabs);
8299       htab_delete (all_children);
8300       htab_delete (all_type_symtabs);
8301     }
8302 }
8303
8304 /* Compute the 'includes' field for the symtabs of all the CUs we just
8305    read.  */
8306
8307 static void
8308 process_cu_includes (void)
8309 {
8310   int ix;
8311   struct dwarf2_per_cu_data *iter;
8312
8313   for (ix = 0;
8314        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8315                     ix, iter);
8316        ++ix)
8317     {
8318       if (! iter->is_debug_types)
8319         compute_compunit_symtab_includes (iter);
8320     }
8321
8322   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8323 }
8324
8325 /* Generate full symbol information for PER_CU, whose DIEs have
8326    already been loaded into memory.  */
8327
8328 static void
8329 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8330                         enum language pretend_language)
8331 {
8332   struct dwarf2_cu *cu = per_cu->cu;
8333   struct objfile *objfile = per_cu->objfile;
8334   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8335   CORE_ADDR lowpc, highpc;
8336   struct compunit_symtab *cust;
8337   struct cleanup *back_to, *delayed_list_cleanup;
8338   CORE_ADDR baseaddr;
8339   struct block *static_block;
8340   CORE_ADDR addr;
8341
8342   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8343
8344   buildsym_init ();
8345   back_to = make_cleanup (really_free_pendings, NULL);
8346   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8347
8348   cu->list_in_scope = &file_symbols;
8349
8350   cu->language = pretend_language;
8351   cu->language_defn = language_def (cu->language);
8352
8353   /* Do line number decoding in read_file_scope () */
8354   process_die (cu->dies, cu);
8355
8356   /* For now fudge the Go package.  */
8357   if (cu->language == language_go)
8358     fixup_go_packaging (cu);
8359
8360   /* Now that we have processed all the DIEs in the CU, all the types 
8361      should be complete, and it should now be safe to compute all of the
8362      physnames.  */
8363   compute_delayed_physnames (cu);
8364   do_cleanups (delayed_list_cleanup);
8365
8366   /* Some compilers don't define a DW_AT_high_pc attribute for the
8367      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8368      it, by scanning the DIE's below the compilation unit.  */
8369   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8370
8371   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8372   static_block = end_symtab_get_static_block (addr, 0, 1);
8373
8374   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8375      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8376      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8377      addrmap to help ensure it has an accurate map of pc values belonging to
8378      this comp unit.  */
8379   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8380
8381   cust = end_symtab_from_static_block (static_block,
8382                                        SECT_OFF_TEXT (objfile), 0);
8383
8384   if (cust != NULL)
8385     {
8386       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8387
8388       /* Set symtab language to language from DW_AT_language.  If the
8389          compilation is from a C file generated by language preprocessors, do
8390          not set the language if it was already deduced by start_subfile.  */
8391       if (!(cu->language == language_c
8392             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8393         COMPUNIT_FILETABS (cust)->language = cu->language;
8394
8395       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8396          produce DW_AT_location with location lists but it can be possibly
8397          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8398          there were bugs in prologue debug info, fixed later in GCC-4.5
8399          by "unwind info for epilogues" patch (which is not directly related).
8400
8401          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8402          needed, it would be wrong due to missing DW_AT_producer there.
8403
8404          Still one can confuse GDB by using non-standard GCC compilation
8405          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8406          */ 
8407       if (cu->has_loclist && gcc_4_minor >= 5)
8408         cust->locations_valid = 1;
8409
8410       if (gcc_4_minor >= 5)
8411         cust->epilogue_unwind_valid = 1;
8412
8413       cust->call_site_htab = cu->call_site_htab;
8414     }
8415
8416   if (dwarf2_per_objfile->using_index)
8417     per_cu->v.quick->compunit_symtab = cust;
8418   else
8419     {
8420       struct partial_symtab *pst = per_cu->v.psymtab;
8421       pst->compunit_symtab = cust;
8422       pst->readin = 1;
8423     }
8424
8425   /* Push it for inclusion processing later.  */
8426   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8427
8428   do_cleanups (back_to);
8429 }
8430
8431 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8432    already been loaded into memory.  */
8433
8434 static void
8435 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8436                         enum language pretend_language)
8437 {
8438   struct dwarf2_cu *cu = per_cu->cu;
8439   struct objfile *objfile = per_cu->objfile;
8440   struct compunit_symtab *cust;
8441   struct cleanup *back_to, *delayed_list_cleanup;
8442   struct signatured_type *sig_type;
8443
8444   gdb_assert (per_cu->is_debug_types);
8445   sig_type = (struct signatured_type *) per_cu;
8446
8447   buildsym_init ();
8448   back_to = make_cleanup (really_free_pendings, NULL);
8449   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8450
8451   cu->list_in_scope = &file_symbols;
8452
8453   cu->language = pretend_language;
8454   cu->language_defn = language_def (cu->language);
8455
8456   /* The symbol tables are set up in read_type_unit_scope.  */
8457   process_die (cu->dies, cu);
8458
8459   /* For now fudge the Go package.  */
8460   if (cu->language == language_go)
8461     fixup_go_packaging (cu);
8462
8463   /* Now that we have processed all the DIEs in the CU, all the types 
8464      should be complete, and it should now be safe to compute all of the
8465      physnames.  */
8466   compute_delayed_physnames (cu);
8467   do_cleanups (delayed_list_cleanup);
8468
8469   /* TUs share symbol tables.
8470      If this is the first TU to use this symtab, complete the construction
8471      of it with end_expandable_symtab.  Otherwise, complete the addition of
8472      this TU's symbols to the existing symtab.  */
8473   if (sig_type->type_unit_group->compunit_symtab == NULL)
8474     {
8475       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8476       sig_type->type_unit_group->compunit_symtab = cust;
8477
8478       if (cust != NULL)
8479         {
8480           /* Set symtab language to language from DW_AT_language.  If the
8481              compilation is from a C file generated by language preprocessors,
8482              do not set the language if it was already deduced by
8483              start_subfile.  */
8484           if (!(cu->language == language_c
8485                 && COMPUNIT_FILETABS (cust)->language != language_c))
8486             COMPUNIT_FILETABS (cust)->language = cu->language;
8487         }
8488     }
8489   else
8490     {
8491       augment_type_symtab ();
8492       cust = sig_type->type_unit_group->compunit_symtab;
8493     }
8494
8495   if (dwarf2_per_objfile->using_index)
8496     per_cu->v.quick->compunit_symtab = cust;
8497   else
8498     {
8499       struct partial_symtab *pst = per_cu->v.psymtab;
8500       pst->compunit_symtab = cust;
8501       pst->readin = 1;
8502     }
8503
8504   do_cleanups (back_to);
8505 }
8506
8507 /* Process an imported unit DIE.  */
8508
8509 static void
8510 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8511 {
8512   struct attribute *attr;
8513
8514   /* For now we don't handle imported units in type units.  */
8515   if (cu->per_cu->is_debug_types)
8516     {
8517       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8518                " supported in type units [in module %s]"),
8519              objfile_name (cu->objfile));
8520     }
8521
8522   attr = dwarf2_attr (die, DW_AT_import, cu);
8523   if (attr != NULL)
8524     {
8525       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8526       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8527       dwarf2_per_cu_data *per_cu
8528         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8529
8530       /* If necessary, add it to the queue and load its DIEs.  */
8531       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8532         load_full_comp_unit (per_cu, cu->language);
8533
8534       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8535                      per_cu);
8536     }
8537 }
8538
8539 /* RAII object that represents a process_die scope: i.e.,
8540    starts/finishes processing a DIE.  */
8541 class process_die_scope
8542 {
8543 public:
8544   process_die_scope (die_info *die, dwarf2_cu *cu)
8545     : m_die (die), m_cu (cu)
8546   {
8547     /* We should only be processing DIEs not already in process.  */
8548     gdb_assert (!m_die->in_process);
8549     m_die->in_process = true;
8550   }
8551
8552   ~process_die_scope ()
8553   {
8554     m_die->in_process = false;
8555
8556     /* If we're done processing the DIE for the CU that owns the line
8557        header, we don't need the line header anymore.  */
8558     if (m_cu->line_header_die_owner == m_die)
8559       {
8560         delete m_cu->line_header;
8561         m_cu->line_header = NULL;
8562         m_cu->line_header_die_owner = NULL;
8563       }
8564   }
8565
8566 private:
8567   die_info *m_die;
8568   dwarf2_cu *m_cu;
8569 };
8570
8571 /* Process a die and its children.  */
8572
8573 static void
8574 process_die (struct die_info *die, struct dwarf2_cu *cu)
8575 {
8576   process_die_scope scope (die, cu);
8577
8578   switch (die->tag)
8579     {
8580     case DW_TAG_padding:
8581       break;
8582     case DW_TAG_compile_unit:
8583     case DW_TAG_partial_unit:
8584       read_file_scope (die, cu);
8585       break;
8586     case DW_TAG_type_unit:
8587       read_type_unit_scope (die, cu);
8588       break;
8589     case DW_TAG_subprogram:
8590     case DW_TAG_inlined_subroutine:
8591       read_func_scope (die, cu);
8592       break;
8593     case DW_TAG_lexical_block:
8594     case DW_TAG_try_block:
8595     case DW_TAG_catch_block:
8596       read_lexical_block_scope (die, cu);
8597       break;
8598     case DW_TAG_call_site:
8599     case DW_TAG_GNU_call_site:
8600       read_call_site_scope (die, cu);
8601       break;
8602     case DW_TAG_class_type:
8603     case DW_TAG_interface_type:
8604     case DW_TAG_structure_type:
8605     case DW_TAG_union_type:
8606       process_structure_scope (die, cu);
8607       break;
8608     case DW_TAG_enumeration_type:
8609       process_enumeration_scope (die, cu);
8610       break;
8611
8612     /* These dies have a type, but processing them does not create
8613        a symbol or recurse to process the children.  Therefore we can
8614        read them on-demand through read_type_die.  */
8615     case DW_TAG_subroutine_type:
8616     case DW_TAG_set_type:
8617     case DW_TAG_array_type:
8618     case DW_TAG_pointer_type:
8619     case DW_TAG_ptr_to_member_type:
8620     case DW_TAG_reference_type:
8621     case DW_TAG_rvalue_reference_type:
8622     case DW_TAG_string_type:
8623       break;
8624
8625     case DW_TAG_base_type:
8626     case DW_TAG_subrange_type:
8627     case DW_TAG_typedef:
8628       /* Add a typedef symbol for the type definition, if it has a
8629          DW_AT_name.  */
8630       new_symbol (die, read_type_die (die, cu), cu);
8631       break;
8632     case DW_TAG_common_block:
8633       read_common_block (die, cu);
8634       break;
8635     case DW_TAG_common_inclusion:
8636       break;
8637     case DW_TAG_namespace:
8638       cu->processing_has_namespace_info = 1;
8639       read_namespace (die, cu);
8640       break;
8641     case DW_TAG_module:
8642       cu->processing_has_namespace_info = 1;
8643       read_module (die, cu);
8644       break;
8645     case DW_TAG_imported_declaration:
8646       cu->processing_has_namespace_info = 1;
8647       if (read_namespace_alias (die, cu))
8648         break;
8649       /* The declaration is not a global namespace alias: fall through.  */
8650     case DW_TAG_imported_module:
8651       cu->processing_has_namespace_info = 1;
8652       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8653                                  || cu->language != language_fortran))
8654         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8655                    dwarf_tag_name (die->tag));
8656       read_import_statement (die, cu);
8657       break;
8658
8659     case DW_TAG_imported_unit:
8660       process_imported_unit_die (die, cu);
8661       break;
8662
8663     default:
8664       new_symbol (die, NULL, cu);
8665       break;
8666     }
8667 }
8668 \f
8669 /* DWARF name computation.  */
8670
8671 /* A helper function for dwarf2_compute_name which determines whether DIE
8672    needs to have the name of the scope prepended to the name listed in the
8673    die.  */
8674
8675 static int
8676 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8677 {
8678   struct attribute *attr;
8679
8680   switch (die->tag)
8681     {
8682     case DW_TAG_namespace:
8683     case DW_TAG_typedef:
8684     case DW_TAG_class_type:
8685     case DW_TAG_interface_type:
8686     case DW_TAG_structure_type:
8687     case DW_TAG_union_type:
8688     case DW_TAG_enumeration_type:
8689     case DW_TAG_enumerator:
8690     case DW_TAG_subprogram:
8691     case DW_TAG_inlined_subroutine:
8692     case DW_TAG_member:
8693     case DW_TAG_imported_declaration:
8694       return 1;
8695
8696     case DW_TAG_variable:
8697     case DW_TAG_constant:
8698       /* We only need to prefix "globally" visible variables.  These include
8699          any variable marked with DW_AT_external or any variable that
8700          lives in a namespace.  [Variables in anonymous namespaces
8701          require prefixing, but they are not DW_AT_external.]  */
8702
8703       if (dwarf2_attr (die, DW_AT_specification, cu))
8704         {
8705           struct dwarf2_cu *spec_cu = cu;
8706
8707           return die_needs_namespace (die_specification (die, &spec_cu),
8708                                       spec_cu);
8709         }
8710
8711       attr = dwarf2_attr (die, DW_AT_external, cu);
8712       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8713           && die->parent->tag != DW_TAG_module)
8714         return 0;
8715       /* A variable in a lexical block of some kind does not need a
8716          namespace, even though in C++ such variables may be external
8717          and have a mangled name.  */
8718       if (die->parent->tag ==  DW_TAG_lexical_block
8719           || die->parent->tag ==  DW_TAG_try_block
8720           || die->parent->tag ==  DW_TAG_catch_block
8721           || die->parent->tag == DW_TAG_subprogram)
8722         return 0;
8723       return 1;
8724
8725     default:
8726       return 0;
8727     }
8728 }
8729
8730 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
8731    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8732    defined for the given DIE.  */
8733
8734 static struct attribute *
8735 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
8736 {
8737   struct attribute *attr;
8738
8739   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8740   if (attr == NULL)
8741     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8742
8743   return attr;
8744 }
8745
8746 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
8747    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8748    defined for the given DIE.  */
8749
8750 static const char *
8751 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
8752 {
8753   const char *linkage_name;
8754
8755   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8756   if (linkage_name == NULL)
8757     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8758
8759   return linkage_name;
8760 }
8761
8762 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8763    compute the physname for the object, which include a method's:
8764    - formal parameters (C++),
8765    - receiver type (Go),
8766
8767    The term "physname" is a bit confusing.
8768    For C++, for example, it is the demangled name.
8769    For Go, for example, it's the mangled name.
8770
8771    For Ada, return the DIE's linkage name rather than the fully qualified
8772    name.  PHYSNAME is ignored..
8773
8774    The result is allocated on the objfile_obstack and canonicalized.  */
8775
8776 static const char *
8777 dwarf2_compute_name (const char *name,
8778                      struct die_info *die, struct dwarf2_cu *cu,
8779                      int physname)
8780 {
8781   struct objfile *objfile = cu->objfile;
8782
8783   if (name == NULL)
8784     name = dwarf2_name (die, cu);
8785
8786   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8787      but otherwise compute it by typename_concat inside GDB.
8788      FIXME: Actually this is not really true, or at least not always true.
8789      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8790      Fortran names because there is no mangling standard.  So new_symbol_full
8791      will set the demangled name to the result of dwarf2_full_name, and it is
8792      the demangled name that GDB uses if it exists.  */
8793   if (cu->language == language_ada
8794       || (cu->language == language_fortran && physname))
8795     {
8796       /* For Ada unit, we prefer the linkage name over the name, as
8797          the former contains the exported name, which the user expects
8798          to be able to reference.  Ideally, we want the user to be able
8799          to reference this entity using either natural or linkage name,
8800          but we haven't started looking at this enhancement yet.  */
8801       const char *linkage_name = dw2_linkage_name (die, cu);
8802
8803       if (linkage_name != NULL)
8804         return linkage_name;
8805     }
8806
8807   /* These are the only languages we know how to qualify names in.  */
8808   if (name != NULL
8809       && (cu->language == language_cplus
8810           || cu->language == language_fortran || cu->language == language_d
8811           || cu->language == language_rust))
8812     {
8813       if (die_needs_namespace (die, cu))
8814         {
8815           long length;
8816           const char *prefix;
8817           const char *canonical_name = NULL;
8818
8819           string_file buf;
8820
8821           prefix = determine_prefix (die, cu);
8822           if (*prefix != '\0')
8823             {
8824               char *prefixed_name = typename_concat (NULL, prefix, name,
8825                                                      physname, cu);
8826
8827               buf.puts (prefixed_name);
8828               xfree (prefixed_name);
8829             }
8830           else
8831             buf.puts (name);
8832
8833           /* Template parameters may be specified in the DIE's DW_AT_name, or
8834              as children with DW_TAG_template_type_param or
8835              DW_TAG_value_type_param.  If the latter, add them to the name
8836              here.  If the name already has template parameters, then
8837              skip this step; some versions of GCC emit both, and
8838              it is more efficient to use the pre-computed name.
8839
8840              Something to keep in mind about this process: it is very
8841              unlikely, or in some cases downright impossible, to produce
8842              something that will match the mangled name of a function.
8843              If the definition of the function has the same debug info,
8844              we should be able to match up with it anyway.  But fallbacks
8845              using the minimal symbol, for instance to find a method
8846              implemented in a stripped copy of libstdc++, will not work.
8847              If we do not have debug info for the definition, we will have to
8848              match them up some other way.
8849
8850              When we do name matching there is a related problem with function
8851              templates; two instantiated function templates are allowed to
8852              differ only by their return types, which we do not add here.  */
8853
8854           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8855             {
8856               struct attribute *attr;
8857               struct die_info *child;
8858               int first = 1;
8859
8860               die->building_fullname = 1;
8861
8862               for (child = die->child; child != NULL; child = child->sibling)
8863                 {
8864                   struct type *type;
8865                   LONGEST value;
8866                   const gdb_byte *bytes;
8867                   struct dwarf2_locexpr_baton *baton;
8868                   struct value *v;
8869
8870                   if (child->tag != DW_TAG_template_type_param
8871                       && child->tag != DW_TAG_template_value_param)
8872                     continue;
8873
8874                   if (first)
8875                     {
8876                       buf.puts ("<");
8877                       first = 0;
8878                     }
8879                   else
8880                     buf.puts (", ");
8881
8882                   attr = dwarf2_attr (child, DW_AT_type, cu);
8883                   if (attr == NULL)
8884                     {
8885                       complaint (&symfile_complaints,
8886                                  _("template parameter missing DW_AT_type"));
8887                       buf.puts ("UNKNOWN_TYPE");
8888                       continue;
8889                     }
8890                   type = die_type (child, cu);
8891
8892                   if (child->tag == DW_TAG_template_type_param)
8893                     {
8894                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8895                       continue;
8896                     }
8897
8898                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8899                   if (attr == NULL)
8900                     {
8901                       complaint (&symfile_complaints,
8902                                  _("template parameter missing "
8903                                    "DW_AT_const_value"));
8904                       buf.puts ("UNKNOWN_VALUE");
8905                       continue;
8906                     }
8907
8908                   dwarf2_const_value_attr (attr, type, name,
8909                                            &cu->comp_unit_obstack, cu,
8910                                            &value, &bytes, &baton);
8911
8912                   if (TYPE_NOSIGN (type))
8913                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8914                        changed, this can use value_print instead.  */
8915                     c_printchar (value, type, &buf);
8916                   else
8917                     {
8918                       struct value_print_options opts;
8919
8920                       if (baton != NULL)
8921                         v = dwarf2_evaluate_loc_desc (type, NULL,
8922                                                       baton->data,
8923                                                       baton->size,
8924                                                       baton->per_cu);
8925                       else if (bytes != NULL)
8926                         {
8927                           v = allocate_value (type);
8928                           memcpy (value_contents_writeable (v), bytes,
8929                                   TYPE_LENGTH (type));
8930                         }
8931                       else
8932                         v = value_from_longest (type, value);
8933
8934                       /* Specify decimal so that we do not depend on
8935                          the radix.  */
8936                       get_formatted_print_options (&opts, 'd');
8937                       opts.raw = 1;
8938                       value_print (v, &buf, &opts);
8939                       release_value (v);
8940                       value_free (v);
8941                     }
8942                 }
8943
8944               die->building_fullname = 0;
8945
8946               if (!first)
8947                 {
8948                   /* Close the argument list, with a space if necessary
8949                      (nested templates).  */
8950                   if (!buf.empty () && buf.string ().back () == '>')
8951                     buf.puts (" >");
8952                   else
8953                     buf.puts (">");
8954                 }
8955             }
8956
8957           /* For C++ methods, append formal parameter type
8958              information, if PHYSNAME.  */
8959
8960           if (physname && die->tag == DW_TAG_subprogram
8961               && cu->language == language_cplus)
8962             {
8963               struct type *type = read_type_die (die, cu);
8964
8965               c_type_print_args (type, &buf, 1, cu->language,
8966                                  &type_print_raw_options);
8967
8968               if (cu->language == language_cplus)
8969                 {
8970                   /* Assume that an artificial first parameter is
8971                      "this", but do not crash if it is not.  RealView
8972                      marks unnamed (and thus unused) parameters as
8973                      artificial; there is no way to differentiate
8974                      the two cases.  */
8975                   if (TYPE_NFIELDS (type) > 0
8976                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8977                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8978                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8979                                                                         0))))
8980                     buf.puts (" const");
8981                 }
8982             }
8983
8984           const std::string &intermediate_name = buf.string ();
8985
8986           if (cu->language == language_cplus)
8987             canonical_name
8988               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8989                                           &objfile->per_bfd->storage_obstack);
8990
8991           /* If we only computed INTERMEDIATE_NAME, or if
8992              INTERMEDIATE_NAME is already canonical, then we need to
8993              copy it to the appropriate obstack.  */
8994           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8995             name = ((const char *)
8996                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8997                                    intermediate_name.c_str (),
8998                                    intermediate_name.length ()));
8999           else
9000             name = canonical_name;
9001         }
9002     }
9003
9004   return name;
9005 }
9006
9007 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9008    If scope qualifiers are appropriate they will be added.  The result
9009    will be allocated on the storage_obstack, or NULL if the DIE does
9010    not have a name.  NAME may either be from a previous call to
9011    dwarf2_name or NULL.
9012
9013    The output string will be canonicalized (if C++).  */
9014
9015 static const char *
9016 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9017 {
9018   return dwarf2_compute_name (name, die, cu, 0);
9019 }
9020
9021 /* Construct a physname for the given DIE in CU.  NAME may either be
9022    from a previous call to dwarf2_name or NULL.  The result will be
9023    allocated on the objfile_objstack or NULL if the DIE does not have a
9024    name.
9025
9026    The output string will be canonicalized (if C++).  */
9027
9028 static const char *
9029 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9030 {
9031   struct objfile *objfile = cu->objfile;
9032   const char *retval, *mangled = NULL, *canon = NULL;
9033   struct cleanup *back_to;
9034   int need_copy = 1;
9035
9036   /* In this case dwarf2_compute_name is just a shortcut not building anything
9037      on its own.  */
9038   if (!die_needs_namespace (die, cu))
9039     return dwarf2_compute_name (name, die, cu, 1);
9040
9041   back_to = make_cleanup (null_cleanup, NULL);
9042
9043   mangled = dw2_linkage_name (die, cu);
9044
9045   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9046      See https://github.com/rust-lang/rust/issues/32925.  */
9047   if (cu->language == language_rust && mangled != NULL
9048       && strchr (mangled, '{') != NULL)
9049     mangled = NULL;
9050
9051   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9052      has computed.  */
9053   if (mangled != NULL)
9054     {
9055       char *demangled;
9056
9057       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9058          type.  It is easier for GDB users to search for such functions as
9059          `name(params)' than `long name(params)'.  In such case the minimal
9060          symbol names do not match the full symbol names but for template
9061          functions there is never a need to look up their definition from their
9062          declaration so the only disadvantage remains the minimal symbol
9063          variant `long name(params)' does not have the proper inferior type.
9064          */
9065
9066       if (cu->language == language_go)
9067         {
9068           /* This is a lie, but we already lie to the caller new_symbol_full.
9069              new_symbol_full assumes we return the mangled name.
9070              This just undoes that lie until things are cleaned up.  */
9071           demangled = NULL;
9072         }
9073       else
9074         {
9075           demangled = gdb_demangle (mangled,
9076                                     (DMGL_PARAMS | DMGL_ANSI | DMGL_RET_DROP));
9077         }
9078       if (demangled)
9079         {
9080           make_cleanup (xfree, demangled);
9081           canon = demangled;
9082         }
9083       else
9084         {
9085           canon = mangled;
9086           need_copy = 0;
9087         }
9088     }
9089
9090   if (canon == NULL || check_physname)
9091     {
9092       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9093
9094       if (canon != NULL && strcmp (physname, canon) != 0)
9095         {
9096           /* It may not mean a bug in GDB.  The compiler could also
9097              compute DW_AT_linkage_name incorrectly.  But in such case
9098              GDB would need to be bug-to-bug compatible.  */
9099
9100           complaint (&symfile_complaints,
9101                      _("Computed physname <%s> does not match demangled <%s> "
9102                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9103                      physname, canon, mangled, to_underlying (die->sect_off),
9104                      objfile_name (objfile));
9105
9106           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9107              is available here - over computed PHYSNAME.  It is safer
9108              against both buggy GDB and buggy compilers.  */
9109
9110           retval = canon;
9111         }
9112       else
9113         {
9114           retval = physname;
9115           need_copy = 0;
9116         }
9117     }
9118   else
9119     retval = canon;
9120
9121   if (need_copy)
9122     retval = ((const char *)
9123               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9124                              retval, strlen (retval)));
9125
9126   do_cleanups (back_to);
9127   return retval;
9128 }
9129
9130 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9131    a new symbol for it.
9132
9133    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9134
9135 static int
9136 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9137 {
9138   struct attribute *attr;
9139
9140   /* If the die does not have a name, this is not a namespace
9141      alias.  */
9142   attr = dwarf2_attr (die, DW_AT_name, cu);
9143   if (attr != NULL)
9144     {
9145       int num;
9146       struct die_info *d = die;
9147       struct dwarf2_cu *imported_cu = cu;
9148
9149       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9150          keep inspecting DIEs until we hit the underlying import.  */
9151 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9152       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9153         {
9154           attr = dwarf2_attr (d, DW_AT_import, cu);
9155           if (attr == NULL)
9156             break;
9157
9158           d = follow_die_ref (d, attr, &imported_cu);
9159           if (d->tag != DW_TAG_imported_declaration)
9160             break;
9161         }
9162
9163       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9164         {
9165           complaint (&symfile_complaints,
9166                      _("DIE at 0x%x has too many recursively imported "
9167                        "declarations"), to_underlying (d->sect_off));
9168           return 0;
9169         }
9170
9171       if (attr != NULL)
9172         {
9173           struct type *type;
9174           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9175
9176           type = get_die_type_at_offset (sect_off, cu->per_cu);
9177           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9178             {
9179               /* This declaration is a global namespace alias.  Add
9180                  a symbol for it whose type is the aliased namespace.  */
9181               new_symbol (die, type, cu);
9182               return 1;
9183             }
9184         }
9185     }
9186
9187   return 0;
9188 }
9189
9190 /* Return the using directives repository (global or local?) to use in the
9191    current context for LANGUAGE.
9192
9193    For Ada, imported declarations can materialize renamings, which *may* be
9194    global.  However it is impossible (for now?) in DWARF to distinguish
9195    "external" imported declarations and "static" ones.  As all imported
9196    declarations seem to be static in all other languages, make them all CU-wide
9197    global only in Ada.  */
9198
9199 static struct using_direct **
9200 using_directives (enum language language)
9201 {
9202   if (language == language_ada && context_stack_depth == 0)
9203     return &global_using_directives;
9204   else
9205     return &local_using_directives;
9206 }
9207
9208 /* Read the import statement specified by the given die and record it.  */
9209
9210 static void
9211 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9212 {
9213   struct objfile *objfile = cu->objfile;
9214   struct attribute *import_attr;
9215   struct die_info *imported_die, *child_die;
9216   struct dwarf2_cu *imported_cu;
9217   const char *imported_name;
9218   const char *imported_name_prefix;
9219   const char *canonical_name;
9220   const char *import_alias;
9221   const char *imported_declaration = NULL;
9222   const char *import_prefix;
9223   std::vector<const char *> excludes;
9224
9225   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9226   if (import_attr == NULL)
9227     {
9228       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9229                  dwarf_tag_name (die->tag));
9230       return;
9231     }
9232
9233   imported_cu = cu;
9234   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9235   imported_name = dwarf2_name (imported_die, imported_cu);
9236   if (imported_name == NULL)
9237     {
9238       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9239
9240         The import in the following code:
9241         namespace A
9242           {
9243             typedef int B;
9244           }
9245
9246         int main ()
9247           {
9248             using A::B;
9249             B b;
9250             return b;
9251           }
9252
9253         ...
9254          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9255             <52>   DW_AT_decl_file   : 1
9256             <53>   DW_AT_decl_line   : 6
9257             <54>   DW_AT_import      : <0x75>
9258          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9259             <59>   DW_AT_name        : B
9260             <5b>   DW_AT_decl_file   : 1
9261             <5c>   DW_AT_decl_line   : 2
9262             <5d>   DW_AT_type        : <0x6e>
9263         ...
9264          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9265             <76>   DW_AT_byte_size   : 4
9266             <77>   DW_AT_encoding    : 5        (signed)
9267
9268         imports the wrong die ( 0x75 instead of 0x58 ).
9269         This case will be ignored until the gcc bug is fixed.  */
9270       return;
9271     }
9272
9273   /* Figure out the local name after import.  */
9274   import_alias = dwarf2_name (die, cu);
9275
9276   /* Figure out where the statement is being imported to.  */
9277   import_prefix = determine_prefix (die, cu);
9278
9279   /* Figure out what the scope of the imported die is and prepend it
9280      to the name of the imported die.  */
9281   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9282
9283   if (imported_die->tag != DW_TAG_namespace
9284       && imported_die->tag != DW_TAG_module)
9285     {
9286       imported_declaration = imported_name;
9287       canonical_name = imported_name_prefix;
9288     }
9289   else if (strlen (imported_name_prefix) > 0)
9290     canonical_name = obconcat (&objfile->objfile_obstack,
9291                                imported_name_prefix,
9292                                (cu->language == language_d ? "." : "::"),
9293                                imported_name, (char *) NULL);
9294   else
9295     canonical_name = imported_name;
9296
9297   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9298     for (child_die = die->child; child_die && child_die->tag;
9299          child_die = sibling_die (child_die))
9300       {
9301         /* DWARF-4: A Fortran use statement with a “rename list” may be
9302            represented by an imported module entry with an import attribute
9303            referring to the module and owned entries corresponding to those
9304            entities that are renamed as part of being imported.  */
9305
9306         if (child_die->tag != DW_TAG_imported_declaration)
9307           {
9308             complaint (&symfile_complaints,
9309                        _("child DW_TAG_imported_declaration expected "
9310                          "- DIE at 0x%x [in module %s]"),
9311                        to_underlying (child_die->sect_off), objfile_name (objfile));
9312             continue;
9313           }
9314
9315         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9316         if (import_attr == NULL)
9317           {
9318             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9319                        dwarf_tag_name (child_die->tag));
9320             continue;
9321           }
9322
9323         imported_cu = cu;
9324         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9325                                               &imported_cu);
9326         imported_name = dwarf2_name (imported_die, imported_cu);
9327         if (imported_name == NULL)
9328           {
9329             complaint (&symfile_complaints,
9330                        _("child DW_TAG_imported_declaration has unknown "
9331                          "imported name - DIE at 0x%x [in module %s]"),
9332                        to_underlying (child_die->sect_off), objfile_name (objfile));
9333             continue;
9334           }
9335
9336         excludes.push_back (imported_name);
9337
9338         process_die (child_die, cu);
9339       }
9340
9341   add_using_directive (using_directives (cu->language),
9342                        import_prefix,
9343                        canonical_name,
9344                        import_alias,
9345                        imported_declaration,
9346                        excludes,
9347                        0,
9348                        &objfile->objfile_obstack);
9349 }
9350
9351 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9352    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9353    this, it was first present in GCC release 4.3.0.  */
9354
9355 static int
9356 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9357 {
9358   if (!cu->checked_producer)
9359     check_producer (cu);
9360
9361   return cu->producer_is_gcc_lt_4_3;
9362 }
9363
9364 static file_and_directory
9365 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9366 {
9367   file_and_directory res;
9368
9369   /* Find the filename.  Do not use dwarf2_name here, since the filename
9370      is not a source language identifier.  */
9371   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9372   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9373
9374   if (res.comp_dir == NULL
9375       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9376       && IS_ABSOLUTE_PATH (res.name))
9377     {
9378       res.comp_dir_storage = ldirname (res.name);
9379       if (!res.comp_dir_storage.empty ())
9380         res.comp_dir = res.comp_dir_storage.c_str ();
9381     }
9382   if (res.comp_dir != NULL)
9383     {
9384       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9385          directory, get rid of it.  */
9386       const char *cp = strchr (res.comp_dir, ':');
9387
9388       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9389         res.comp_dir = cp + 1;
9390     }
9391
9392   if (res.name == NULL)
9393     res.name = "<unknown>";
9394
9395   return res;
9396 }
9397
9398 /* Handle DW_AT_stmt_list for a compilation unit.
9399    DIE is the DW_TAG_compile_unit die for CU.
9400    COMP_DIR is the compilation directory.  LOWPC is passed to
9401    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9402
9403 static void
9404 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9405                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9406 {
9407   struct objfile *objfile = dwarf2_per_objfile->objfile;
9408   struct attribute *attr;
9409   struct line_header line_header_local;
9410   hashval_t line_header_local_hash;
9411   unsigned u;
9412   void **slot;
9413   int decode_mapping;
9414
9415   gdb_assert (! cu->per_cu->is_debug_types);
9416
9417   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9418   if (attr == NULL)
9419     return;
9420
9421   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9422
9423   /* The line header hash table is only created if needed (it exists to
9424      prevent redundant reading of the line table for partial_units).
9425      If we're given a partial_unit, we'll need it.  If we're given a
9426      compile_unit, then use the line header hash table if it's already
9427      created, but don't create one just yet.  */
9428
9429   if (dwarf2_per_objfile->line_header_hash == NULL
9430       && die->tag == DW_TAG_partial_unit)
9431     {
9432       dwarf2_per_objfile->line_header_hash
9433         = htab_create_alloc_ex (127, line_header_hash_voidp,
9434                                 line_header_eq_voidp,
9435                                 free_line_header_voidp,
9436                                 &objfile->objfile_obstack,
9437                                 hashtab_obstack_allocate,
9438                                 dummy_obstack_deallocate);
9439     }
9440
9441   line_header_local.sect_off = line_offset;
9442   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9443   line_header_local_hash = line_header_hash (&line_header_local);
9444   if (dwarf2_per_objfile->line_header_hash != NULL)
9445     {
9446       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9447                                        &line_header_local,
9448                                        line_header_local_hash, NO_INSERT);
9449
9450       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9451          is not present in *SLOT (since if there is something in *SLOT then
9452          it will be for a partial_unit).  */
9453       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9454         {
9455           gdb_assert (*slot != NULL);
9456           cu->line_header = (struct line_header *) *slot;
9457           return;
9458         }
9459     }
9460
9461   /* dwarf_decode_line_header does not yet provide sufficient information.
9462      We always have to call also dwarf_decode_lines for it.  */
9463   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9464   if (lh == NULL)
9465     return;
9466
9467   cu->line_header = lh.release ();
9468   cu->line_header_die_owner = die;
9469
9470   if (dwarf2_per_objfile->line_header_hash == NULL)
9471     slot = NULL;
9472   else
9473     {
9474       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9475                                        &line_header_local,
9476                                        line_header_local_hash, INSERT);
9477       gdb_assert (slot != NULL);
9478     }
9479   if (slot != NULL && *slot == NULL)
9480     {
9481       /* This newly decoded line number information unit will be owned
9482          by line_header_hash hash table.  */
9483       *slot = cu->line_header;
9484       cu->line_header_die_owner = NULL;
9485     }
9486   else
9487     {
9488       /* We cannot free any current entry in (*slot) as that struct line_header
9489          may be already used by multiple CUs.  Create only temporary decoded
9490          line_header for this CU - it may happen at most once for each line
9491          number information unit.  And if we're not using line_header_hash
9492          then this is what we want as well.  */
9493       gdb_assert (die->tag != DW_TAG_partial_unit);
9494     }
9495   decode_mapping = (die->tag != DW_TAG_partial_unit);
9496   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9497                       decode_mapping);
9498
9499 }
9500
9501 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9502
9503 static void
9504 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9505 {
9506   struct objfile *objfile = dwarf2_per_objfile->objfile;
9507   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9508   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9509   CORE_ADDR highpc = ((CORE_ADDR) 0);
9510   struct attribute *attr;
9511   struct die_info *child_die;
9512   CORE_ADDR baseaddr;
9513
9514   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9515
9516   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9517
9518   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9519      from finish_block.  */
9520   if (lowpc == ((CORE_ADDR) -1))
9521     lowpc = highpc;
9522   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9523
9524   file_and_directory fnd = find_file_and_directory (die, cu);
9525
9526   prepare_one_comp_unit (cu, die, cu->language);
9527
9528   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9529      standardised yet.  As a workaround for the language detection we fall
9530      back to the DW_AT_producer string.  */
9531   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9532     cu->language = language_opencl;
9533
9534   /* Similar hack for Go.  */
9535   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9536     set_cu_language (DW_LANG_Go, cu);
9537
9538   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9539
9540   /* Decode line number information if present.  We do this before
9541      processing child DIEs, so that the line header table is available
9542      for DW_AT_decl_file.  */
9543   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9544
9545   /* Process all dies in compilation unit.  */
9546   if (die->child != NULL)
9547     {
9548       child_die = die->child;
9549       while (child_die && child_die->tag)
9550         {
9551           process_die (child_die, cu);
9552           child_die = sibling_die (child_die);
9553         }
9554     }
9555
9556   /* Decode macro information, if present.  Dwarf 2 macro information
9557      refers to information in the line number info statement program
9558      header, so we can only read it if we've read the header
9559      successfully.  */
9560   attr = dwarf2_attr (die, DW_AT_macros, cu);
9561   if (attr == NULL)
9562     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9563   if (attr && cu->line_header)
9564     {
9565       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9566         complaint (&symfile_complaints,
9567                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9568
9569       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9570     }
9571   else
9572     {
9573       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9574       if (attr && cu->line_header)
9575         {
9576           unsigned int macro_offset = DW_UNSND (attr);
9577
9578           dwarf_decode_macros (cu, macro_offset, 0);
9579         }
9580     }
9581 }
9582
9583 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9584    Create the set of symtabs used by this TU, or if this TU is sharing
9585    symtabs with another TU and the symtabs have already been created
9586    then restore those symtabs in the line header.
9587    We don't need the pc/line-number mapping for type units.  */
9588
9589 static void
9590 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9591 {
9592   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9593   struct type_unit_group *tu_group;
9594   int first_time;
9595   struct attribute *attr;
9596   unsigned int i;
9597   struct signatured_type *sig_type;
9598
9599   gdb_assert (per_cu->is_debug_types);
9600   sig_type = (struct signatured_type *) per_cu;
9601
9602   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9603
9604   /* If we're using .gdb_index (includes -readnow) then
9605      per_cu->type_unit_group may not have been set up yet.  */
9606   if (sig_type->type_unit_group == NULL)
9607     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9608   tu_group = sig_type->type_unit_group;
9609
9610   /* If we've already processed this stmt_list there's no real need to
9611      do it again, we could fake it and just recreate the part we need
9612      (file name,index -> symtab mapping).  If data shows this optimization
9613      is useful we can do it then.  */
9614   first_time = tu_group->compunit_symtab == NULL;
9615
9616   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9617      debug info.  */
9618   line_header_up lh;
9619   if (attr != NULL)
9620     {
9621       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9622       lh = dwarf_decode_line_header (line_offset, cu);
9623     }
9624   if (lh == NULL)
9625     {
9626       if (first_time)
9627         dwarf2_start_symtab (cu, "", NULL, 0);
9628       else
9629         {
9630           gdb_assert (tu_group->symtabs == NULL);
9631           restart_symtab (tu_group->compunit_symtab, "", 0);
9632         }
9633       return;
9634     }
9635
9636   cu->line_header = lh.release ();
9637   cu->line_header_die_owner = die;
9638
9639   if (first_time)
9640     {
9641       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9642
9643       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9644          still initializing it, and our caller (a few levels up)
9645          process_full_type_unit still needs to know if this is the first
9646          time.  */
9647
9648       tu_group->num_symtabs = cu->line_header->file_names.size ();
9649       tu_group->symtabs = XNEWVEC (struct symtab *,
9650                                    cu->line_header->file_names.size ());
9651
9652       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9653         {
9654           file_entry &fe = cu->line_header->file_names[i];
9655
9656           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9657
9658           if (current_subfile->symtab == NULL)
9659             {
9660               /* NOTE: start_subfile will recognize when it's been
9661                  passed a file it has already seen.  So we can't
9662                  assume there's a simple mapping from
9663                  cu->line_header->file_names to subfiles, plus
9664                  cu->line_header->file_names may contain dups.  */
9665               current_subfile->symtab
9666                 = allocate_symtab (cust, current_subfile->name);
9667             }
9668
9669           fe.symtab = current_subfile->symtab;
9670           tu_group->symtabs[i] = fe.symtab;
9671         }
9672     }
9673   else
9674     {
9675       restart_symtab (tu_group->compunit_symtab, "", 0);
9676
9677       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9678         {
9679           file_entry &fe = cu->line_header->file_names[i];
9680
9681           fe.symtab = tu_group->symtabs[i];
9682         }
9683     }
9684
9685   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9686      so they don't have a "real" (so to speak) symtab anyway.
9687      There is later code that will assign the main symtab to all symbols
9688      that don't have one.  We need to handle the case of a symbol with a
9689      missing symtab (DW_AT_decl_file) anyway.  */
9690 }
9691
9692 /* Process DW_TAG_type_unit.
9693    For TUs we want to skip the first top level sibling if it's not the
9694    actual type being defined by this TU.  In this case the first top
9695    level sibling is there to provide context only.  */
9696
9697 static void
9698 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9699 {
9700   struct die_info *child_die;
9701
9702   prepare_one_comp_unit (cu, die, language_minimal);
9703
9704   /* Initialize (or reinitialize) the machinery for building symtabs.
9705      We do this before processing child DIEs, so that the line header table
9706      is available for DW_AT_decl_file.  */
9707   setup_type_unit_groups (die, cu);
9708
9709   if (die->child != NULL)
9710     {
9711       child_die = die->child;
9712       while (child_die && child_die->tag)
9713         {
9714           process_die (child_die, cu);
9715           child_die = sibling_die (child_die);
9716         }
9717     }
9718 }
9719 \f
9720 /* DWO/DWP files.
9721
9722    http://gcc.gnu.org/wiki/DebugFission
9723    http://gcc.gnu.org/wiki/DebugFissionDWP
9724
9725    To simplify handling of both DWO files ("object" files with the DWARF info)
9726    and DWP files (a file with the DWOs packaged up into one file), we treat
9727    DWP files as having a collection of virtual DWO files.  */
9728
9729 static hashval_t
9730 hash_dwo_file (const void *item)
9731 {
9732   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9733   hashval_t hash;
9734
9735   hash = htab_hash_string (dwo_file->dwo_name);
9736   if (dwo_file->comp_dir != NULL)
9737     hash += htab_hash_string (dwo_file->comp_dir);
9738   return hash;
9739 }
9740
9741 static int
9742 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9743 {
9744   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9745   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9746
9747   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9748     return 0;
9749   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9750     return lhs->comp_dir == rhs->comp_dir;
9751   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9752 }
9753
9754 /* Allocate a hash table for DWO files.  */
9755
9756 static htab_t
9757 allocate_dwo_file_hash_table (void)
9758 {
9759   struct objfile *objfile = dwarf2_per_objfile->objfile;
9760
9761   return htab_create_alloc_ex (41,
9762                                hash_dwo_file,
9763                                eq_dwo_file,
9764                                NULL,
9765                                &objfile->objfile_obstack,
9766                                hashtab_obstack_allocate,
9767                                dummy_obstack_deallocate);
9768 }
9769
9770 /* Lookup DWO file DWO_NAME.  */
9771
9772 static void **
9773 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9774 {
9775   struct dwo_file find_entry;
9776   void **slot;
9777
9778   if (dwarf2_per_objfile->dwo_files == NULL)
9779     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9780
9781   memset (&find_entry, 0, sizeof (find_entry));
9782   find_entry.dwo_name = dwo_name;
9783   find_entry.comp_dir = comp_dir;
9784   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9785
9786   return slot;
9787 }
9788
9789 static hashval_t
9790 hash_dwo_unit (const void *item)
9791 {
9792   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9793
9794   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9795   return dwo_unit->signature;
9796 }
9797
9798 static int
9799 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9800 {
9801   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9802   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9803
9804   /* The signature is assumed to be unique within the DWO file.
9805      So while object file CU dwo_id's always have the value zero,
9806      that's OK, assuming each object file DWO file has only one CU,
9807      and that's the rule for now.  */
9808   return lhs->signature == rhs->signature;
9809 }
9810
9811 /* Allocate a hash table for DWO CUs,TUs.
9812    There is one of these tables for each of CUs,TUs for each DWO file.  */
9813
9814 static htab_t
9815 allocate_dwo_unit_table (struct objfile *objfile)
9816 {
9817   /* Start out with a pretty small number.
9818      Generally DWO files contain only one CU and maybe some TUs.  */
9819   return htab_create_alloc_ex (3,
9820                                hash_dwo_unit,
9821                                eq_dwo_unit,
9822                                NULL,
9823                                &objfile->objfile_obstack,
9824                                hashtab_obstack_allocate,
9825                                dummy_obstack_deallocate);
9826 }
9827
9828 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9829
9830 struct create_dwo_cu_data
9831 {
9832   struct dwo_file *dwo_file;
9833   struct dwo_unit dwo_unit;
9834 };
9835
9836 /* die_reader_func for create_dwo_cu.  */
9837
9838 static void
9839 create_dwo_cu_reader (const struct die_reader_specs *reader,
9840                       const gdb_byte *info_ptr,
9841                       struct die_info *comp_unit_die,
9842                       int has_children,
9843                       void *datap)
9844 {
9845   struct dwarf2_cu *cu = reader->cu;
9846   sect_offset sect_off = cu->per_cu->sect_off;
9847   struct dwarf2_section_info *section = cu->per_cu->section;
9848   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9849   struct dwo_file *dwo_file = data->dwo_file;
9850   struct dwo_unit *dwo_unit = &data->dwo_unit;
9851   struct attribute *attr;
9852
9853   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9854   if (attr == NULL)
9855     {
9856       complaint (&symfile_complaints,
9857                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9858                    " its dwo_id [in module %s]"),
9859                  to_underlying (sect_off), dwo_file->dwo_name);
9860       return;
9861     }
9862
9863   dwo_unit->dwo_file = dwo_file;
9864   dwo_unit->signature = DW_UNSND (attr);
9865   dwo_unit->section = section;
9866   dwo_unit->sect_off = sect_off;
9867   dwo_unit->length = cu->per_cu->length;
9868
9869   if (dwarf_read_debug)
9870     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9871                         to_underlying (sect_off),
9872                         hex_string (dwo_unit->signature));
9873 }
9874
9875 /* Create the dwo_units for the CUs in a DWO_FILE.
9876    Note: This function processes DWO files only, not DWP files.  */
9877
9878 static void
9879 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9880                        htab_t &cus_htab)
9881 {
9882   struct objfile *objfile = dwarf2_per_objfile->objfile;
9883   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9884   const gdb_byte *info_ptr, *end_ptr;
9885
9886   dwarf2_read_section (objfile, &section);
9887   info_ptr = section.buffer;
9888
9889   if (info_ptr == NULL)
9890     return;
9891
9892   if (dwarf_read_debug)
9893     {
9894       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9895                           get_section_name (&section),
9896                           get_section_file_name (&section));
9897     }
9898
9899   end_ptr = info_ptr + section.size;
9900   while (info_ptr < end_ptr)
9901     {
9902       struct dwarf2_per_cu_data per_cu;
9903       struct create_dwo_cu_data create_dwo_cu_data;
9904       struct dwo_unit *dwo_unit;
9905       void **slot;
9906       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9907
9908       memset (&create_dwo_cu_data.dwo_unit, 0,
9909               sizeof (create_dwo_cu_data.dwo_unit));
9910       memset (&per_cu, 0, sizeof (per_cu));
9911       per_cu.objfile = objfile;
9912       per_cu.is_debug_types = 0;
9913       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9914       per_cu.section = &section;
9915       create_dwo_cu_data.dwo_file = &dwo_file;
9916
9917       init_cutu_and_read_dies_no_follow (
9918           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9919       info_ptr += per_cu.length;
9920
9921       // If the unit could not be parsed, skip it.
9922       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9923         continue;
9924
9925       if (cus_htab == NULL)
9926         cus_htab = allocate_dwo_unit_table (objfile);
9927
9928       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9929       *dwo_unit = create_dwo_cu_data.dwo_unit;
9930       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9931       gdb_assert (slot != NULL);
9932       if (*slot != NULL)
9933         {
9934           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9935           sect_offset dup_sect_off = dup_cu->sect_off;
9936
9937           complaint (&symfile_complaints,
9938                      _("debug cu entry at offset 0x%x is duplicate to"
9939                        " the entry at offset 0x%x, signature %s"),
9940                      to_underlying (sect_off), to_underlying (dup_sect_off),
9941                      hex_string (dwo_unit->signature));
9942         }
9943       *slot = (void *)dwo_unit;
9944     }
9945 }
9946
9947 /* DWP file .debug_{cu,tu}_index section format:
9948    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9949
9950    DWP Version 1:
9951
9952    Both index sections have the same format, and serve to map a 64-bit
9953    signature to a set of section numbers.  Each section begins with a header,
9954    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9955    indexes, and a pool of 32-bit section numbers.  The index sections will be
9956    aligned at 8-byte boundaries in the file.
9957
9958    The index section header consists of:
9959
9960     V, 32 bit version number
9961     -, 32 bits unused
9962     N, 32 bit number of compilation units or type units in the index
9963     M, 32 bit number of slots in the hash table
9964
9965    Numbers are recorded using the byte order of the application binary.
9966
9967    The hash table begins at offset 16 in the section, and consists of an array
9968    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9969    order of the application binary).  Unused slots in the hash table are 0.
9970    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9971
9972    The parallel table begins immediately after the hash table
9973    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9974    array of 32-bit indexes (using the byte order of the application binary),
9975    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9976    table contains a 32-bit index into the pool of section numbers.  For unused
9977    hash table slots, the corresponding entry in the parallel table will be 0.
9978
9979    The pool of section numbers begins immediately following the hash table
9980    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9981    section numbers consists of an array of 32-bit words (using the byte order
9982    of the application binary).  Each item in the array is indexed starting
9983    from 0.  The hash table entry provides the index of the first section
9984    number in the set.  Additional section numbers in the set follow, and the
9985    set is terminated by a 0 entry (section number 0 is not used in ELF).
9986
9987    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9988    section must be the first entry in the set, and the .debug_abbrev.dwo must
9989    be the second entry. Other members of the set may follow in any order.
9990
9991    ---
9992
9993    DWP Version 2:
9994
9995    DWP Version 2 combines all the .debug_info, etc. sections into one,
9996    and the entries in the index tables are now offsets into these sections.
9997    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9998    section.
9999
10000    Index Section Contents:
10001     Header
10002     Hash Table of Signatures   dwp_hash_table.hash_table
10003     Parallel Table of Indices  dwp_hash_table.unit_table
10004     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10005     Table of Section Sizes     dwp_hash_table.v2.sizes
10006
10007    The index section header consists of:
10008
10009     V, 32 bit version number
10010     L, 32 bit number of columns in the table of section offsets
10011     N, 32 bit number of compilation units or type units in the index
10012     M, 32 bit number of slots in the hash table
10013
10014    Numbers are recorded using the byte order of the application binary.
10015
10016    The hash table has the same format as version 1.
10017    The parallel table of indices has the same format as version 1,
10018    except that the entries are origin-1 indices into the table of sections
10019    offsets and the table of section sizes.
10020
10021    The table of offsets begins immediately following the parallel table
10022    (at offset 16 + 12 * M from the beginning of the section).  The table is
10023    a two-dimensional array of 32-bit words (using the byte order of the
10024    application binary), with L columns and N+1 rows, in row-major order.
10025    Each row in the array is indexed starting from 0.  The first row provides
10026    a key to the remaining rows: each column in this row provides an identifier
10027    for a debug section, and the offsets in the same column of subsequent rows
10028    refer to that section.  The section identifiers are:
10029
10030     DW_SECT_INFO         1  .debug_info.dwo
10031     DW_SECT_TYPES        2  .debug_types.dwo
10032     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10033     DW_SECT_LINE         4  .debug_line.dwo
10034     DW_SECT_LOC          5  .debug_loc.dwo
10035     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10036     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10037     DW_SECT_MACRO        8  .debug_macro.dwo
10038
10039    The offsets provided by the CU and TU index sections are the base offsets
10040    for the contributions made by each CU or TU to the corresponding section
10041    in the package file.  Each CU and TU header contains an abbrev_offset
10042    field, used to find the abbreviations table for that CU or TU within the
10043    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10044    be interpreted as relative to the base offset given in the index section.
10045    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10046    should be interpreted as relative to the base offset for .debug_line.dwo,
10047    and offsets into other debug sections obtained from DWARF attributes should
10048    also be interpreted as relative to the corresponding base offset.
10049
10050    The table of sizes begins immediately following the table of offsets.
10051    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10052    with L columns and N rows, in row-major order.  Each row in the array is
10053    indexed starting from 1 (row 0 is shared by the two tables).
10054
10055    ---
10056
10057    Hash table lookup is handled the same in version 1 and 2:
10058
10059    We assume that N and M will not exceed 2^32 - 1.
10060    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10061
10062    Given a 64-bit compilation unit signature or a type signature S, an entry
10063    in the hash table is located as follows:
10064
10065    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10066       the low-order k bits all set to 1.
10067
10068    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10069
10070    3) If the hash table entry at index H matches the signature, use that
10071       entry.  If the hash table entry at index H is unused (all zeroes),
10072       terminate the search: the signature is not present in the table.
10073
10074    4) Let H = (H + H') modulo M. Repeat at Step 3.
10075
10076    Because M > N and H' and M are relatively prime, the search is guaranteed
10077    to stop at an unused slot or find the match.  */
10078
10079 /* Create a hash table to map DWO IDs to their CU/TU entry in
10080    .debug_{info,types}.dwo in DWP_FILE.
10081    Returns NULL if there isn't one.
10082    Note: This function processes DWP files only, not DWO files.  */
10083
10084 static struct dwp_hash_table *
10085 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10086 {
10087   struct objfile *objfile = dwarf2_per_objfile->objfile;
10088   bfd *dbfd = dwp_file->dbfd;
10089   const gdb_byte *index_ptr, *index_end;
10090   struct dwarf2_section_info *index;
10091   uint32_t version, nr_columns, nr_units, nr_slots;
10092   struct dwp_hash_table *htab;
10093
10094   if (is_debug_types)
10095     index = &dwp_file->sections.tu_index;
10096   else
10097     index = &dwp_file->sections.cu_index;
10098
10099   if (dwarf2_section_empty_p (index))
10100     return NULL;
10101   dwarf2_read_section (objfile, index);
10102
10103   index_ptr = index->buffer;
10104   index_end = index_ptr + index->size;
10105
10106   version = read_4_bytes (dbfd, index_ptr);
10107   index_ptr += 4;
10108   if (version == 2)
10109     nr_columns = read_4_bytes (dbfd, index_ptr);
10110   else
10111     nr_columns = 0;
10112   index_ptr += 4;
10113   nr_units = read_4_bytes (dbfd, index_ptr);
10114   index_ptr += 4;
10115   nr_slots = read_4_bytes (dbfd, index_ptr);
10116   index_ptr += 4;
10117
10118   if (version != 1 && version != 2)
10119     {
10120       error (_("Dwarf Error: unsupported DWP file version (%s)"
10121                " [in module %s]"),
10122              pulongest (version), dwp_file->name);
10123     }
10124   if (nr_slots != (nr_slots & -nr_slots))
10125     {
10126       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10127                " is not power of 2 [in module %s]"),
10128              pulongest (nr_slots), dwp_file->name);
10129     }
10130
10131   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10132   htab->version = version;
10133   htab->nr_columns = nr_columns;
10134   htab->nr_units = nr_units;
10135   htab->nr_slots = nr_slots;
10136   htab->hash_table = index_ptr;
10137   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10138
10139   /* Exit early if the table is empty.  */
10140   if (nr_slots == 0 || nr_units == 0
10141       || (version == 2 && nr_columns == 0))
10142     {
10143       /* All must be zero.  */
10144       if (nr_slots != 0 || nr_units != 0
10145           || (version == 2 && nr_columns != 0))
10146         {
10147           complaint (&symfile_complaints,
10148                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10149                        " all zero [in modules %s]"),
10150                      dwp_file->name);
10151         }
10152       return htab;
10153     }
10154
10155   if (version == 1)
10156     {
10157       htab->section_pool.v1.indices =
10158         htab->unit_table + sizeof (uint32_t) * nr_slots;
10159       /* It's harder to decide whether the section is too small in v1.
10160          V1 is deprecated anyway so we punt.  */
10161     }
10162   else
10163     {
10164       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10165       int *ids = htab->section_pool.v2.section_ids;
10166       /* Reverse map for error checking.  */
10167       int ids_seen[DW_SECT_MAX + 1];
10168       int i;
10169
10170       if (nr_columns < 2)
10171         {
10172           error (_("Dwarf Error: bad DWP hash table, too few columns"
10173                    " in section table [in module %s]"),
10174                  dwp_file->name);
10175         }
10176       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10177         {
10178           error (_("Dwarf Error: bad DWP hash table, too many columns"
10179                    " in section table [in module %s]"),
10180                  dwp_file->name);
10181         }
10182       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10183       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10184       for (i = 0; i < nr_columns; ++i)
10185         {
10186           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10187
10188           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10189             {
10190               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10191                        " in section table [in module %s]"),
10192                      id, dwp_file->name);
10193             }
10194           if (ids_seen[id] != -1)
10195             {
10196               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10197                        " id %d in section table [in module %s]"),
10198                      id, dwp_file->name);
10199             }
10200           ids_seen[id] = i;
10201           ids[i] = id;
10202         }
10203       /* Must have exactly one info or types section.  */
10204       if (((ids_seen[DW_SECT_INFO] != -1)
10205            + (ids_seen[DW_SECT_TYPES] != -1))
10206           != 1)
10207         {
10208           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10209                    " DWO info/types section [in module %s]"),
10210                  dwp_file->name);
10211         }
10212       /* Must have an abbrev section.  */
10213       if (ids_seen[DW_SECT_ABBREV] == -1)
10214         {
10215           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10216                    " section [in module %s]"),
10217                  dwp_file->name);
10218         }
10219       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10220       htab->section_pool.v2.sizes =
10221         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10222                                          * nr_units * nr_columns);
10223       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10224                                           * nr_units * nr_columns))
10225           > index_end)
10226         {
10227           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10228                    " [in module %s]"),
10229                  dwp_file->name);
10230         }
10231     }
10232
10233   return htab;
10234 }
10235
10236 /* Update SECTIONS with the data from SECTP.
10237
10238    This function is like the other "locate" section routines that are
10239    passed to bfd_map_over_sections, but in this context the sections to
10240    read comes from the DWP V1 hash table, not the full ELF section table.
10241
10242    The result is non-zero for success, or zero if an error was found.  */
10243
10244 static int
10245 locate_v1_virtual_dwo_sections (asection *sectp,
10246                                 struct virtual_v1_dwo_sections *sections)
10247 {
10248   const struct dwop_section_names *names = &dwop_section_names;
10249
10250   if (section_is_p (sectp->name, &names->abbrev_dwo))
10251     {
10252       /* There can be only one.  */
10253       if (sections->abbrev.s.section != NULL)
10254         return 0;
10255       sections->abbrev.s.section = sectp;
10256       sections->abbrev.size = bfd_get_section_size (sectp);
10257     }
10258   else if (section_is_p (sectp->name, &names->info_dwo)
10259            || section_is_p (sectp->name, &names->types_dwo))
10260     {
10261       /* There can be only one.  */
10262       if (sections->info_or_types.s.section != NULL)
10263         return 0;
10264       sections->info_or_types.s.section = sectp;
10265       sections->info_or_types.size = bfd_get_section_size (sectp);
10266     }
10267   else if (section_is_p (sectp->name, &names->line_dwo))
10268     {
10269       /* There can be only one.  */
10270       if (sections->line.s.section != NULL)
10271         return 0;
10272       sections->line.s.section = sectp;
10273       sections->line.size = bfd_get_section_size (sectp);
10274     }
10275   else if (section_is_p (sectp->name, &names->loc_dwo))
10276     {
10277       /* There can be only one.  */
10278       if (sections->loc.s.section != NULL)
10279         return 0;
10280       sections->loc.s.section = sectp;
10281       sections->loc.size = bfd_get_section_size (sectp);
10282     }
10283   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10284     {
10285       /* There can be only one.  */
10286       if (sections->macinfo.s.section != NULL)
10287         return 0;
10288       sections->macinfo.s.section = sectp;
10289       sections->macinfo.size = bfd_get_section_size (sectp);
10290     }
10291   else if (section_is_p (sectp->name, &names->macro_dwo))
10292     {
10293       /* There can be only one.  */
10294       if (sections->macro.s.section != NULL)
10295         return 0;
10296       sections->macro.s.section = sectp;
10297       sections->macro.size = bfd_get_section_size (sectp);
10298     }
10299   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10300     {
10301       /* There can be only one.  */
10302       if (sections->str_offsets.s.section != NULL)
10303         return 0;
10304       sections->str_offsets.s.section = sectp;
10305       sections->str_offsets.size = bfd_get_section_size (sectp);
10306     }
10307   else
10308     {
10309       /* No other kind of section is valid.  */
10310       return 0;
10311     }
10312
10313   return 1;
10314 }
10315
10316 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10317    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10318    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10319    This is for DWP version 1 files.  */
10320
10321 static struct dwo_unit *
10322 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10323                            uint32_t unit_index,
10324                            const char *comp_dir,
10325                            ULONGEST signature, int is_debug_types)
10326 {
10327   struct objfile *objfile = dwarf2_per_objfile->objfile;
10328   const struct dwp_hash_table *dwp_htab =
10329     is_debug_types ? dwp_file->tus : dwp_file->cus;
10330   bfd *dbfd = dwp_file->dbfd;
10331   const char *kind = is_debug_types ? "TU" : "CU";
10332   struct dwo_file *dwo_file;
10333   struct dwo_unit *dwo_unit;
10334   struct virtual_v1_dwo_sections sections;
10335   void **dwo_file_slot;
10336   char *virtual_dwo_name;
10337   struct cleanup *cleanups;
10338   int i;
10339
10340   gdb_assert (dwp_file->version == 1);
10341
10342   if (dwarf_read_debug)
10343     {
10344       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10345                           kind,
10346                           pulongest (unit_index), hex_string (signature),
10347                           dwp_file->name);
10348     }
10349
10350   /* Fetch the sections of this DWO unit.
10351      Put a limit on the number of sections we look for so that bad data
10352      doesn't cause us to loop forever.  */
10353
10354 #define MAX_NR_V1_DWO_SECTIONS \
10355   (1 /* .debug_info or .debug_types */ \
10356    + 1 /* .debug_abbrev */ \
10357    + 1 /* .debug_line */ \
10358    + 1 /* .debug_loc */ \
10359    + 1 /* .debug_str_offsets */ \
10360    + 1 /* .debug_macro or .debug_macinfo */ \
10361    + 1 /* trailing zero */)
10362
10363   memset (&sections, 0, sizeof (sections));
10364   cleanups = make_cleanup (null_cleanup, 0);
10365
10366   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10367     {
10368       asection *sectp;
10369       uint32_t section_nr =
10370         read_4_bytes (dbfd,
10371                       dwp_htab->section_pool.v1.indices
10372                       + (unit_index + i) * sizeof (uint32_t));
10373
10374       if (section_nr == 0)
10375         break;
10376       if (section_nr >= dwp_file->num_sections)
10377         {
10378           error (_("Dwarf Error: bad DWP hash table, section number too large"
10379                    " [in module %s]"),
10380                  dwp_file->name);
10381         }
10382
10383       sectp = dwp_file->elf_sections[section_nr];
10384       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10385         {
10386           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10387                    " [in module %s]"),
10388                  dwp_file->name);
10389         }
10390     }
10391
10392   if (i < 2
10393       || dwarf2_section_empty_p (&sections.info_or_types)
10394       || dwarf2_section_empty_p (&sections.abbrev))
10395     {
10396       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10397                " [in module %s]"),
10398              dwp_file->name);
10399     }
10400   if (i == MAX_NR_V1_DWO_SECTIONS)
10401     {
10402       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10403                " [in module %s]"),
10404              dwp_file->name);
10405     }
10406
10407   /* It's easier for the rest of the code if we fake a struct dwo_file and
10408      have dwo_unit "live" in that.  At least for now.
10409
10410      The DWP file can be made up of a random collection of CUs and TUs.
10411      However, for each CU + set of TUs that came from the same original DWO
10412      file, we can combine them back into a virtual DWO file to save space
10413      (fewer struct dwo_file objects to allocate).  Remember that for really
10414      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10415
10416   virtual_dwo_name =
10417     xstrprintf ("virtual-dwo/%d-%d-%d-%d",
10418                 get_section_id (&sections.abbrev),
10419                 get_section_id (&sections.line),
10420                 get_section_id (&sections.loc),
10421                 get_section_id (&sections.str_offsets));
10422   make_cleanup (xfree, virtual_dwo_name);
10423   /* Can we use an existing virtual DWO file?  */
10424   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10425   /* Create one if necessary.  */
10426   if (*dwo_file_slot == NULL)
10427     {
10428       if (dwarf_read_debug)
10429         {
10430           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10431                               virtual_dwo_name);
10432         }
10433       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10434       dwo_file->dwo_name
10435         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10436                                         virtual_dwo_name,
10437                                         strlen (virtual_dwo_name));
10438       dwo_file->comp_dir = comp_dir;
10439       dwo_file->sections.abbrev = sections.abbrev;
10440       dwo_file->sections.line = sections.line;
10441       dwo_file->sections.loc = sections.loc;
10442       dwo_file->sections.macinfo = sections.macinfo;
10443       dwo_file->sections.macro = sections.macro;
10444       dwo_file->sections.str_offsets = sections.str_offsets;
10445       /* The "str" section is global to the entire DWP file.  */
10446       dwo_file->sections.str = dwp_file->sections.str;
10447       /* The info or types section is assigned below to dwo_unit,
10448          there's no need to record it in dwo_file.
10449          Also, we can't simply record type sections in dwo_file because
10450          we record a pointer into the vector in dwo_unit.  As we collect more
10451          types we'll grow the vector and eventually have to reallocate space
10452          for it, invalidating all copies of pointers into the previous
10453          contents.  */
10454       *dwo_file_slot = dwo_file;
10455     }
10456   else
10457     {
10458       if (dwarf_read_debug)
10459         {
10460           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10461                               virtual_dwo_name);
10462         }
10463       dwo_file = (struct dwo_file *) *dwo_file_slot;
10464     }
10465   do_cleanups (cleanups);
10466
10467   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10468   dwo_unit->dwo_file = dwo_file;
10469   dwo_unit->signature = signature;
10470   dwo_unit->section =
10471     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10472   *dwo_unit->section = sections.info_or_types;
10473   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10474
10475   return dwo_unit;
10476 }
10477
10478 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10479    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10480    piece within that section used by a TU/CU, return a virtual section
10481    of just that piece.  */
10482
10483 static struct dwarf2_section_info
10484 create_dwp_v2_section (struct dwarf2_section_info *section,
10485                        bfd_size_type offset, bfd_size_type size)
10486 {
10487   struct dwarf2_section_info result;
10488   asection *sectp;
10489
10490   gdb_assert (section != NULL);
10491   gdb_assert (!section->is_virtual);
10492
10493   memset (&result, 0, sizeof (result));
10494   result.s.containing_section = section;
10495   result.is_virtual = 1;
10496
10497   if (size == 0)
10498     return result;
10499
10500   sectp = get_section_bfd_section (section);
10501
10502   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10503      bounds of the real section.  This is a pretty-rare event, so just
10504      flag an error (easier) instead of a warning and trying to cope.  */
10505   if (sectp == NULL
10506       || offset + size > bfd_get_section_size (sectp))
10507     {
10508       bfd *abfd = sectp->owner;
10509
10510       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10511                " in section %s [in module %s]"),
10512              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10513              objfile_name (dwarf2_per_objfile->objfile));
10514     }
10515
10516   result.virtual_offset = offset;
10517   result.size = size;
10518   return result;
10519 }
10520
10521 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10522    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10523    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10524    This is for DWP version 2 files.  */
10525
10526 static struct dwo_unit *
10527 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10528                            uint32_t unit_index,
10529                            const char *comp_dir,
10530                            ULONGEST signature, int is_debug_types)
10531 {
10532   struct objfile *objfile = dwarf2_per_objfile->objfile;
10533   const struct dwp_hash_table *dwp_htab =
10534     is_debug_types ? dwp_file->tus : dwp_file->cus;
10535   bfd *dbfd = dwp_file->dbfd;
10536   const char *kind = is_debug_types ? "TU" : "CU";
10537   struct dwo_file *dwo_file;
10538   struct dwo_unit *dwo_unit;
10539   struct virtual_v2_dwo_sections sections;
10540   void **dwo_file_slot;
10541   char *virtual_dwo_name;
10542   struct cleanup *cleanups;
10543   int i;
10544
10545   gdb_assert (dwp_file->version == 2);
10546
10547   if (dwarf_read_debug)
10548     {
10549       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10550                           kind,
10551                           pulongest (unit_index), hex_string (signature),
10552                           dwp_file->name);
10553     }
10554
10555   /* Fetch the section offsets of this DWO unit.  */
10556
10557   memset (&sections, 0, sizeof (sections));
10558   cleanups = make_cleanup (null_cleanup, 0);
10559
10560   for (i = 0; i < dwp_htab->nr_columns; ++i)
10561     {
10562       uint32_t offset = read_4_bytes (dbfd,
10563                                       dwp_htab->section_pool.v2.offsets
10564                                       + (((unit_index - 1) * dwp_htab->nr_columns
10565                                           + i)
10566                                          * sizeof (uint32_t)));
10567       uint32_t size = read_4_bytes (dbfd,
10568                                     dwp_htab->section_pool.v2.sizes
10569                                     + (((unit_index - 1) * dwp_htab->nr_columns
10570                                         + i)
10571                                        * sizeof (uint32_t)));
10572
10573       switch (dwp_htab->section_pool.v2.section_ids[i])
10574         {
10575         case DW_SECT_INFO:
10576         case DW_SECT_TYPES:
10577           sections.info_or_types_offset = offset;
10578           sections.info_or_types_size = size;
10579           break;
10580         case DW_SECT_ABBREV:
10581           sections.abbrev_offset = offset;
10582           sections.abbrev_size = size;
10583           break;
10584         case DW_SECT_LINE:
10585           sections.line_offset = offset;
10586           sections.line_size = size;
10587           break;
10588         case DW_SECT_LOC:
10589           sections.loc_offset = offset;
10590           sections.loc_size = size;
10591           break;
10592         case DW_SECT_STR_OFFSETS:
10593           sections.str_offsets_offset = offset;
10594           sections.str_offsets_size = size;
10595           break;
10596         case DW_SECT_MACINFO:
10597           sections.macinfo_offset = offset;
10598           sections.macinfo_size = size;
10599           break;
10600         case DW_SECT_MACRO:
10601           sections.macro_offset = offset;
10602           sections.macro_size = size;
10603           break;
10604         }
10605     }
10606
10607   /* It's easier for the rest of the code if we fake a struct dwo_file and
10608      have dwo_unit "live" in that.  At least for now.
10609
10610      The DWP file can be made up of a random collection of CUs and TUs.
10611      However, for each CU + set of TUs that came from the same original DWO
10612      file, we can combine them back into a virtual DWO file to save space
10613      (fewer struct dwo_file objects to allocate).  Remember that for really
10614      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10615
10616   virtual_dwo_name =
10617     xstrprintf ("virtual-dwo/%ld-%ld-%ld-%ld",
10618                 (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10619                 (long) (sections.line_size ? sections.line_offset : 0),
10620                 (long) (sections.loc_size ? sections.loc_offset : 0),
10621                 (long) (sections.str_offsets_size
10622                         ? sections.str_offsets_offset : 0));
10623   make_cleanup (xfree, virtual_dwo_name);
10624   /* Can we use an existing virtual DWO file?  */
10625   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name, comp_dir);
10626   /* Create one if necessary.  */
10627   if (*dwo_file_slot == NULL)
10628     {
10629       if (dwarf_read_debug)
10630         {
10631           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10632                               virtual_dwo_name);
10633         }
10634       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10635       dwo_file->dwo_name
10636         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10637                                         virtual_dwo_name,
10638                                         strlen (virtual_dwo_name));
10639       dwo_file->comp_dir = comp_dir;
10640       dwo_file->sections.abbrev =
10641         create_dwp_v2_section (&dwp_file->sections.abbrev,
10642                                sections.abbrev_offset, sections.abbrev_size);
10643       dwo_file->sections.line =
10644         create_dwp_v2_section (&dwp_file->sections.line,
10645                                sections.line_offset, sections.line_size);
10646       dwo_file->sections.loc =
10647         create_dwp_v2_section (&dwp_file->sections.loc,
10648                                sections.loc_offset, sections.loc_size);
10649       dwo_file->sections.macinfo =
10650         create_dwp_v2_section (&dwp_file->sections.macinfo,
10651                                sections.macinfo_offset, sections.macinfo_size);
10652       dwo_file->sections.macro =
10653         create_dwp_v2_section (&dwp_file->sections.macro,
10654                                sections.macro_offset, sections.macro_size);
10655       dwo_file->sections.str_offsets =
10656         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10657                                sections.str_offsets_offset,
10658                                sections.str_offsets_size);
10659       /* The "str" section is global to the entire DWP file.  */
10660       dwo_file->sections.str = dwp_file->sections.str;
10661       /* The info or types section is assigned below to dwo_unit,
10662          there's no need to record it in dwo_file.
10663          Also, we can't simply record type sections in dwo_file because
10664          we record a pointer into the vector in dwo_unit.  As we collect more
10665          types we'll grow the vector and eventually have to reallocate space
10666          for it, invalidating all copies of pointers into the previous
10667          contents.  */
10668       *dwo_file_slot = dwo_file;
10669     }
10670   else
10671     {
10672       if (dwarf_read_debug)
10673         {
10674           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10675                               virtual_dwo_name);
10676         }
10677       dwo_file = (struct dwo_file *) *dwo_file_slot;
10678     }
10679   do_cleanups (cleanups);
10680
10681   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10682   dwo_unit->dwo_file = dwo_file;
10683   dwo_unit->signature = signature;
10684   dwo_unit->section =
10685     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10686   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10687                                               ? &dwp_file->sections.types
10688                                               : &dwp_file->sections.info,
10689                                               sections.info_or_types_offset,
10690                                               sections.info_or_types_size);
10691   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10692
10693   return dwo_unit;
10694 }
10695
10696 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10697    Returns NULL if the signature isn't found.  */
10698
10699 static struct dwo_unit *
10700 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10701                         ULONGEST signature, int is_debug_types)
10702 {
10703   const struct dwp_hash_table *dwp_htab =
10704     is_debug_types ? dwp_file->tus : dwp_file->cus;
10705   bfd *dbfd = dwp_file->dbfd;
10706   uint32_t mask = dwp_htab->nr_slots - 1;
10707   uint32_t hash = signature & mask;
10708   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10709   unsigned int i;
10710   void **slot;
10711   struct dwo_unit find_dwo_cu;
10712
10713   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10714   find_dwo_cu.signature = signature;
10715   slot = htab_find_slot (is_debug_types
10716                          ? dwp_file->loaded_tus
10717                          : dwp_file->loaded_cus,
10718                          &find_dwo_cu, INSERT);
10719
10720   if (*slot != NULL)
10721     return (struct dwo_unit *) *slot;
10722
10723   /* Use a for loop so that we don't loop forever on bad debug info.  */
10724   for (i = 0; i < dwp_htab->nr_slots; ++i)
10725     {
10726       ULONGEST signature_in_table;
10727
10728       signature_in_table =
10729         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10730       if (signature_in_table == signature)
10731         {
10732           uint32_t unit_index =
10733             read_4_bytes (dbfd,
10734                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10735
10736           if (dwp_file->version == 1)
10737             {
10738               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10739                                                  comp_dir, signature,
10740                                                  is_debug_types);
10741             }
10742           else
10743             {
10744               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10745                                                  comp_dir, signature,
10746                                                  is_debug_types);
10747             }
10748           return (struct dwo_unit *) *slot;
10749         }
10750       if (signature_in_table == 0)
10751         return NULL;
10752       hash = (hash + hash2) & mask;
10753     }
10754
10755   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10756            " [in module %s]"),
10757          dwp_file->name);
10758 }
10759
10760 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10761    Open the file specified by FILE_NAME and hand it off to BFD for
10762    preliminary analysis.  Return a newly initialized bfd *, which
10763    includes a canonicalized copy of FILE_NAME.
10764    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10765    SEARCH_CWD is true if the current directory is to be searched.
10766    It will be searched before debug-file-directory.
10767    If successful, the file is added to the bfd include table of the
10768    objfile's bfd (see gdb_bfd_record_inclusion).
10769    If unable to find/open the file, return NULL.
10770    NOTE: This function is derived from symfile_bfd_open.  */
10771
10772 static gdb_bfd_ref_ptr
10773 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10774 {
10775   int desc, flags;
10776   char *absolute_name;
10777   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10778      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10779      to debug_file_directory.  */
10780   char *search_path;
10781   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10782
10783   if (search_cwd)
10784     {
10785       if (*debug_file_directory != '\0')
10786         search_path = concat (".", dirname_separator_string,
10787                               debug_file_directory, (char *) NULL);
10788       else
10789         search_path = xstrdup (".");
10790     }
10791   else
10792     search_path = xstrdup (debug_file_directory);
10793
10794   flags = OPF_RETURN_REALPATH;
10795   if (is_dwp)
10796     flags |= OPF_SEARCH_IN_PATH;
10797   desc = openp (search_path, flags, file_name,
10798                 O_RDONLY | O_BINARY, &absolute_name);
10799   xfree (search_path);
10800   if (desc < 0)
10801     return NULL;
10802
10803   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10804   xfree (absolute_name);
10805   if (sym_bfd == NULL)
10806     return NULL;
10807   bfd_set_cacheable (sym_bfd.get (), 1);
10808
10809   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10810     return NULL;
10811
10812   /* Success.  Record the bfd as having been included by the objfile's bfd.
10813      This is important because things like demangled_names_hash lives in the
10814      objfile's per_bfd space and may have references to things like symbol
10815      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10816   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10817
10818   return sym_bfd;
10819 }
10820
10821 /* Try to open DWO file FILE_NAME.
10822    COMP_DIR is the DW_AT_comp_dir attribute.
10823    The result is the bfd handle of the file.
10824    If there is a problem finding or opening the file, return NULL.
10825    Upon success, the canonicalized path of the file is stored in the bfd,
10826    same as symfile_bfd_open.  */
10827
10828 static gdb_bfd_ref_ptr
10829 open_dwo_file (const char *file_name, const char *comp_dir)
10830 {
10831   if (IS_ABSOLUTE_PATH (file_name))
10832     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10833
10834   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10835
10836   if (comp_dir != NULL)
10837     {
10838       char *path_to_try = concat (comp_dir, SLASH_STRING,
10839                                   file_name, (char *) NULL);
10840
10841       /* NOTE: If comp_dir is a relative path, this will also try the
10842          search path, which seems useful.  */
10843       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10844                                                 1 /*search_cwd*/));
10845       xfree (path_to_try);
10846       if (abfd != NULL)
10847         return abfd;
10848     }
10849
10850   /* That didn't work, try debug-file-directory, which, despite its name,
10851      is a list of paths.  */
10852
10853   if (*debug_file_directory == '\0')
10854     return NULL;
10855
10856   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10857 }
10858
10859 /* This function is mapped across the sections and remembers the offset and
10860    size of each of the DWO debugging sections we are interested in.  */
10861
10862 static void
10863 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10864 {
10865   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10866   const struct dwop_section_names *names = &dwop_section_names;
10867
10868   if (section_is_p (sectp->name, &names->abbrev_dwo))
10869     {
10870       dwo_sections->abbrev.s.section = sectp;
10871       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10872     }
10873   else if (section_is_p (sectp->name, &names->info_dwo))
10874     {
10875       dwo_sections->info.s.section = sectp;
10876       dwo_sections->info.size = bfd_get_section_size (sectp);
10877     }
10878   else if (section_is_p (sectp->name, &names->line_dwo))
10879     {
10880       dwo_sections->line.s.section = sectp;
10881       dwo_sections->line.size = bfd_get_section_size (sectp);
10882     }
10883   else if (section_is_p (sectp->name, &names->loc_dwo))
10884     {
10885       dwo_sections->loc.s.section = sectp;
10886       dwo_sections->loc.size = bfd_get_section_size (sectp);
10887     }
10888   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10889     {
10890       dwo_sections->macinfo.s.section = sectp;
10891       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10892     }
10893   else if (section_is_p (sectp->name, &names->macro_dwo))
10894     {
10895       dwo_sections->macro.s.section = sectp;
10896       dwo_sections->macro.size = bfd_get_section_size (sectp);
10897     }
10898   else if (section_is_p (sectp->name, &names->str_dwo))
10899     {
10900       dwo_sections->str.s.section = sectp;
10901       dwo_sections->str.size = bfd_get_section_size (sectp);
10902     }
10903   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10904     {
10905       dwo_sections->str_offsets.s.section = sectp;
10906       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10907     }
10908   else if (section_is_p (sectp->name, &names->types_dwo))
10909     {
10910       struct dwarf2_section_info type_section;
10911
10912       memset (&type_section, 0, sizeof (type_section));
10913       type_section.s.section = sectp;
10914       type_section.size = bfd_get_section_size (sectp);
10915       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10916                      &type_section);
10917     }
10918 }
10919
10920 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10921    by PER_CU.  This is for the non-DWP case.
10922    The result is NULL if DWO_NAME can't be found.  */
10923
10924 static struct dwo_file *
10925 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10926                         const char *dwo_name, const char *comp_dir)
10927 {
10928   struct objfile *objfile = dwarf2_per_objfile->objfile;
10929   struct dwo_file *dwo_file;
10930   struct cleanup *cleanups;
10931
10932   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10933   if (dbfd == NULL)
10934     {
10935       if (dwarf_read_debug)
10936         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10937       return NULL;
10938     }
10939   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10940   dwo_file->dwo_name = dwo_name;
10941   dwo_file->comp_dir = comp_dir;
10942   dwo_file->dbfd = dbfd.release ();
10943
10944   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10945
10946   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10947                          &dwo_file->sections);
10948
10949   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10950
10951   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10952                                  dwo_file->tus);
10953
10954   discard_cleanups (cleanups);
10955
10956   if (dwarf_read_debug)
10957     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10958
10959   return dwo_file;
10960 }
10961
10962 /* This function is mapped across the sections and remembers the offset and
10963    size of each of the DWP debugging sections common to version 1 and 2 that
10964    we are interested in.  */
10965
10966 static void
10967 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10968                                    void *dwp_file_ptr)
10969 {
10970   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10971   const struct dwop_section_names *names = &dwop_section_names;
10972   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10973
10974   /* Record the ELF section number for later lookup: this is what the
10975      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10976   gdb_assert (elf_section_nr < dwp_file->num_sections);
10977   dwp_file->elf_sections[elf_section_nr] = sectp;
10978
10979   /* Look for specific sections that we need.  */
10980   if (section_is_p (sectp->name, &names->str_dwo))
10981     {
10982       dwp_file->sections.str.s.section = sectp;
10983       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10984     }
10985   else if (section_is_p (sectp->name, &names->cu_index))
10986     {
10987       dwp_file->sections.cu_index.s.section = sectp;
10988       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10989     }
10990   else if (section_is_p (sectp->name, &names->tu_index))
10991     {
10992       dwp_file->sections.tu_index.s.section = sectp;
10993       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10994     }
10995 }
10996
10997 /* This function is mapped across the sections and remembers the offset and
10998    size of each of the DWP version 2 debugging sections that we are interested
10999    in.  This is split into a separate function because we don't know if we
11000    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11001
11002 static void
11003 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11004 {
11005   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11006   const struct dwop_section_names *names = &dwop_section_names;
11007   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11008
11009   /* Record the ELF section number for later lookup: this is what the
11010      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11011   gdb_assert (elf_section_nr < dwp_file->num_sections);
11012   dwp_file->elf_sections[elf_section_nr] = sectp;
11013
11014   /* Look for specific sections that we need.  */
11015   if (section_is_p (sectp->name, &names->abbrev_dwo))
11016     {
11017       dwp_file->sections.abbrev.s.section = sectp;
11018       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11019     }
11020   else if (section_is_p (sectp->name, &names->info_dwo))
11021     {
11022       dwp_file->sections.info.s.section = sectp;
11023       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11024     }
11025   else if (section_is_p (sectp->name, &names->line_dwo))
11026     {
11027       dwp_file->sections.line.s.section = sectp;
11028       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11029     }
11030   else if (section_is_p (sectp->name, &names->loc_dwo))
11031     {
11032       dwp_file->sections.loc.s.section = sectp;
11033       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11034     }
11035   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11036     {
11037       dwp_file->sections.macinfo.s.section = sectp;
11038       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11039     }
11040   else if (section_is_p (sectp->name, &names->macro_dwo))
11041     {
11042       dwp_file->sections.macro.s.section = sectp;
11043       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11044     }
11045   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11046     {
11047       dwp_file->sections.str_offsets.s.section = sectp;
11048       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11049     }
11050   else if (section_is_p (sectp->name, &names->types_dwo))
11051     {
11052       dwp_file->sections.types.s.section = sectp;
11053       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11054     }
11055 }
11056
11057 /* Hash function for dwp_file loaded CUs/TUs.  */
11058
11059 static hashval_t
11060 hash_dwp_loaded_cutus (const void *item)
11061 {
11062   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11063
11064   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11065   return dwo_unit->signature;
11066 }
11067
11068 /* Equality function for dwp_file loaded CUs/TUs.  */
11069
11070 static int
11071 eq_dwp_loaded_cutus (const void *a, const void *b)
11072 {
11073   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11074   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11075
11076   return dua->signature == dub->signature;
11077 }
11078
11079 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11080
11081 static htab_t
11082 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11083 {
11084   return htab_create_alloc_ex (3,
11085                                hash_dwp_loaded_cutus,
11086                                eq_dwp_loaded_cutus,
11087                                NULL,
11088                                &objfile->objfile_obstack,
11089                                hashtab_obstack_allocate,
11090                                dummy_obstack_deallocate);
11091 }
11092
11093 /* Try to open DWP file FILE_NAME.
11094    The result is the bfd handle of the file.
11095    If there is a problem finding or opening the file, return NULL.
11096    Upon success, the canonicalized path of the file is stored in the bfd,
11097    same as symfile_bfd_open.  */
11098
11099 static gdb_bfd_ref_ptr
11100 open_dwp_file (const char *file_name)
11101 {
11102   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11103                                             1 /*search_cwd*/));
11104   if (abfd != NULL)
11105     return abfd;
11106
11107   /* Work around upstream bug 15652.
11108      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11109      [Whether that's a "bug" is debatable, but it is getting in our way.]
11110      We have no real idea where the dwp file is, because gdb's realpath-ing
11111      of the executable's path may have discarded the needed info.
11112      [IWBN if the dwp file name was recorded in the executable, akin to
11113      .gnu_debuglink, but that doesn't exist yet.]
11114      Strip the directory from FILE_NAME and search again.  */
11115   if (*debug_file_directory != '\0')
11116     {
11117       /* Don't implicitly search the current directory here.
11118          If the user wants to search "." to handle this case,
11119          it must be added to debug-file-directory.  */
11120       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11121                                  0 /*search_cwd*/);
11122     }
11123
11124   return NULL;
11125 }
11126
11127 /* Initialize the use of the DWP file for the current objfile.
11128    By convention the name of the DWP file is ${objfile}.dwp.
11129    The result is NULL if it can't be found.  */
11130
11131 static struct dwp_file *
11132 open_and_init_dwp_file (void)
11133 {
11134   struct objfile *objfile = dwarf2_per_objfile->objfile;
11135   struct dwp_file *dwp_file;
11136
11137   /* Try to find first .dwp for the binary file before any symbolic links
11138      resolving.  */
11139
11140   /* If the objfile is a debug file, find the name of the real binary
11141      file and get the name of dwp file from there.  */
11142   std::string dwp_name;
11143   if (objfile->separate_debug_objfile_backlink != NULL)
11144     {
11145       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11146       const char *backlink_basename = lbasename (backlink->original_name);
11147
11148       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11149     }
11150   else
11151     dwp_name = objfile->original_name;
11152
11153   dwp_name += ".dwp";
11154
11155   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11156   if (dbfd == NULL
11157       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11158     {
11159       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11160       dwp_name = objfile_name (objfile);
11161       dwp_name += ".dwp";
11162       dbfd = open_dwp_file (dwp_name.c_str ());
11163     }
11164
11165   if (dbfd == NULL)
11166     {
11167       if (dwarf_read_debug)
11168         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11169       return NULL;
11170     }
11171   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11172   dwp_file->name = bfd_get_filename (dbfd.get ());
11173   dwp_file->dbfd = dbfd.release ();
11174
11175   /* +1: section 0 is unused */
11176   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11177   dwp_file->elf_sections =
11178     OBSTACK_CALLOC (&objfile->objfile_obstack,
11179                     dwp_file->num_sections, asection *);
11180
11181   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11182                          dwp_file);
11183
11184   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11185
11186   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11187
11188   /* The DWP file version is stored in the hash table.  Oh well.  */
11189   if (dwp_file->cus->version != dwp_file->tus->version)
11190     {
11191       /* Technically speaking, we should try to limp along, but this is
11192          pretty bizarre.  We use pulongest here because that's the established
11193          portability solution (e.g, we cannot use %u for uint32_t).  */
11194       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11195                " TU version %s [in DWP file %s]"),
11196              pulongest (dwp_file->cus->version),
11197              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11198     }
11199   dwp_file->version = dwp_file->cus->version;
11200
11201   if (dwp_file->version == 2)
11202     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11203                            dwp_file);
11204
11205   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11206   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11207
11208   if (dwarf_read_debug)
11209     {
11210       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11211       fprintf_unfiltered (gdb_stdlog,
11212                           "    %s CUs, %s TUs\n",
11213                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11214                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11215     }
11216
11217   return dwp_file;
11218 }
11219
11220 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11221
11222 static struct dwp_file *
11223 get_dwp_file (void)
11224 {
11225   if (! dwarf2_per_objfile->dwp_checked)
11226     {
11227       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11228       dwarf2_per_objfile->dwp_checked = 1;
11229     }
11230   return dwarf2_per_objfile->dwp_file;
11231 }
11232
11233 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11234    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11235    or in the DWP file for the objfile, referenced by THIS_UNIT.
11236    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11237    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11238
11239    This is called, for example, when wanting to read a variable with a
11240    complex location.  Therefore we don't want to do file i/o for every call.
11241    Therefore we don't want to look for a DWO file on every call.
11242    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11243    then we check if we've already seen DWO_NAME, and only THEN do we check
11244    for a DWO file.
11245
11246    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11247    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11248
11249 static struct dwo_unit *
11250 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11251                  const char *dwo_name, const char *comp_dir,
11252                  ULONGEST signature, int is_debug_types)
11253 {
11254   struct objfile *objfile = dwarf2_per_objfile->objfile;
11255   const char *kind = is_debug_types ? "TU" : "CU";
11256   void **dwo_file_slot;
11257   struct dwo_file *dwo_file;
11258   struct dwp_file *dwp_file;
11259
11260   /* First see if there's a DWP file.
11261      If we have a DWP file but didn't find the DWO inside it, don't
11262      look for the original DWO file.  It makes gdb behave differently
11263      depending on whether one is debugging in the build tree.  */
11264
11265   dwp_file = get_dwp_file ();
11266   if (dwp_file != NULL)
11267     {
11268       const struct dwp_hash_table *dwp_htab =
11269         is_debug_types ? dwp_file->tus : dwp_file->cus;
11270
11271       if (dwp_htab != NULL)
11272         {
11273           struct dwo_unit *dwo_cutu =
11274             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11275                                     signature, is_debug_types);
11276
11277           if (dwo_cutu != NULL)
11278             {
11279               if (dwarf_read_debug)
11280                 {
11281                   fprintf_unfiltered (gdb_stdlog,
11282                                       "Virtual DWO %s %s found: @%s\n",
11283                                       kind, hex_string (signature),
11284                                       host_address_to_string (dwo_cutu));
11285                 }
11286               return dwo_cutu;
11287             }
11288         }
11289     }
11290   else
11291     {
11292       /* No DWP file, look for the DWO file.  */
11293
11294       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11295       if (*dwo_file_slot == NULL)
11296         {
11297           /* Read in the file and build a table of the CUs/TUs it contains.  */
11298           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11299         }
11300       /* NOTE: This will be NULL if unable to open the file.  */
11301       dwo_file = (struct dwo_file *) *dwo_file_slot;
11302
11303       if (dwo_file != NULL)
11304         {
11305           struct dwo_unit *dwo_cutu = NULL;
11306
11307           if (is_debug_types && dwo_file->tus)
11308             {
11309               struct dwo_unit find_dwo_cutu;
11310
11311               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11312               find_dwo_cutu.signature = signature;
11313               dwo_cutu
11314                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11315             }
11316           else if (!is_debug_types && dwo_file->cus)
11317             {
11318               struct dwo_unit find_dwo_cutu;
11319
11320               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11321               find_dwo_cutu.signature = signature;
11322               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11323                                                        &find_dwo_cutu);
11324             }
11325
11326           if (dwo_cutu != NULL)
11327             {
11328               if (dwarf_read_debug)
11329                 {
11330                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11331                                       kind, dwo_name, hex_string (signature),
11332                                       host_address_to_string (dwo_cutu));
11333                 }
11334               return dwo_cutu;
11335             }
11336         }
11337     }
11338
11339   /* We didn't find it.  This could mean a dwo_id mismatch, or
11340      someone deleted the DWO/DWP file, or the search path isn't set up
11341      correctly to find the file.  */
11342
11343   if (dwarf_read_debug)
11344     {
11345       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11346                           kind, dwo_name, hex_string (signature));
11347     }
11348
11349   /* This is a warning and not a complaint because it can be caused by
11350      pilot error (e.g., user accidentally deleting the DWO).  */
11351   {
11352     /* Print the name of the DWP file if we looked there, helps the user
11353        better diagnose the problem.  */
11354     char *dwp_text = NULL;
11355     struct cleanup *cleanups;
11356
11357     if (dwp_file != NULL)
11358       dwp_text = xstrprintf (" [in DWP file %s]", lbasename (dwp_file->name));
11359     cleanups = make_cleanup (xfree, dwp_text);
11360
11361     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11362                " [in module %s]"),
11363              kind, dwo_name, hex_string (signature),
11364              dwp_text != NULL ? dwp_text : "",
11365              this_unit->is_debug_types ? "TU" : "CU",
11366              to_underlying (this_unit->sect_off), objfile_name (objfile));
11367
11368     do_cleanups (cleanups);
11369   }
11370   return NULL;
11371 }
11372
11373 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11374    See lookup_dwo_cutu_unit for details.  */
11375
11376 static struct dwo_unit *
11377 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11378                       const char *dwo_name, const char *comp_dir,
11379                       ULONGEST signature)
11380 {
11381   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11382 }
11383
11384 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11385    See lookup_dwo_cutu_unit for details.  */
11386
11387 static struct dwo_unit *
11388 lookup_dwo_type_unit (struct signatured_type *this_tu,
11389                       const char *dwo_name, const char *comp_dir)
11390 {
11391   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11392 }
11393
11394 /* Traversal function for queue_and_load_all_dwo_tus.  */
11395
11396 static int
11397 queue_and_load_dwo_tu (void **slot, void *info)
11398 {
11399   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11400   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11401   ULONGEST signature = dwo_unit->signature;
11402   struct signatured_type *sig_type =
11403     lookup_dwo_signatured_type (per_cu->cu, signature);
11404
11405   if (sig_type != NULL)
11406     {
11407       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11408
11409       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11410          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11411          while processing PER_CU.  */
11412       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11413         load_full_type_unit (sig_cu);
11414       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11415     }
11416
11417   return 1;
11418 }
11419
11420 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11421    The DWO may have the only definition of the type, though it may not be
11422    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11423    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11424
11425 static void
11426 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11427 {
11428   struct dwo_unit *dwo_unit;
11429   struct dwo_file *dwo_file;
11430
11431   gdb_assert (!per_cu->is_debug_types);
11432   gdb_assert (get_dwp_file () == NULL);
11433   gdb_assert (per_cu->cu != NULL);
11434
11435   dwo_unit = per_cu->cu->dwo_unit;
11436   gdb_assert (dwo_unit != NULL);
11437
11438   dwo_file = dwo_unit->dwo_file;
11439   if (dwo_file->tus != NULL)
11440     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11441 }
11442
11443 /* Free all resources associated with DWO_FILE.
11444    Close the DWO file and munmap the sections.
11445    All memory should be on the objfile obstack.  */
11446
11447 static void
11448 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11449 {
11450
11451   /* Note: dbfd is NULL for virtual DWO files.  */
11452   gdb_bfd_unref (dwo_file->dbfd);
11453
11454   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11455 }
11456
11457 /* Wrapper for free_dwo_file for use in cleanups.  */
11458
11459 static void
11460 free_dwo_file_cleanup (void *arg)
11461 {
11462   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11463   struct objfile *objfile = dwarf2_per_objfile->objfile;
11464
11465   free_dwo_file (dwo_file, objfile);
11466 }
11467
11468 /* Traversal function for free_dwo_files.  */
11469
11470 static int
11471 free_dwo_file_from_slot (void **slot, void *info)
11472 {
11473   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11474   struct objfile *objfile = (struct objfile *) info;
11475
11476   free_dwo_file (dwo_file, objfile);
11477
11478   return 1;
11479 }
11480
11481 /* Free all resources associated with DWO_FILES.  */
11482
11483 static void
11484 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11485 {
11486   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11487 }
11488 \f
11489 /* Read in various DIEs.  */
11490
11491 /* qsort helper for inherit_abstract_dies.  */
11492
11493 static int
11494 unsigned_int_compar (const void *ap, const void *bp)
11495 {
11496   unsigned int a = *(unsigned int *) ap;
11497   unsigned int b = *(unsigned int *) bp;
11498
11499   return (a > b) - (b > a);
11500 }
11501
11502 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11503    Inherit only the children of the DW_AT_abstract_origin DIE not being
11504    already referenced by DW_AT_abstract_origin from the children of the
11505    current DIE.  */
11506
11507 static void
11508 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11509 {
11510   struct die_info *child_die;
11511   unsigned die_children_count;
11512   /* CU offsets which were referenced by children of the current DIE.  */
11513   sect_offset *offsets;
11514   sect_offset *offsets_end, *offsetp;
11515   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11516   struct die_info *origin_die;
11517   /* Iterator of the ORIGIN_DIE children.  */
11518   struct die_info *origin_child_die;
11519   struct cleanup *cleanups;
11520   struct attribute *attr;
11521   struct dwarf2_cu *origin_cu;
11522   struct pending **origin_previous_list_in_scope;
11523
11524   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11525   if (!attr)
11526     return;
11527
11528   /* Note that following die references may follow to a die in a
11529      different cu.  */
11530
11531   origin_cu = cu;
11532   origin_die = follow_die_ref (die, attr, &origin_cu);
11533
11534   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11535      symbols in.  */
11536   origin_previous_list_in_scope = origin_cu->list_in_scope;
11537   origin_cu->list_in_scope = cu->list_in_scope;
11538
11539   if (die->tag != origin_die->tag
11540       && !(die->tag == DW_TAG_inlined_subroutine
11541            && origin_die->tag == DW_TAG_subprogram))
11542     complaint (&symfile_complaints,
11543                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11544                to_underlying (die->sect_off),
11545                to_underlying (origin_die->sect_off));
11546
11547   child_die = die->child;
11548   die_children_count = 0;
11549   while (child_die && child_die->tag)
11550     {
11551       child_die = sibling_die (child_die);
11552       die_children_count++;
11553     }
11554   offsets = XNEWVEC (sect_offset, die_children_count);
11555   cleanups = make_cleanup (xfree, offsets);
11556
11557   offsets_end = offsets;
11558   for (child_die = die->child;
11559        child_die && child_die->tag;
11560        child_die = sibling_die (child_die))
11561     {
11562       struct die_info *child_origin_die;
11563       struct dwarf2_cu *child_origin_cu;
11564
11565       /* We are trying to process concrete instance entries:
11566          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11567          it's not relevant to our analysis here. i.e. detecting DIEs that are
11568          present in the abstract instance but not referenced in the concrete
11569          one.  */
11570       if (child_die->tag == DW_TAG_call_site
11571           || child_die->tag == DW_TAG_GNU_call_site)
11572         continue;
11573
11574       /* For each CHILD_DIE, find the corresponding child of
11575          ORIGIN_DIE.  If there is more than one layer of
11576          DW_AT_abstract_origin, follow them all; there shouldn't be,
11577          but GCC versions at least through 4.4 generate this (GCC PR
11578          40573).  */
11579       child_origin_die = child_die;
11580       child_origin_cu = cu;
11581       while (1)
11582         {
11583           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11584                               child_origin_cu);
11585           if (attr == NULL)
11586             break;
11587           child_origin_die = follow_die_ref (child_origin_die, attr,
11588                                              &child_origin_cu);
11589         }
11590
11591       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11592          counterpart may exist.  */
11593       if (child_origin_die != child_die)
11594         {
11595           if (child_die->tag != child_origin_die->tag
11596               && !(child_die->tag == DW_TAG_inlined_subroutine
11597                    && child_origin_die->tag == DW_TAG_subprogram))
11598             complaint (&symfile_complaints,
11599                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11600                          "different tags"),
11601                        to_underlying (child_die->sect_off),
11602                        to_underlying (child_origin_die->sect_off));
11603           if (child_origin_die->parent != origin_die)
11604             complaint (&symfile_complaints,
11605                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11606                          "different parents"),
11607                        to_underlying (child_die->sect_off),
11608                        to_underlying (child_origin_die->sect_off));
11609           else
11610             *offsets_end++ = child_origin_die->sect_off;
11611         }
11612     }
11613   qsort (offsets, offsets_end - offsets, sizeof (*offsets),
11614          unsigned_int_compar);
11615   for (offsetp = offsets + 1; offsetp < offsets_end; offsetp++)
11616     if (offsetp[-1] == *offsetp)
11617       complaint (&symfile_complaints,
11618                  _("Multiple children of DIE 0x%x refer "
11619                    "to DIE 0x%x as their abstract origin"),
11620                  to_underlying (die->sect_off), to_underlying (*offsetp));
11621
11622   offsetp = offsets;
11623   origin_child_die = origin_die->child;
11624   while (origin_child_die && origin_child_die->tag)
11625     {
11626       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11627       while (offsetp < offsets_end
11628              && *offsetp < origin_child_die->sect_off)
11629         offsetp++;
11630       if (offsetp >= offsets_end
11631           || *offsetp > origin_child_die->sect_off)
11632         {
11633           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11634              Check whether we're already processing ORIGIN_CHILD_DIE.
11635              This can happen with mutually referenced abstract_origins.
11636              PR 16581.  */
11637           if (!origin_child_die->in_process)
11638             process_die (origin_child_die, origin_cu);
11639         }
11640       origin_child_die = sibling_die (origin_child_die);
11641     }
11642   origin_cu->list_in_scope = origin_previous_list_in_scope;
11643
11644   do_cleanups (cleanups);
11645 }
11646
11647 static void
11648 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11649 {
11650   struct objfile *objfile = cu->objfile;
11651   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11652   struct context_stack *newobj;
11653   CORE_ADDR lowpc;
11654   CORE_ADDR highpc;
11655   struct die_info *child_die;
11656   struct attribute *attr, *call_line, *call_file;
11657   const char *name;
11658   CORE_ADDR baseaddr;
11659   struct block *block;
11660   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11661   VEC (symbolp) *template_args = NULL;
11662   struct template_symbol *templ_func = NULL;
11663
11664   if (inlined_func)
11665     {
11666       /* If we do not have call site information, we can't show the
11667          caller of this inlined function.  That's too confusing, so
11668          only use the scope for local variables.  */
11669       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11670       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11671       if (call_line == NULL || call_file == NULL)
11672         {
11673           read_lexical_block_scope (die, cu);
11674           return;
11675         }
11676     }
11677
11678   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11679
11680   name = dwarf2_name (die, cu);
11681
11682   /* Ignore functions with missing or empty names.  These are actually
11683      illegal according to the DWARF standard.  */
11684   if (name == NULL)
11685     {
11686       complaint (&symfile_complaints,
11687                  _("missing name for subprogram DIE at %d"),
11688                  to_underlying (die->sect_off));
11689       return;
11690     }
11691
11692   /* Ignore functions with missing or invalid low and high pc attributes.  */
11693   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11694       <= PC_BOUNDS_INVALID)
11695     {
11696       attr = dwarf2_attr (die, DW_AT_external, cu);
11697       if (!attr || !DW_UNSND (attr))
11698         complaint (&symfile_complaints,
11699                    _("cannot get low and high bounds "
11700                      "for subprogram DIE at %d"),
11701                    to_underlying (die->sect_off));
11702       return;
11703     }
11704
11705   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11706   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11707
11708   /* If we have any template arguments, then we must allocate a
11709      different sort of symbol.  */
11710   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11711     {
11712       if (child_die->tag == DW_TAG_template_type_param
11713           || child_die->tag == DW_TAG_template_value_param)
11714         {
11715           templ_func = allocate_template_symbol (objfile);
11716           templ_func->base.is_cplus_template_function = 1;
11717           break;
11718         }
11719     }
11720
11721   newobj = push_context (0, lowpc);
11722   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11723                                (struct symbol *) templ_func);
11724
11725   /* If there is a location expression for DW_AT_frame_base, record
11726      it.  */
11727   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11728   if (attr)
11729     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11730
11731   /* If there is a location for the static link, record it.  */
11732   newobj->static_link = NULL;
11733   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11734   if (attr)
11735     {
11736       newobj->static_link
11737         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11738       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11739     }
11740
11741   cu->list_in_scope = &local_symbols;
11742
11743   if (die->child != NULL)
11744     {
11745       child_die = die->child;
11746       while (child_die && child_die->tag)
11747         {
11748           if (child_die->tag == DW_TAG_template_type_param
11749               || child_die->tag == DW_TAG_template_value_param)
11750             {
11751               struct symbol *arg = new_symbol (child_die, NULL, cu);
11752
11753               if (arg != NULL)
11754                 VEC_safe_push (symbolp, template_args, arg);
11755             }
11756           else
11757             process_die (child_die, cu);
11758           child_die = sibling_die (child_die);
11759         }
11760     }
11761
11762   inherit_abstract_dies (die, cu);
11763
11764   /* If we have a DW_AT_specification, we might need to import using
11765      directives from the context of the specification DIE.  See the
11766      comment in determine_prefix.  */
11767   if (cu->language == language_cplus
11768       && dwarf2_attr (die, DW_AT_specification, cu))
11769     {
11770       struct dwarf2_cu *spec_cu = cu;
11771       struct die_info *spec_die = die_specification (die, &spec_cu);
11772
11773       while (spec_die)
11774         {
11775           child_die = spec_die->child;
11776           while (child_die && child_die->tag)
11777             {
11778               if (child_die->tag == DW_TAG_imported_module)
11779                 process_die (child_die, spec_cu);
11780               child_die = sibling_die (child_die);
11781             }
11782
11783           /* In some cases, GCC generates specification DIEs that
11784              themselves contain DW_AT_specification attributes.  */
11785           spec_die = die_specification (spec_die, &spec_cu);
11786         }
11787     }
11788
11789   newobj = pop_context ();
11790   /* Make a block for the local symbols within.  */
11791   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11792                         newobj->static_link, lowpc, highpc);
11793
11794   /* For C++, set the block's scope.  */
11795   if ((cu->language == language_cplus
11796        || cu->language == language_fortran
11797        || cu->language == language_d
11798        || cu->language == language_rust)
11799       && cu->processing_has_namespace_info)
11800     block_set_scope (block, determine_prefix (die, cu),
11801                      &objfile->objfile_obstack);
11802
11803   /* If we have address ranges, record them.  */
11804   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11805
11806   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11807
11808   /* Attach template arguments to function.  */
11809   if (! VEC_empty (symbolp, template_args))
11810     {
11811       gdb_assert (templ_func != NULL);
11812
11813       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11814       templ_func->template_arguments
11815         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11816                      templ_func->n_template_arguments);
11817       memcpy (templ_func->template_arguments,
11818               VEC_address (symbolp, template_args),
11819               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11820       VEC_free (symbolp, template_args);
11821     }
11822
11823   /* In C++, we can have functions nested inside functions (e.g., when
11824      a function declares a class that has methods).  This means that
11825      when we finish processing a function scope, we may need to go
11826      back to building a containing block's symbol lists.  */
11827   local_symbols = newobj->locals;
11828   local_using_directives = newobj->local_using_directives;
11829
11830   /* If we've finished processing a top-level function, subsequent
11831      symbols go in the file symbol list.  */
11832   if (outermost_context_p ())
11833     cu->list_in_scope = &file_symbols;
11834 }
11835
11836 /* Process all the DIES contained within a lexical block scope.  Start
11837    a new scope, process the dies, and then close the scope.  */
11838
11839 static void
11840 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11841 {
11842   struct objfile *objfile = cu->objfile;
11843   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11844   struct context_stack *newobj;
11845   CORE_ADDR lowpc, highpc;
11846   struct die_info *child_die;
11847   CORE_ADDR baseaddr;
11848
11849   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11850
11851   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11852   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11853      as multiple lexical blocks?  Handling children in a sane way would
11854      be nasty.  Might be easier to properly extend generic blocks to
11855      describe ranges.  */
11856   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11857     {
11858     case PC_BOUNDS_NOT_PRESENT:
11859       /* DW_TAG_lexical_block has no attributes, process its children as if
11860          there was no wrapping by that DW_TAG_lexical_block.
11861          GCC does no longer produces such DWARF since GCC r224161.  */
11862       for (child_die = die->child;
11863            child_die != NULL && child_die->tag;
11864            child_die = sibling_die (child_die))
11865         process_die (child_die, cu);
11866       return;
11867     case PC_BOUNDS_INVALID:
11868       return;
11869     }
11870   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11871   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11872
11873   push_context (0, lowpc);
11874   if (die->child != NULL)
11875     {
11876       child_die = die->child;
11877       while (child_die && child_die->tag)
11878         {
11879           process_die (child_die, cu);
11880           child_die = sibling_die (child_die);
11881         }
11882     }
11883   inherit_abstract_dies (die, cu);
11884   newobj = pop_context ();
11885
11886   if (local_symbols != NULL || local_using_directives != NULL)
11887     {
11888       struct block *block
11889         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11890                         newobj->start_addr, highpc);
11891
11892       /* Note that recording ranges after traversing children, as we
11893          do here, means that recording a parent's ranges entails
11894          walking across all its children's ranges as they appear in
11895          the address map, which is quadratic behavior.
11896
11897          It would be nicer to record the parent's ranges before
11898          traversing its children, simply overriding whatever you find
11899          there.  But since we don't even decide whether to create a
11900          block until after we've traversed its children, that's hard
11901          to do.  */
11902       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11903     }
11904   local_symbols = newobj->locals;
11905   local_using_directives = newobj->local_using_directives;
11906 }
11907
11908 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11909
11910 static void
11911 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11912 {
11913   struct objfile *objfile = cu->objfile;
11914   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11915   CORE_ADDR pc, baseaddr;
11916   struct attribute *attr;
11917   struct call_site *call_site, call_site_local;
11918   void **slot;
11919   int nparams;
11920   struct die_info *child_die;
11921
11922   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11923
11924   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11925   if (attr == NULL)
11926     {
11927       /* This was a pre-DWARF-5 GNU extension alias
11928          for DW_AT_call_return_pc.  */
11929       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11930     }
11931   if (!attr)
11932     {
11933       complaint (&symfile_complaints,
11934                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11935                    "DIE 0x%x [in module %s]"),
11936                  to_underlying (die->sect_off), objfile_name (objfile));
11937       return;
11938     }
11939   pc = attr_value_as_address (attr) + baseaddr;
11940   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11941
11942   if (cu->call_site_htab == NULL)
11943     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11944                                                NULL, &objfile->objfile_obstack,
11945                                                hashtab_obstack_allocate, NULL);
11946   call_site_local.pc = pc;
11947   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11948   if (*slot != NULL)
11949     {
11950       complaint (&symfile_complaints,
11951                  _("Duplicate PC %s for DW_TAG_call_site "
11952                    "DIE 0x%x [in module %s]"),
11953                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11954                  objfile_name (objfile));
11955       return;
11956     }
11957
11958   /* Count parameters at the caller.  */
11959
11960   nparams = 0;
11961   for (child_die = die->child; child_die && child_die->tag;
11962        child_die = sibling_die (child_die))
11963     {
11964       if (child_die->tag != DW_TAG_call_site_parameter
11965           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11966         {
11967           complaint (&symfile_complaints,
11968                      _("Tag %d is not DW_TAG_call_site_parameter in "
11969                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11970                      child_die->tag, to_underlying (child_die->sect_off),
11971                      objfile_name (objfile));
11972           continue;
11973         }
11974
11975       nparams++;
11976     }
11977
11978   call_site
11979     = ((struct call_site *)
11980        obstack_alloc (&objfile->objfile_obstack,
11981                       sizeof (*call_site)
11982                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11983   *slot = call_site;
11984   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11985   call_site->pc = pc;
11986
11987   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11988       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11989     {
11990       struct die_info *func_die;
11991
11992       /* Skip also over DW_TAG_inlined_subroutine.  */
11993       for (func_die = die->parent;
11994            func_die && func_die->tag != DW_TAG_subprogram
11995            && func_die->tag != DW_TAG_subroutine_type;
11996            func_die = func_die->parent);
11997
11998       /* DW_AT_call_all_calls is a superset
11999          of DW_AT_call_all_tail_calls.  */
12000       if (func_die
12001           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12002           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12003           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12004           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12005         {
12006           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12007              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12008              both the initial caller containing the real return address PC and
12009              the final callee containing the current PC of a chain of tail
12010              calls do not need to have the tail call list complete.  But any
12011              function candidate for a virtual tail call frame searched via
12012              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12013              determined unambiguously.  */
12014         }
12015       else
12016         {
12017           struct type *func_type = NULL;
12018
12019           if (func_die)
12020             func_type = get_die_type (func_die, cu);
12021           if (func_type != NULL)
12022             {
12023               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12024
12025               /* Enlist this call site to the function.  */
12026               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12027               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12028             }
12029           else
12030             complaint (&symfile_complaints,
12031                        _("Cannot find function owning DW_TAG_call_site "
12032                          "DIE 0x%x [in module %s]"),
12033                        to_underlying (die->sect_off), objfile_name (objfile));
12034         }
12035     }
12036
12037   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12038   if (attr == NULL)
12039     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12040   if (attr == NULL)
12041     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12042   if (attr == NULL)
12043     {
12044       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12045       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12046     }
12047   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12048   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12049     /* Keep NULL DWARF_BLOCK.  */;
12050   else if (attr_form_is_block (attr))
12051     {
12052       struct dwarf2_locexpr_baton *dlbaton;
12053
12054       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12055       dlbaton->data = DW_BLOCK (attr)->data;
12056       dlbaton->size = DW_BLOCK (attr)->size;
12057       dlbaton->per_cu = cu->per_cu;
12058
12059       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12060     }
12061   else if (attr_form_is_ref (attr))
12062     {
12063       struct dwarf2_cu *target_cu = cu;
12064       struct die_info *target_die;
12065
12066       target_die = follow_die_ref (die, attr, &target_cu);
12067       gdb_assert (target_cu->objfile == objfile);
12068       if (die_is_declaration (target_die, target_cu))
12069         {
12070           const char *target_physname;
12071
12072           /* Prefer the mangled name; otherwise compute the demangled one.  */
12073           target_physname = dw2_linkage_name (target_die, target_cu);
12074           if (target_physname == NULL)
12075             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12076           if (target_physname == NULL)
12077             complaint (&symfile_complaints,
12078                        _("DW_AT_call_target target DIE has invalid "
12079                          "physname, for referencing DIE 0x%x [in module %s]"),
12080                        to_underlying (die->sect_off), objfile_name (objfile));
12081           else
12082             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12083         }
12084       else
12085         {
12086           CORE_ADDR lowpc;
12087
12088           /* DW_AT_entry_pc should be preferred.  */
12089           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12090               <= PC_BOUNDS_INVALID)
12091             complaint (&symfile_complaints,
12092                        _("DW_AT_call_target target DIE has invalid "
12093                          "low pc, for referencing DIE 0x%x [in module %s]"),
12094                        to_underlying (die->sect_off), objfile_name (objfile));
12095           else
12096             {
12097               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12098               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12099             }
12100         }
12101     }
12102   else
12103     complaint (&symfile_complaints,
12104                _("DW_TAG_call_site DW_AT_call_target is neither "
12105                  "block nor reference, for DIE 0x%x [in module %s]"),
12106                to_underlying (die->sect_off), objfile_name (objfile));
12107
12108   call_site->per_cu = cu->per_cu;
12109
12110   for (child_die = die->child;
12111        child_die && child_die->tag;
12112        child_die = sibling_die (child_die))
12113     {
12114       struct call_site_parameter *parameter;
12115       struct attribute *loc, *origin;
12116
12117       if (child_die->tag != DW_TAG_call_site_parameter
12118           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12119         {
12120           /* Already printed the complaint above.  */
12121           continue;
12122         }
12123
12124       gdb_assert (call_site->parameter_count < nparams);
12125       parameter = &call_site->parameter[call_site->parameter_count];
12126
12127       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12128          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12129          register is contained in DW_AT_call_value.  */
12130
12131       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12132       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12133       if (origin == NULL)
12134         {
12135           /* This was a pre-DWARF-5 GNU extension alias
12136              for DW_AT_call_parameter.  */
12137           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12138         }
12139       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12140         {
12141           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12142
12143           sect_offset sect_off
12144             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12145           if (!offset_in_cu_p (&cu->header, sect_off))
12146             {
12147               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12148                  binding can be done only inside one CU.  Such referenced DIE
12149                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12150               complaint (&symfile_complaints,
12151                          _("DW_AT_call_parameter offset is not in CU for "
12152                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12153                          to_underlying (child_die->sect_off),
12154                          objfile_name (objfile));
12155               continue;
12156             }
12157           parameter->u.param_cu_off
12158             = (cu_offset) (sect_off - cu->header.sect_off);
12159         }
12160       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12161         {
12162           complaint (&symfile_complaints,
12163                      _("No DW_FORM_block* DW_AT_location for "
12164                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12165                      to_underlying (child_die->sect_off), objfile_name (objfile));
12166           continue;
12167         }
12168       else
12169         {
12170           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12171             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12172           if (parameter->u.dwarf_reg != -1)
12173             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12174           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12175                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12176                                              &parameter->u.fb_offset))
12177             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12178           else
12179             {
12180               complaint (&symfile_complaints,
12181                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12182                            "for DW_FORM_block* DW_AT_location is supported for "
12183                            "DW_TAG_call_site child DIE 0x%x "
12184                            "[in module %s]"),
12185                          to_underlying (child_die->sect_off),
12186                          objfile_name (objfile));
12187               continue;
12188             }
12189         }
12190
12191       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12192       if (attr == NULL)
12193         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12194       if (!attr_form_is_block (attr))
12195         {
12196           complaint (&symfile_complaints,
12197                      _("No DW_FORM_block* DW_AT_call_value for "
12198                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12199                      to_underlying (child_die->sect_off),
12200                      objfile_name (objfile));
12201           continue;
12202         }
12203       parameter->value = DW_BLOCK (attr)->data;
12204       parameter->value_size = DW_BLOCK (attr)->size;
12205
12206       /* Parameters are not pre-cleared by memset above.  */
12207       parameter->data_value = NULL;
12208       parameter->data_value_size = 0;
12209       call_site->parameter_count++;
12210
12211       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12212       if (attr == NULL)
12213         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12214       if (attr)
12215         {
12216           if (!attr_form_is_block (attr))
12217             complaint (&symfile_complaints,
12218                        _("No DW_FORM_block* DW_AT_call_data_value for "
12219                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12220                        to_underlying (child_die->sect_off),
12221                        objfile_name (objfile));
12222           else
12223             {
12224               parameter->data_value = DW_BLOCK (attr)->data;
12225               parameter->data_value_size = DW_BLOCK (attr)->size;
12226             }
12227         }
12228     }
12229 }
12230
12231 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12232    reading .debug_rnglists.
12233    Callback's type should be:
12234     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12235    Return true if the attributes are present and valid, otherwise,
12236    return false.  */
12237
12238 template <typename Callback>
12239 static bool
12240 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12241                          Callback &&callback)
12242 {
12243   struct objfile *objfile = cu->objfile;
12244   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12245   struct comp_unit_head *cu_header = &cu->header;
12246   bfd *obfd = objfile->obfd;
12247   unsigned int addr_size = cu_header->addr_size;
12248   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12249   /* Base address selection entry.  */
12250   CORE_ADDR base;
12251   int found_base;
12252   unsigned int dummy;
12253   const gdb_byte *buffer;
12254   CORE_ADDR low = 0;
12255   CORE_ADDR high = 0;
12256   CORE_ADDR baseaddr;
12257   bool overflow = false;
12258
12259   found_base = cu->base_known;
12260   base = cu->base_address;
12261
12262   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12263   if (offset >= dwarf2_per_objfile->rnglists.size)
12264     {
12265       complaint (&symfile_complaints,
12266                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12267                  offset);
12268       return false;
12269     }
12270   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12271
12272   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12273
12274   while (1)
12275     {
12276       /* Initialize it due to a false compiler warning.  */
12277       CORE_ADDR range_beginning = 0, range_end = 0;
12278       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12279                                  + dwarf2_per_objfile->rnglists.size);
12280       unsigned int bytes_read;
12281
12282       if (buffer == buf_end)
12283         {
12284           overflow = true;
12285           break;
12286         }
12287       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12288       switch (rlet)
12289         {
12290         case DW_RLE_end_of_list:
12291           break;
12292         case DW_RLE_base_address:
12293           if (buffer + cu->header.addr_size > buf_end)
12294             {
12295               overflow = true;
12296               break;
12297             }
12298           base = read_address (obfd, buffer, cu, &bytes_read);
12299           found_base = 1;
12300           buffer += bytes_read;
12301           break;
12302         case DW_RLE_start_length:
12303           if (buffer + cu->header.addr_size > buf_end)
12304             {
12305               overflow = true;
12306               break;
12307             }
12308           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12309           buffer += bytes_read;
12310           range_end = (range_beginning
12311                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12312           buffer += bytes_read;
12313           if (buffer > buf_end)
12314             {
12315               overflow = true;
12316               break;
12317             }
12318           break;
12319         case DW_RLE_offset_pair:
12320           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12321           buffer += bytes_read;
12322           if (buffer > buf_end)
12323             {
12324               overflow = true;
12325               break;
12326             }
12327           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12328           buffer += bytes_read;
12329           if (buffer > buf_end)
12330             {
12331               overflow = true;
12332               break;
12333             }
12334           break;
12335         case DW_RLE_start_end:
12336           if (buffer + 2 * cu->header.addr_size > buf_end)
12337             {
12338               overflow = true;
12339               break;
12340             }
12341           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12342           buffer += bytes_read;
12343           range_end = read_address (obfd, buffer, cu, &bytes_read);
12344           buffer += bytes_read;
12345           break;
12346         default:
12347           complaint (&symfile_complaints,
12348                      _("Invalid .debug_rnglists data (no base address)"));
12349           return false;
12350         }
12351       if (rlet == DW_RLE_end_of_list || overflow)
12352         break;
12353       if (rlet == DW_RLE_base_address)
12354         continue;
12355
12356       if (!found_base)
12357         {
12358           /* We have no valid base address for the ranges
12359              data.  */
12360           complaint (&symfile_complaints,
12361                      _("Invalid .debug_rnglists data (no base address)"));
12362           return false;
12363         }
12364
12365       if (range_beginning > range_end)
12366         {
12367           /* Inverted range entries are invalid.  */
12368           complaint (&symfile_complaints,
12369                      _("Invalid .debug_rnglists data (inverted range)"));
12370           return false;
12371         }
12372
12373       /* Empty range entries have no effect.  */
12374       if (range_beginning == range_end)
12375         continue;
12376
12377       range_beginning += base;
12378       range_end += base;
12379
12380       /* A not-uncommon case of bad debug info.
12381          Don't pollute the addrmap with bad data.  */
12382       if (range_beginning + baseaddr == 0
12383           && !dwarf2_per_objfile->has_section_at_zero)
12384         {
12385           complaint (&symfile_complaints,
12386                      _(".debug_rnglists entry has start address of zero"
12387                        " [in module %s]"), objfile_name (objfile));
12388           continue;
12389         }
12390
12391       callback (range_beginning, range_end);
12392     }
12393
12394   if (overflow)
12395     {
12396       complaint (&symfile_complaints,
12397                  _("Offset %d is not terminated "
12398                    "for DW_AT_ranges attribute"),
12399                  offset);
12400       return false;
12401     }
12402
12403   return true;
12404 }
12405
12406 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12407    Callback's type should be:
12408     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12409    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12410
12411 template <typename Callback>
12412 static int
12413 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12414                        Callback &&callback)
12415 {
12416   struct objfile *objfile = cu->objfile;
12417   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12418   struct comp_unit_head *cu_header = &cu->header;
12419   bfd *obfd = objfile->obfd;
12420   unsigned int addr_size = cu_header->addr_size;
12421   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12422   /* Base address selection entry.  */
12423   CORE_ADDR base;
12424   int found_base;
12425   unsigned int dummy;
12426   const gdb_byte *buffer;
12427   CORE_ADDR baseaddr;
12428
12429   if (cu_header->version >= 5)
12430     return dwarf2_rnglists_process (offset, cu, callback);
12431
12432   found_base = cu->base_known;
12433   base = cu->base_address;
12434
12435   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12436   if (offset >= dwarf2_per_objfile->ranges.size)
12437     {
12438       complaint (&symfile_complaints,
12439                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12440                  offset);
12441       return 0;
12442     }
12443   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12444
12445   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12446
12447   while (1)
12448     {
12449       CORE_ADDR range_beginning, range_end;
12450
12451       range_beginning = read_address (obfd, buffer, cu, &dummy);
12452       buffer += addr_size;
12453       range_end = read_address (obfd, buffer, cu, &dummy);
12454       buffer += addr_size;
12455       offset += 2 * addr_size;
12456
12457       /* An end of list marker is a pair of zero addresses.  */
12458       if (range_beginning == 0 && range_end == 0)
12459         /* Found the end of list entry.  */
12460         break;
12461
12462       /* Each base address selection entry is a pair of 2 values.
12463          The first is the largest possible address, the second is
12464          the base address.  Check for a base address here.  */
12465       if ((range_beginning & mask) == mask)
12466         {
12467           /* If we found the largest possible address, then we already
12468              have the base address in range_end.  */
12469           base = range_end;
12470           found_base = 1;
12471           continue;
12472         }
12473
12474       if (!found_base)
12475         {
12476           /* We have no valid base address for the ranges
12477              data.  */
12478           complaint (&symfile_complaints,
12479                      _("Invalid .debug_ranges data (no base address)"));
12480           return 0;
12481         }
12482
12483       if (range_beginning > range_end)
12484         {
12485           /* Inverted range entries are invalid.  */
12486           complaint (&symfile_complaints,
12487                      _("Invalid .debug_ranges data (inverted range)"));
12488           return 0;
12489         }
12490
12491       /* Empty range entries have no effect.  */
12492       if (range_beginning == range_end)
12493         continue;
12494
12495       range_beginning += base;
12496       range_end += base;
12497
12498       /* A not-uncommon case of bad debug info.
12499          Don't pollute the addrmap with bad data.  */
12500       if (range_beginning + baseaddr == 0
12501           && !dwarf2_per_objfile->has_section_at_zero)
12502         {
12503           complaint (&symfile_complaints,
12504                      _(".debug_ranges entry has start address of zero"
12505                        " [in module %s]"), objfile_name (objfile));
12506           continue;
12507         }
12508
12509       callback (range_beginning, range_end);
12510     }
12511
12512   return 1;
12513 }
12514
12515 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12516    Return 1 if the attributes are present and valid, otherwise, return 0.
12517    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12518
12519 static int
12520 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12521                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12522                     struct partial_symtab *ranges_pst)
12523 {
12524   struct objfile *objfile = cu->objfile;
12525   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12526   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12527                                        SECT_OFF_TEXT (objfile));
12528   int low_set = 0;
12529   CORE_ADDR low = 0;
12530   CORE_ADDR high = 0;
12531   int retval;
12532
12533   retval = dwarf2_ranges_process (offset, cu,
12534     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12535     {
12536       if (ranges_pst != NULL)
12537         {
12538           CORE_ADDR lowpc;
12539           CORE_ADDR highpc;
12540
12541           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12542                                               range_beginning + baseaddr);
12543           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12544                                                range_end + baseaddr);
12545           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12546                              ranges_pst);
12547         }
12548
12549       /* FIXME: This is recording everything as a low-high
12550          segment of consecutive addresses.  We should have a
12551          data structure for discontiguous block ranges
12552          instead.  */
12553       if (! low_set)
12554         {
12555           low = range_beginning;
12556           high = range_end;
12557           low_set = 1;
12558         }
12559       else
12560         {
12561           if (range_beginning < low)
12562             low = range_beginning;
12563           if (range_end > high)
12564             high = range_end;
12565         }
12566     });
12567   if (!retval)
12568     return 0;
12569
12570   if (! low_set)
12571     /* If the first entry is an end-of-list marker, the range
12572        describes an empty scope, i.e. no instructions.  */
12573     return 0;
12574
12575   if (low_return)
12576     *low_return = low;
12577   if (high_return)
12578     *high_return = high;
12579   return 1;
12580 }
12581
12582 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12583    definition for the return value.  *LOWPC and *HIGHPC are set iff
12584    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12585
12586 static enum pc_bounds_kind
12587 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12588                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12589                       struct partial_symtab *pst)
12590 {
12591   struct attribute *attr;
12592   struct attribute *attr_high;
12593   CORE_ADDR low = 0;
12594   CORE_ADDR high = 0;
12595   enum pc_bounds_kind ret;
12596
12597   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12598   if (attr_high)
12599     {
12600       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12601       if (attr)
12602         {
12603           low = attr_value_as_address (attr);
12604           high = attr_value_as_address (attr_high);
12605           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12606             high += low;
12607         }
12608       else
12609         /* Found high w/o low attribute.  */
12610         return PC_BOUNDS_INVALID;
12611
12612       /* Found consecutive range of addresses.  */
12613       ret = PC_BOUNDS_HIGH_LOW;
12614     }
12615   else
12616     {
12617       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12618       if (attr != NULL)
12619         {
12620           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12621              We take advantage of the fact that DW_AT_ranges does not appear
12622              in DW_TAG_compile_unit of DWO files.  */
12623           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12624           unsigned int ranges_offset = (DW_UNSND (attr)
12625                                         + (need_ranges_base
12626                                            ? cu->ranges_base
12627                                            : 0));
12628
12629           /* Value of the DW_AT_ranges attribute is the offset in the
12630              .debug_ranges section.  */
12631           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12632             return PC_BOUNDS_INVALID;
12633           /* Found discontinuous range of addresses.  */
12634           ret = PC_BOUNDS_RANGES;
12635         }
12636       else
12637         return PC_BOUNDS_NOT_PRESENT;
12638     }
12639
12640   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12641   if (high <= low)
12642     return PC_BOUNDS_INVALID;
12643
12644   /* When using the GNU linker, .gnu.linkonce. sections are used to
12645      eliminate duplicate copies of functions and vtables and such.
12646      The linker will arbitrarily choose one and discard the others.
12647      The AT_*_pc values for such functions refer to local labels in
12648      these sections.  If the section from that file was discarded, the
12649      labels are not in the output, so the relocs get a value of 0.
12650      If this is a discarded function, mark the pc bounds as invalid,
12651      so that GDB will ignore it.  */
12652   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12653     return PC_BOUNDS_INVALID;
12654
12655   *lowpc = low;
12656   if (highpc)
12657     *highpc = high;
12658   return ret;
12659 }
12660
12661 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12662    its low and high PC addresses.  Do nothing if these addresses could not
12663    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12664    and HIGHPC to the high address if greater than HIGHPC.  */
12665
12666 static void
12667 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12668                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12669                                  struct dwarf2_cu *cu)
12670 {
12671   CORE_ADDR low, high;
12672   struct die_info *child = die->child;
12673
12674   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12675     {
12676       *lowpc = std::min (*lowpc, low);
12677       *highpc = std::max (*highpc, high);
12678     }
12679
12680   /* If the language does not allow nested subprograms (either inside
12681      subprograms or lexical blocks), we're done.  */
12682   if (cu->language != language_ada)
12683     return;
12684
12685   /* Check all the children of the given DIE.  If it contains nested
12686      subprograms, then check their pc bounds.  Likewise, we need to
12687      check lexical blocks as well, as they may also contain subprogram
12688      definitions.  */
12689   while (child && child->tag)
12690     {
12691       if (child->tag == DW_TAG_subprogram
12692           || child->tag == DW_TAG_lexical_block)
12693         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12694       child = sibling_die (child);
12695     }
12696 }
12697
12698 /* Get the low and high pc's represented by the scope DIE, and store
12699    them in *LOWPC and *HIGHPC.  If the correct values can't be
12700    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12701
12702 static void
12703 get_scope_pc_bounds (struct die_info *die,
12704                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12705                      struct dwarf2_cu *cu)
12706 {
12707   CORE_ADDR best_low = (CORE_ADDR) -1;
12708   CORE_ADDR best_high = (CORE_ADDR) 0;
12709   CORE_ADDR current_low, current_high;
12710
12711   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12712       >= PC_BOUNDS_RANGES)
12713     {
12714       best_low = current_low;
12715       best_high = current_high;
12716     }
12717   else
12718     {
12719       struct die_info *child = die->child;
12720
12721       while (child && child->tag)
12722         {
12723           switch (child->tag) {
12724           case DW_TAG_subprogram:
12725             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12726             break;
12727           case DW_TAG_namespace:
12728           case DW_TAG_module:
12729             /* FIXME: carlton/2004-01-16: Should we do this for
12730                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12731                that current GCC's always emit the DIEs corresponding
12732                to definitions of methods of classes as children of a
12733                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12734                the DIEs giving the declarations, which could be
12735                anywhere).  But I don't see any reason why the
12736                standards says that they have to be there.  */
12737             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12738
12739             if (current_low != ((CORE_ADDR) -1))
12740               {
12741                 best_low = std::min (best_low, current_low);
12742                 best_high = std::max (best_high, current_high);
12743               }
12744             break;
12745           default:
12746             /* Ignore.  */
12747             break;
12748           }
12749
12750           child = sibling_die (child);
12751         }
12752     }
12753
12754   *lowpc = best_low;
12755   *highpc = best_high;
12756 }
12757
12758 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12759    in DIE.  */
12760
12761 static void
12762 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12763                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12764 {
12765   struct objfile *objfile = cu->objfile;
12766   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12767   struct attribute *attr;
12768   struct attribute *attr_high;
12769
12770   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12771   if (attr_high)
12772     {
12773       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12774       if (attr)
12775         {
12776           CORE_ADDR low = attr_value_as_address (attr);
12777           CORE_ADDR high = attr_value_as_address (attr_high);
12778
12779           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12780             high += low;
12781
12782           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12783           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12784           record_block_range (block, low, high - 1);
12785         }
12786     }
12787
12788   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12789   if (attr)
12790     {
12791       bfd *obfd = objfile->obfd;
12792       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12793          We take advantage of the fact that DW_AT_ranges does not appear
12794          in DW_TAG_compile_unit of DWO files.  */
12795       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12796
12797       /* The value of the DW_AT_ranges attribute is the offset of the
12798          address range list in the .debug_ranges section.  */
12799       unsigned long offset = (DW_UNSND (attr)
12800                               + (need_ranges_base ? cu->ranges_base : 0));
12801       const gdb_byte *buffer;
12802
12803       /* For some target architectures, but not others, the
12804          read_address function sign-extends the addresses it returns.
12805          To recognize base address selection entries, we need a
12806          mask.  */
12807       unsigned int addr_size = cu->header.addr_size;
12808       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12809
12810       /* The base address, to which the next pair is relative.  Note
12811          that this 'base' is a DWARF concept: most entries in a range
12812          list are relative, to reduce the number of relocs against the
12813          debugging information.  This is separate from this function's
12814          'baseaddr' argument, which GDB uses to relocate debugging
12815          information from a shared library based on the address at
12816          which the library was loaded.  */
12817       CORE_ADDR base = cu->base_address;
12818       int base_known = cu->base_known;
12819
12820       dwarf2_ranges_process (offset, cu,
12821         [&] (CORE_ADDR start, CORE_ADDR end)
12822         {
12823           start += baseaddr;
12824           end += baseaddr;
12825           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12826           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12827           record_block_range (block, start, end - 1);
12828         });
12829     }
12830 }
12831
12832 /* Check whether the producer field indicates either of GCC < 4.6, or the
12833    Intel C/C++ compiler, and cache the result in CU.  */
12834
12835 static void
12836 check_producer (struct dwarf2_cu *cu)
12837 {
12838   int major, minor;
12839
12840   if (cu->producer == NULL)
12841     {
12842       /* For unknown compilers expect their behavior is DWARF version
12843          compliant.
12844
12845          GCC started to support .debug_types sections by -gdwarf-4 since
12846          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12847          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12848          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12849          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12850     }
12851   else if (producer_is_gcc (cu->producer, &major, &minor))
12852     {
12853       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12854       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12855     }
12856   else if (startswith (cu->producer, "Intel(R) C"))
12857     cu->producer_is_icc = 1;
12858   else
12859     {
12860       /* For other non-GCC compilers, expect their behavior is DWARF version
12861          compliant.  */
12862     }
12863
12864   cu->checked_producer = 1;
12865 }
12866
12867 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12868    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12869    during 4.6.0 experimental.  */
12870
12871 static int
12872 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12873 {
12874   if (!cu->checked_producer)
12875     check_producer (cu);
12876
12877   return cu->producer_is_gxx_lt_4_6;
12878 }
12879
12880 /* Return the default accessibility type if it is not overriden by
12881    DW_AT_accessibility.  */
12882
12883 static enum dwarf_access_attribute
12884 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12885 {
12886   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12887     {
12888       /* The default DWARF 2 accessibility for members is public, the default
12889          accessibility for inheritance is private.  */
12890
12891       if (die->tag != DW_TAG_inheritance)
12892         return DW_ACCESS_public;
12893       else
12894         return DW_ACCESS_private;
12895     }
12896   else
12897     {
12898       /* DWARF 3+ defines the default accessibility a different way.  The same
12899          rules apply now for DW_TAG_inheritance as for the members and it only
12900          depends on the container kind.  */
12901
12902       if (die->parent->tag == DW_TAG_class_type)
12903         return DW_ACCESS_private;
12904       else
12905         return DW_ACCESS_public;
12906     }
12907 }
12908
12909 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12910    offset.  If the attribute was not found return 0, otherwise return
12911    1.  If it was found but could not properly be handled, set *OFFSET
12912    to 0.  */
12913
12914 static int
12915 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12916                              LONGEST *offset)
12917 {
12918   struct attribute *attr;
12919
12920   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12921   if (attr != NULL)
12922     {
12923       *offset = 0;
12924
12925       /* Note that we do not check for a section offset first here.
12926          This is because DW_AT_data_member_location is new in DWARF 4,
12927          so if we see it, we can assume that a constant form is really
12928          a constant and not a section offset.  */
12929       if (attr_form_is_constant (attr))
12930         *offset = dwarf2_get_attr_constant_value (attr, 0);
12931       else if (attr_form_is_section_offset (attr))
12932         dwarf2_complex_location_expr_complaint ();
12933       else if (attr_form_is_block (attr))
12934         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12935       else
12936         dwarf2_complex_location_expr_complaint ();
12937
12938       return 1;
12939     }
12940
12941   return 0;
12942 }
12943
12944 /* Add an aggregate field to the field list.  */
12945
12946 static void
12947 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12948                   struct dwarf2_cu *cu)
12949 {
12950   struct objfile *objfile = cu->objfile;
12951   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12952   struct nextfield *new_field;
12953   struct attribute *attr;
12954   struct field *fp;
12955   const char *fieldname = "";
12956
12957   /* Allocate a new field list entry and link it in.  */
12958   new_field = XNEW (struct nextfield);
12959   make_cleanup (xfree, new_field);
12960   memset (new_field, 0, sizeof (struct nextfield));
12961
12962   if (die->tag == DW_TAG_inheritance)
12963     {
12964       new_field->next = fip->baseclasses;
12965       fip->baseclasses = new_field;
12966     }
12967   else
12968     {
12969       new_field->next = fip->fields;
12970       fip->fields = new_field;
12971     }
12972   fip->nfields++;
12973
12974   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12975   if (attr)
12976     new_field->accessibility = DW_UNSND (attr);
12977   else
12978     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12979   if (new_field->accessibility != DW_ACCESS_public)
12980     fip->non_public_fields = 1;
12981
12982   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12983   if (attr)
12984     new_field->virtuality = DW_UNSND (attr);
12985   else
12986     new_field->virtuality = DW_VIRTUALITY_none;
12987
12988   fp = &new_field->field;
12989
12990   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12991     {
12992       LONGEST offset;
12993
12994       /* Data member other than a C++ static data member.  */
12995
12996       /* Get type of field.  */
12997       fp->type = die_type (die, cu);
12998
12999       SET_FIELD_BITPOS (*fp, 0);
13000
13001       /* Get bit size of field (zero if none).  */
13002       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13003       if (attr)
13004         {
13005           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13006         }
13007       else
13008         {
13009           FIELD_BITSIZE (*fp) = 0;
13010         }
13011
13012       /* Get bit offset of field.  */
13013       if (handle_data_member_location (die, cu, &offset))
13014         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13015       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13016       if (attr)
13017         {
13018           if (gdbarch_bits_big_endian (gdbarch))
13019             {
13020               /* For big endian bits, the DW_AT_bit_offset gives the
13021                  additional bit offset from the MSB of the containing
13022                  anonymous object to the MSB of the field.  We don't
13023                  have to do anything special since we don't need to
13024                  know the size of the anonymous object.  */
13025               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13026             }
13027           else
13028             {
13029               /* For little endian bits, compute the bit offset to the
13030                  MSB of the anonymous object, subtract off the number of
13031                  bits from the MSB of the field to the MSB of the
13032                  object, and then subtract off the number of bits of
13033                  the field itself.  The result is the bit offset of
13034                  the LSB of the field.  */
13035               int anonymous_size;
13036               int bit_offset = DW_UNSND (attr);
13037
13038               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13039               if (attr)
13040                 {
13041                   /* The size of the anonymous object containing
13042                      the bit field is explicit, so use the
13043                      indicated size (in bytes).  */
13044                   anonymous_size = DW_UNSND (attr);
13045                 }
13046               else
13047                 {
13048                   /* The size of the anonymous object containing
13049                      the bit field must be inferred from the type
13050                      attribute of the data member containing the
13051                      bit field.  */
13052                   anonymous_size = TYPE_LENGTH (fp->type);
13053                 }
13054               SET_FIELD_BITPOS (*fp,
13055                                 (FIELD_BITPOS (*fp)
13056                                  + anonymous_size * bits_per_byte
13057                                  - bit_offset - FIELD_BITSIZE (*fp)));
13058             }
13059         }
13060       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13061       if (attr != NULL)
13062         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13063                                 + dwarf2_get_attr_constant_value (attr, 0)));
13064
13065       /* Get name of field.  */
13066       fieldname = dwarf2_name (die, cu);
13067       if (fieldname == NULL)
13068         fieldname = "";
13069
13070       /* The name is already allocated along with this objfile, so we don't
13071          need to duplicate it for the type.  */
13072       fp->name = fieldname;
13073
13074       /* Change accessibility for artificial fields (e.g. virtual table
13075          pointer or virtual base class pointer) to private.  */
13076       if (dwarf2_attr (die, DW_AT_artificial, cu))
13077         {
13078           FIELD_ARTIFICIAL (*fp) = 1;
13079           new_field->accessibility = DW_ACCESS_private;
13080           fip->non_public_fields = 1;
13081         }
13082     }
13083   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13084     {
13085       /* C++ static member.  */
13086
13087       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13088          is a declaration, but all versions of G++ as of this writing
13089          (so through at least 3.2.1) incorrectly generate
13090          DW_TAG_variable tags.  */
13091
13092       const char *physname;
13093
13094       /* Get name of field.  */
13095       fieldname = dwarf2_name (die, cu);
13096       if (fieldname == NULL)
13097         return;
13098
13099       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13100       if (attr
13101           /* Only create a symbol if this is an external value.
13102              new_symbol checks this and puts the value in the global symbol
13103              table, which we want.  If it is not external, new_symbol
13104              will try to put the value in cu->list_in_scope which is wrong.  */
13105           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13106         {
13107           /* A static const member, not much different than an enum as far as
13108              we're concerned, except that we can support more types.  */
13109           new_symbol (die, NULL, cu);
13110         }
13111
13112       /* Get physical name.  */
13113       physname = dwarf2_physname (fieldname, die, cu);
13114
13115       /* The name is already allocated along with this objfile, so we don't
13116          need to duplicate it for the type.  */
13117       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13118       FIELD_TYPE (*fp) = die_type (die, cu);
13119       FIELD_NAME (*fp) = fieldname;
13120     }
13121   else if (die->tag == DW_TAG_inheritance)
13122     {
13123       LONGEST offset;
13124
13125       /* C++ base class field.  */
13126       if (handle_data_member_location (die, cu, &offset))
13127         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13128       FIELD_BITSIZE (*fp) = 0;
13129       FIELD_TYPE (*fp) = die_type (die, cu);
13130       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13131       fip->nbaseclasses++;
13132     }
13133 }
13134
13135 /* Add a typedef defined in the scope of the FIP's class.  */
13136
13137 static void
13138 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13139                     struct dwarf2_cu *cu)
13140 {
13141   struct typedef_field_list *new_field;
13142   struct typedef_field *fp;
13143
13144   /* Allocate a new field list entry and link it in.  */
13145   new_field = XCNEW (struct typedef_field_list);
13146   make_cleanup (xfree, new_field);
13147
13148   gdb_assert (die->tag == DW_TAG_typedef);
13149
13150   fp = &new_field->field;
13151
13152   /* Get name of field.  */
13153   fp->name = dwarf2_name (die, cu);
13154   if (fp->name == NULL)
13155     return;
13156
13157   fp->type = read_type_die (die, cu);
13158
13159   new_field->next = fip->typedef_field_list;
13160   fip->typedef_field_list = new_field;
13161   fip->typedef_field_list_count++;
13162 }
13163
13164 /* Create the vector of fields, and attach it to the type.  */
13165
13166 static void
13167 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13168                               struct dwarf2_cu *cu)
13169 {
13170   int nfields = fip->nfields;
13171
13172   /* Record the field count, allocate space for the array of fields,
13173      and create blank accessibility bitfields if necessary.  */
13174   TYPE_NFIELDS (type) = nfields;
13175   TYPE_FIELDS (type) = (struct field *)
13176     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13177   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13178
13179   if (fip->non_public_fields && cu->language != language_ada)
13180     {
13181       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13182
13183       TYPE_FIELD_PRIVATE_BITS (type) =
13184         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13185       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13186
13187       TYPE_FIELD_PROTECTED_BITS (type) =
13188         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13189       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13190
13191       TYPE_FIELD_IGNORE_BITS (type) =
13192         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13193       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13194     }
13195
13196   /* If the type has baseclasses, allocate and clear a bit vector for
13197      TYPE_FIELD_VIRTUAL_BITS.  */
13198   if (fip->nbaseclasses && cu->language != language_ada)
13199     {
13200       int num_bytes = B_BYTES (fip->nbaseclasses);
13201       unsigned char *pointer;
13202
13203       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13204       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13205       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13206       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13207       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13208     }
13209
13210   /* Copy the saved-up fields into the field vector.  Start from the head of
13211      the list, adding to the tail of the field array, so that they end up in
13212      the same order in the array in which they were added to the list.  */
13213   while (nfields-- > 0)
13214     {
13215       struct nextfield *fieldp;
13216
13217       if (fip->fields)
13218         {
13219           fieldp = fip->fields;
13220           fip->fields = fieldp->next;
13221         }
13222       else
13223         {
13224           fieldp = fip->baseclasses;
13225           fip->baseclasses = fieldp->next;
13226         }
13227
13228       TYPE_FIELD (type, nfields) = fieldp->field;
13229       switch (fieldp->accessibility)
13230         {
13231         case DW_ACCESS_private:
13232           if (cu->language != language_ada)
13233             SET_TYPE_FIELD_PRIVATE (type, nfields);
13234           break;
13235
13236         case DW_ACCESS_protected:
13237           if (cu->language != language_ada)
13238             SET_TYPE_FIELD_PROTECTED (type, nfields);
13239           break;
13240
13241         case DW_ACCESS_public:
13242           break;
13243
13244         default:
13245           /* Unknown accessibility.  Complain and treat it as public.  */
13246           {
13247             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13248                        fieldp->accessibility);
13249           }
13250           break;
13251         }
13252       if (nfields < fip->nbaseclasses)
13253         {
13254           switch (fieldp->virtuality)
13255             {
13256             case DW_VIRTUALITY_virtual:
13257             case DW_VIRTUALITY_pure_virtual:
13258               if (cu->language == language_ada)
13259                 error (_("unexpected virtuality in component of Ada type"));
13260               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13261               break;
13262             }
13263         }
13264     }
13265 }
13266
13267 /* Return true if this member function is a constructor, false
13268    otherwise.  */
13269
13270 static int
13271 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13272 {
13273   const char *fieldname;
13274   const char *type_name;
13275   int len;
13276
13277   if (die->parent == NULL)
13278     return 0;
13279
13280   if (die->parent->tag != DW_TAG_structure_type
13281       && die->parent->tag != DW_TAG_union_type
13282       && die->parent->tag != DW_TAG_class_type)
13283     return 0;
13284
13285   fieldname = dwarf2_name (die, cu);
13286   type_name = dwarf2_name (die->parent, cu);
13287   if (fieldname == NULL || type_name == NULL)
13288     return 0;
13289
13290   len = strlen (fieldname);
13291   return (strncmp (fieldname, type_name, len) == 0
13292           && (type_name[len] == '\0' || type_name[len] == '<'));
13293 }
13294
13295 /* Add a member function to the proper fieldlist.  */
13296
13297 static void
13298 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13299                       struct type *type, struct dwarf2_cu *cu)
13300 {
13301   struct objfile *objfile = cu->objfile;
13302   struct attribute *attr;
13303   struct fnfieldlist *flp;
13304   int i;
13305   struct fn_field *fnp;
13306   const char *fieldname;
13307   struct nextfnfield *new_fnfield;
13308   struct type *this_type;
13309   enum dwarf_access_attribute accessibility;
13310
13311   if (cu->language == language_ada)
13312     error (_("unexpected member function in Ada type"));
13313
13314   /* Get name of member function.  */
13315   fieldname = dwarf2_name (die, cu);
13316   if (fieldname == NULL)
13317     return;
13318
13319   /* Look up member function name in fieldlist.  */
13320   for (i = 0; i < fip->nfnfields; i++)
13321     {
13322       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13323         break;
13324     }
13325
13326   /* Create new list element if necessary.  */
13327   if (i < fip->nfnfields)
13328     flp = &fip->fnfieldlists[i];
13329   else
13330     {
13331       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13332         {
13333           fip->fnfieldlists = (struct fnfieldlist *)
13334             xrealloc (fip->fnfieldlists,
13335                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13336                       * sizeof (struct fnfieldlist));
13337           if (fip->nfnfields == 0)
13338             make_cleanup (free_current_contents, &fip->fnfieldlists);
13339         }
13340       flp = &fip->fnfieldlists[fip->nfnfields];
13341       flp->name = fieldname;
13342       flp->length = 0;
13343       flp->head = NULL;
13344       i = fip->nfnfields++;
13345     }
13346
13347   /* Create a new member function field and chain it to the field list
13348      entry.  */
13349   new_fnfield = XNEW (struct nextfnfield);
13350   make_cleanup (xfree, new_fnfield);
13351   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13352   new_fnfield->next = flp->head;
13353   flp->head = new_fnfield;
13354   flp->length++;
13355
13356   /* Fill in the member function field info.  */
13357   fnp = &new_fnfield->fnfield;
13358
13359   /* Delay processing of the physname until later.  */
13360   if (cu->language == language_cplus)
13361     {
13362       add_to_method_list (type, i, flp->length - 1, fieldname,
13363                           die, cu);
13364     }
13365   else
13366     {
13367       const char *physname = dwarf2_physname (fieldname, die, cu);
13368       fnp->physname = physname ? physname : "";
13369     }
13370
13371   fnp->type = alloc_type (objfile);
13372   this_type = read_type_die (die, cu);
13373   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13374     {
13375       int nparams = TYPE_NFIELDS (this_type);
13376
13377       /* TYPE is the domain of this method, and THIS_TYPE is the type
13378            of the method itself (TYPE_CODE_METHOD).  */
13379       smash_to_method_type (fnp->type, type,
13380                             TYPE_TARGET_TYPE (this_type),
13381                             TYPE_FIELDS (this_type),
13382                             TYPE_NFIELDS (this_type),
13383                             TYPE_VARARGS (this_type));
13384
13385       /* Handle static member functions.
13386          Dwarf2 has no clean way to discern C++ static and non-static
13387          member functions.  G++ helps GDB by marking the first
13388          parameter for non-static member functions (which is the this
13389          pointer) as artificial.  We obtain this information from
13390          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13391       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13392         fnp->voffset = VOFFSET_STATIC;
13393     }
13394   else
13395     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13396                dwarf2_full_name (fieldname, die, cu));
13397
13398   /* Get fcontext from DW_AT_containing_type if present.  */
13399   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13400     fnp->fcontext = die_containing_type (die, cu);
13401
13402   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13403      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13404
13405   /* Get accessibility.  */
13406   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13407   if (attr)
13408     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13409   else
13410     accessibility = dwarf2_default_access_attribute (die, cu);
13411   switch (accessibility)
13412     {
13413     case DW_ACCESS_private:
13414       fnp->is_private = 1;
13415       break;
13416     case DW_ACCESS_protected:
13417       fnp->is_protected = 1;
13418       break;
13419     }
13420
13421   /* Check for artificial methods.  */
13422   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13423   if (attr && DW_UNSND (attr) != 0)
13424     fnp->is_artificial = 1;
13425
13426   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13427
13428   /* Get index in virtual function table if it is a virtual member
13429      function.  For older versions of GCC, this is an offset in the
13430      appropriate virtual table, as specified by DW_AT_containing_type.
13431      For everyone else, it is an expression to be evaluated relative
13432      to the object address.  */
13433
13434   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13435   if (attr)
13436     {
13437       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13438         {
13439           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13440             {
13441               /* Old-style GCC.  */
13442               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13443             }
13444           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13445                    || (DW_BLOCK (attr)->size > 1
13446                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13447                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13448             {
13449               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13450               if ((fnp->voffset % cu->header.addr_size) != 0)
13451                 dwarf2_complex_location_expr_complaint ();
13452               else
13453                 fnp->voffset /= cu->header.addr_size;
13454               fnp->voffset += 2;
13455             }
13456           else
13457             dwarf2_complex_location_expr_complaint ();
13458
13459           if (!fnp->fcontext)
13460             {
13461               /* If there is no `this' field and no DW_AT_containing_type,
13462                  we cannot actually find a base class context for the
13463                  vtable!  */
13464               if (TYPE_NFIELDS (this_type) == 0
13465                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13466                 {
13467                   complaint (&symfile_complaints,
13468                              _("cannot determine context for virtual member "
13469                                "function \"%s\" (offset %d)"),
13470                              fieldname, to_underlying (die->sect_off));
13471                 }
13472               else
13473                 {
13474                   fnp->fcontext
13475                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13476                 }
13477             }
13478         }
13479       else if (attr_form_is_section_offset (attr))
13480         {
13481           dwarf2_complex_location_expr_complaint ();
13482         }
13483       else
13484         {
13485           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13486                                                  fieldname);
13487         }
13488     }
13489   else
13490     {
13491       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13492       if (attr && DW_UNSND (attr))
13493         {
13494           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13495           complaint (&symfile_complaints,
13496                      _("Member function \"%s\" (offset %d) is virtual "
13497                        "but the vtable offset is not specified"),
13498                      fieldname, to_underlying (die->sect_off));
13499           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13500           TYPE_CPLUS_DYNAMIC (type) = 1;
13501         }
13502     }
13503 }
13504
13505 /* Create the vector of member function fields, and attach it to the type.  */
13506
13507 static void
13508 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13509                                  struct dwarf2_cu *cu)
13510 {
13511   struct fnfieldlist *flp;
13512   int i;
13513
13514   if (cu->language == language_ada)
13515     error (_("unexpected member functions in Ada type"));
13516
13517   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13518   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13519     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13520
13521   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13522     {
13523       struct nextfnfield *nfp = flp->head;
13524       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13525       int k;
13526
13527       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13528       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13529       fn_flp->fn_fields = (struct fn_field *)
13530         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13531       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13532         fn_flp->fn_fields[k] = nfp->fnfield;
13533     }
13534
13535   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13536 }
13537
13538 /* Returns non-zero if NAME is the name of a vtable member in CU's
13539    language, zero otherwise.  */
13540 static int
13541 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13542 {
13543   static const char vptr[] = "_vptr";
13544   static const char vtable[] = "vtable";
13545
13546   /* Look for the C++ form of the vtable.  */
13547   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13548     return 1;
13549
13550   return 0;
13551 }
13552
13553 /* GCC outputs unnamed structures that are really pointers to member
13554    functions, with the ABI-specified layout.  If TYPE describes
13555    such a structure, smash it into a member function type.
13556
13557    GCC shouldn't do this; it should just output pointer to member DIEs.
13558    This is GCC PR debug/28767.  */
13559
13560 static void
13561 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13562 {
13563   struct type *pfn_type, *self_type, *new_type;
13564
13565   /* Check for a structure with no name and two children.  */
13566   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13567     return;
13568
13569   /* Check for __pfn and __delta members.  */
13570   if (TYPE_FIELD_NAME (type, 0) == NULL
13571       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13572       || TYPE_FIELD_NAME (type, 1) == NULL
13573       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13574     return;
13575
13576   /* Find the type of the method.  */
13577   pfn_type = TYPE_FIELD_TYPE (type, 0);
13578   if (pfn_type == NULL
13579       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13580       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13581     return;
13582
13583   /* Look for the "this" argument.  */
13584   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13585   if (TYPE_NFIELDS (pfn_type) == 0
13586       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13587       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13588     return;
13589
13590   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13591   new_type = alloc_type (objfile);
13592   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13593                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13594                         TYPE_VARARGS (pfn_type));
13595   smash_to_methodptr_type (type, new_type);
13596 }
13597
13598 /* Return non-zero if the CU's PRODUCER string matches the Intel C/C++ compiler
13599    (icc).  */
13600
13601 static int
13602 producer_is_icc (struct dwarf2_cu *cu)
13603 {
13604   if (!cu->checked_producer)
13605     check_producer (cu);
13606
13607   return cu->producer_is_icc;
13608 }
13609
13610 /* Called when we find the DIE that starts a structure or union scope
13611    (definition) to create a type for the structure or union.  Fill in
13612    the type's name and general properties; the members will not be
13613    processed until process_structure_scope.  A symbol table entry for
13614    the type will also not be done until process_structure_scope (assuming
13615    the type has a name).
13616
13617    NOTE: we need to call these functions regardless of whether or not the
13618    DIE has a DW_AT_name attribute, since it might be an anonymous
13619    structure or union.  This gets the type entered into our set of
13620    user defined types.  */
13621
13622 static struct type *
13623 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13624 {
13625   struct objfile *objfile = cu->objfile;
13626   struct type *type;
13627   struct attribute *attr;
13628   const char *name;
13629
13630   /* If the definition of this type lives in .debug_types, read that type.
13631      Don't follow DW_AT_specification though, that will take us back up
13632      the chain and we want to go down.  */
13633   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13634   if (attr)
13635     {
13636       type = get_DW_AT_signature_type (die, attr, cu);
13637
13638       /* The type's CU may not be the same as CU.
13639          Ensure TYPE is recorded with CU in die_type_hash.  */
13640       return set_die_type (die, type, cu);
13641     }
13642
13643   type = alloc_type (objfile);
13644   INIT_CPLUS_SPECIFIC (type);
13645
13646   name = dwarf2_name (die, cu);
13647   if (name != NULL)
13648     {
13649       if (cu->language == language_cplus
13650           || cu->language == language_d
13651           || cu->language == language_rust)
13652         {
13653           const char *full_name = dwarf2_full_name (name, die, cu);
13654
13655           /* dwarf2_full_name might have already finished building the DIE's
13656              type.  If so, there is no need to continue.  */
13657           if (get_die_type (die, cu) != NULL)
13658             return get_die_type (die, cu);
13659
13660           TYPE_TAG_NAME (type) = full_name;
13661           if (die->tag == DW_TAG_structure_type
13662               || die->tag == DW_TAG_class_type)
13663             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13664         }
13665       else
13666         {
13667           /* The name is already allocated along with this objfile, so
13668              we don't need to duplicate it for the type.  */
13669           TYPE_TAG_NAME (type) = name;
13670           if (die->tag == DW_TAG_class_type)
13671             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13672         }
13673     }
13674
13675   if (die->tag == DW_TAG_structure_type)
13676     {
13677       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13678     }
13679   else if (die->tag == DW_TAG_union_type)
13680     {
13681       TYPE_CODE (type) = TYPE_CODE_UNION;
13682     }
13683   else
13684     {
13685       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13686     }
13687
13688   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13689     TYPE_DECLARED_CLASS (type) = 1;
13690
13691   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13692   if (attr)
13693     {
13694       if (attr_form_is_constant (attr))
13695         TYPE_LENGTH (type) = DW_UNSND (attr);
13696       else
13697         {
13698           /* For the moment, dynamic type sizes are not supported
13699              by GDB's struct type.  The actual size is determined
13700              on-demand when resolving the type of a given object,
13701              so set the type's length to zero for now.  Otherwise,
13702              we record an expression as the length, and that expression
13703              could lead to a very large value, which could eventually
13704              lead to us trying to allocate that much memory when creating
13705              a value of that type.  */
13706           TYPE_LENGTH (type) = 0;
13707         }
13708     }
13709   else
13710     {
13711       TYPE_LENGTH (type) = 0;
13712     }
13713
13714   if (producer_is_icc (cu) && (TYPE_LENGTH (type) == 0))
13715     {
13716       /* ICC does not output the required DW_AT_declaration
13717          on incomplete types, but gives them a size of zero.  */
13718       TYPE_STUB (type) = 1;
13719     }
13720   else
13721     TYPE_STUB_SUPPORTED (type) = 1;
13722
13723   if (die_is_declaration (die, cu))
13724     TYPE_STUB (type) = 1;
13725   else if (attr == NULL && die->child == NULL
13726            && producer_is_realview (cu->producer))
13727     /* RealView does not output the required DW_AT_declaration
13728        on incomplete types.  */
13729     TYPE_STUB (type) = 1;
13730
13731   /* We need to add the type field to the die immediately so we don't
13732      infinitely recurse when dealing with pointers to the structure
13733      type within the structure itself.  */
13734   set_die_type (die, type, cu);
13735
13736   /* set_die_type should be already done.  */
13737   set_descriptive_type (type, die, cu);
13738
13739   return type;
13740 }
13741
13742 /* Finish creating a structure or union type, including filling in
13743    its members and creating a symbol for it.  */
13744
13745 static void
13746 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13747 {
13748   struct objfile *objfile = cu->objfile;
13749   struct die_info *child_die;
13750   struct type *type;
13751
13752   type = get_die_type (die, cu);
13753   if (type == NULL)
13754     type = read_structure_type (die, cu);
13755
13756   if (die->child != NULL && ! die_is_declaration (die, cu))
13757     {
13758       struct field_info fi;
13759       VEC (symbolp) *template_args = NULL;
13760       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13761
13762       memset (&fi, 0, sizeof (struct field_info));
13763
13764       child_die = die->child;
13765
13766       while (child_die && child_die->tag)
13767         {
13768           if (child_die->tag == DW_TAG_member
13769               || child_die->tag == DW_TAG_variable)
13770             {
13771               /* NOTE: carlton/2002-11-05: A C++ static data member
13772                  should be a DW_TAG_member that is a declaration, but
13773                  all versions of G++ as of this writing (so through at
13774                  least 3.2.1) incorrectly generate DW_TAG_variable
13775                  tags for them instead.  */
13776               dwarf2_add_field (&fi, child_die, cu);
13777             }
13778           else if (child_die->tag == DW_TAG_subprogram)
13779             {
13780               /* Rust doesn't have member functions in the C++ sense.
13781                  However, it does emit ordinary functions as children
13782                  of a struct DIE.  */
13783               if (cu->language == language_rust)
13784                 read_func_scope (child_die, cu);
13785               else
13786                 {
13787                   /* C++ member function.  */
13788                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13789                 }
13790             }
13791           else if (child_die->tag == DW_TAG_inheritance)
13792             {
13793               /* C++ base class field.  */
13794               dwarf2_add_field (&fi, child_die, cu);
13795             }
13796           else if (child_die->tag == DW_TAG_typedef)
13797             dwarf2_add_typedef (&fi, child_die, cu);
13798           else if (child_die->tag == DW_TAG_template_type_param
13799                    || child_die->tag == DW_TAG_template_value_param)
13800             {
13801               struct symbol *arg = new_symbol (child_die, NULL, cu);
13802
13803               if (arg != NULL)
13804                 VEC_safe_push (symbolp, template_args, arg);
13805             }
13806
13807           child_die = sibling_die (child_die);
13808         }
13809
13810       /* Attach template arguments to type.  */
13811       if (! VEC_empty (symbolp, template_args))
13812         {
13813           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13814           TYPE_N_TEMPLATE_ARGUMENTS (type)
13815             = VEC_length (symbolp, template_args);
13816           TYPE_TEMPLATE_ARGUMENTS (type)
13817             = XOBNEWVEC (&objfile->objfile_obstack,
13818                          struct symbol *,
13819                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13820           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13821                   VEC_address (symbolp, template_args),
13822                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13823                    * sizeof (struct symbol *)));
13824           VEC_free (symbolp, template_args);
13825         }
13826
13827       /* Attach fields and member functions to the type.  */
13828       if (fi.nfields)
13829         dwarf2_attach_fields_to_type (&fi, type, cu);
13830       if (fi.nfnfields)
13831         {
13832           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13833
13834           /* Get the type which refers to the base class (possibly this
13835              class itself) which contains the vtable pointer for the current
13836              class from the DW_AT_containing_type attribute.  This use of
13837              DW_AT_containing_type is a GNU extension.  */
13838
13839           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13840             {
13841               struct type *t = die_containing_type (die, cu);
13842
13843               set_type_vptr_basetype (type, t);
13844               if (type == t)
13845                 {
13846                   int i;
13847
13848                   /* Our own class provides vtbl ptr.  */
13849                   for (i = TYPE_NFIELDS (t) - 1;
13850                        i >= TYPE_N_BASECLASSES (t);
13851                        --i)
13852                     {
13853                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13854
13855                       if (is_vtable_name (fieldname, cu))
13856                         {
13857                           set_type_vptr_fieldno (type, i);
13858                           break;
13859                         }
13860                     }
13861
13862                   /* Complain if virtual function table field not found.  */
13863                   if (i < TYPE_N_BASECLASSES (t))
13864                     complaint (&symfile_complaints,
13865                                _("virtual function table pointer "
13866                                  "not found when defining class '%s'"),
13867                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13868                                "");
13869                 }
13870               else
13871                 {
13872                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13873                 }
13874             }
13875           else if (cu->producer
13876                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13877             {
13878               /* The IBM XLC compiler does not provide direct indication
13879                  of the containing type, but the vtable pointer is
13880                  always named __vfp.  */
13881
13882               int i;
13883
13884               for (i = TYPE_NFIELDS (type) - 1;
13885                    i >= TYPE_N_BASECLASSES (type);
13886                    --i)
13887                 {
13888                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13889                     {
13890                       set_type_vptr_fieldno (type, i);
13891                       set_type_vptr_basetype (type, type);
13892                       break;
13893                     }
13894                 }
13895             }
13896         }
13897
13898       /* Copy fi.typedef_field_list linked list elements content into the
13899          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13900       if (fi.typedef_field_list)
13901         {
13902           int i = fi.typedef_field_list_count;
13903
13904           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13905           TYPE_TYPEDEF_FIELD_ARRAY (type)
13906             = ((struct typedef_field *)
13907                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13908           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13909
13910           /* Reverse the list order to keep the debug info elements order.  */
13911           while (--i >= 0)
13912             {
13913               struct typedef_field *dest, *src;
13914
13915               dest = &TYPE_TYPEDEF_FIELD (type, i);
13916               src = &fi.typedef_field_list->field;
13917               fi.typedef_field_list = fi.typedef_field_list->next;
13918               *dest = *src;
13919             }
13920         }
13921
13922       do_cleanups (back_to);
13923     }
13924
13925   quirk_gcc_member_function_pointer (type, objfile);
13926
13927   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13928      snapshots) has been known to create a die giving a declaration
13929      for a class that has, as a child, a die giving a definition for a
13930      nested class.  So we have to process our children even if the
13931      current die is a declaration.  Normally, of course, a declaration
13932      won't have any children at all.  */
13933
13934   child_die = die->child;
13935
13936   while (child_die != NULL && child_die->tag)
13937     {
13938       if (child_die->tag == DW_TAG_member
13939           || child_die->tag == DW_TAG_variable
13940           || child_die->tag == DW_TAG_inheritance
13941           || child_die->tag == DW_TAG_template_value_param
13942           || child_die->tag == DW_TAG_template_type_param)
13943         {
13944           /* Do nothing.  */
13945         }
13946       else
13947         process_die (child_die, cu);
13948
13949       child_die = sibling_die (child_die);
13950     }
13951
13952   /* Do not consider external references.  According to the DWARF standard,
13953      these DIEs are identified by the fact that they have no byte_size
13954      attribute, and a declaration attribute.  */
13955   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13956       || !die_is_declaration (die, cu))
13957     new_symbol (die, type, cu);
13958 }
13959
13960 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13961    update TYPE using some information only available in DIE's children.  */
13962
13963 static void
13964 update_enumeration_type_from_children (struct die_info *die,
13965                                        struct type *type,
13966                                        struct dwarf2_cu *cu)
13967 {
13968   struct die_info *child_die;
13969   int unsigned_enum = 1;
13970   int flag_enum = 1;
13971   ULONGEST mask = 0;
13972
13973   auto_obstack obstack;
13974
13975   for (child_die = die->child;
13976        child_die != NULL && child_die->tag;
13977        child_die = sibling_die (child_die))
13978     {
13979       struct attribute *attr;
13980       LONGEST value;
13981       const gdb_byte *bytes;
13982       struct dwarf2_locexpr_baton *baton;
13983       const char *name;
13984
13985       if (child_die->tag != DW_TAG_enumerator)
13986         continue;
13987
13988       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13989       if (attr == NULL)
13990         continue;
13991
13992       name = dwarf2_name (child_die, cu);
13993       if (name == NULL)
13994         name = "<anonymous enumerator>";
13995
13996       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13997                                &value, &bytes, &baton);
13998       if (value < 0)
13999         {
14000           unsigned_enum = 0;
14001           flag_enum = 0;
14002         }
14003       else if ((mask & value) != 0)
14004         flag_enum = 0;
14005       else
14006         mask |= value;
14007
14008       /* If we already know that the enum type is neither unsigned, nor
14009          a flag type, no need to look at the rest of the enumerates.  */
14010       if (!unsigned_enum && !flag_enum)
14011         break;
14012     }
14013
14014   if (unsigned_enum)
14015     TYPE_UNSIGNED (type) = 1;
14016   if (flag_enum)
14017     TYPE_FLAG_ENUM (type) = 1;
14018 }
14019
14020 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14021    complete the type's fields yet, or create any symbols.  */
14022
14023 static struct type *
14024 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14025 {
14026   struct objfile *objfile = cu->objfile;
14027   struct type *type;
14028   struct attribute *attr;
14029   const char *name;
14030
14031   /* If the definition of this type lives in .debug_types, read that type.
14032      Don't follow DW_AT_specification though, that will take us back up
14033      the chain and we want to go down.  */
14034   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14035   if (attr)
14036     {
14037       type = get_DW_AT_signature_type (die, attr, cu);
14038
14039       /* The type's CU may not be the same as CU.
14040          Ensure TYPE is recorded with CU in die_type_hash.  */
14041       return set_die_type (die, type, cu);
14042     }
14043
14044   type = alloc_type (objfile);
14045
14046   TYPE_CODE (type) = TYPE_CODE_ENUM;
14047   name = dwarf2_full_name (NULL, die, cu);
14048   if (name != NULL)
14049     TYPE_TAG_NAME (type) = name;
14050
14051   attr = dwarf2_attr (die, DW_AT_type, cu);
14052   if (attr != NULL)
14053     {
14054       struct type *underlying_type = die_type (die, cu);
14055
14056       TYPE_TARGET_TYPE (type) = underlying_type;
14057     }
14058
14059   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14060   if (attr)
14061     {
14062       TYPE_LENGTH (type) = DW_UNSND (attr);
14063     }
14064   else
14065     {
14066       TYPE_LENGTH (type) = 0;
14067     }
14068
14069   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14070      declared as private in the package spec, and then defined only
14071      inside the package body.  Such types are known as Taft Amendment
14072      Types.  When another package uses such a type, an incomplete DIE
14073      may be generated by the compiler.  */
14074   if (die_is_declaration (die, cu))
14075     TYPE_STUB (type) = 1;
14076
14077   /* Finish the creation of this type by using the enum's children.
14078      We must call this even when the underlying type has been provided
14079      so that we can determine if we're looking at a "flag" enum.  */
14080   update_enumeration_type_from_children (die, type, cu);
14081
14082   /* If this type has an underlying type that is not a stub, then we
14083      may use its attributes.  We always use the "unsigned" attribute
14084      in this situation, because ordinarily we guess whether the type
14085      is unsigned -- but the guess can be wrong and the underlying type
14086      can tell us the reality.  However, we defer to a local size
14087      attribute if one exists, because this lets the compiler override
14088      the underlying type if needed.  */
14089   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14090     {
14091       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14092       if (TYPE_LENGTH (type) == 0)
14093         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14094     }
14095
14096   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14097
14098   return set_die_type (die, type, cu);
14099 }
14100
14101 /* Given a pointer to a die which begins an enumeration, process all
14102    the dies that define the members of the enumeration, and create the
14103    symbol for the enumeration type.
14104
14105    NOTE: We reverse the order of the element list.  */
14106
14107 static void
14108 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14109 {
14110   struct type *this_type;
14111
14112   this_type = get_die_type (die, cu);
14113   if (this_type == NULL)
14114     this_type = read_enumeration_type (die, cu);
14115
14116   if (die->child != NULL)
14117     {
14118       struct die_info *child_die;
14119       struct symbol *sym;
14120       struct field *fields = NULL;
14121       int num_fields = 0;
14122       const char *name;
14123
14124       child_die = die->child;
14125       while (child_die && child_die->tag)
14126         {
14127           if (child_die->tag != DW_TAG_enumerator)
14128             {
14129               process_die (child_die, cu);
14130             }
14131           else
14132             {
14133               name = dwarf2_name (child_die, cu);
14134               if (name)
14135                 {
14136                   sym = new_symbol (child_die, this_type, cu);
14137
14138                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14139                     {
14140                       fields = (struct field *)
14141                         xrealloc (fields,
14142                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14143                                   * sizeof (struct field));
14144                     }
14145
14146                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14147                   FIELD_TYPE (fields[num_fields]) = NULL;
14148                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14149                   FIELD_BITSIZE (fields[num_fields]) = 0;
14150
14151                   num_fields++;
14152                 }
14153             }
14154
14155           child_die = sibling_die (child_die);
14156         }
14157
14158       if (num_fields)
14159         {
14160           TYPE_NFIELDS (this_type) = num_fields;
14161           TYPE_FIELDS (this_type) = (struct field *)
14162             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14163           memcpy (TYPE_FIELDS (this_type), fields,
14164                   sizeof (struct field) * num_fields);
14165           xfree (fields);
14166         }
14167     }
14168
14169   /* If we are reading an enum from a .debug_types unit, and the enum
14170      is a declaration, and the enum is not the signatured type in the
14171      unit, then we do not want to add a symbol for it.  Adding a
14172      symbol would in some cases obscure the true definition of the
14173      enum, giving users an incomplete type when the definition is
14174      actually available.  Note that we do not want to do this for all
14175      enums which are just declarations, because C++0x allows forward
14176      enum declarations.  */
14177   if (cu->per_cu->is_debug_types
14178       && die_is_declaration (die, cu))
14179     {
14180       struct signatured_type *sig_type;
14181
14182       sig_type = (struct signatured_type *) cu->per_cu;
14183       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14184       if (sig_type->type_offset_in_section != die->sect_off)
14185         return;
14186     }
14187
14188   new_symbol (die, this_type, cu);
14189 }
14190
14191 /* Extract all information from a DW_TAG_array_type DIE and put it in
14192    the DIE's type field.  For now, this only handles one dimensional
14193    arrays.  */
14194
14195 static struct type *
14196 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14197 {
14198   struct objfile *objfile = cu->objfile;
14199   struct die_info *child_die;
14200   struct type *type;
14201   struct type *element_type, *range_type, *index_type;
14202   struct type **range_types = NULL;
14203   struct attribute *attr;
14204   int ndim = 0;
14205   struct cleanup *back_to;
14206   const char *name;
14207   unsigned int bit_stride = 0;
14208
14209   element_type = die_type (die, cu);
14210
14211   /* The die_type call above may have already set the type for this DIE.  */
14212   type = get_die_type (die, cu);
14213   if (type)
14214     return type;
14215
14216   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14217   if (attr != NULL)
14218     bit_stride = DW_UNSND (attr) * 8;
14219
14220   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14221   if (attr != NULL)
14222     bit_stride = DW_UNSND (attr);
14223
14224   /* Irix 6.2 native cc creates array types without children for
14225      arrays with unspecified length.  */
14226   if (die->child == NULL)
14227     {
14228       index_type = objfile_type (objfile)->builtin_int;
14229       range_type = create_static_range_type (NULL, index_type, 0, -1);
14230       type = create_array_type_with_stride (NULL, element_type, range_type,
14231                                             bit_stride);
14232       return set_die_type (die, type, cu);
14233     }
14234
14235   back_to = make_cleanup (null_cleanup, NULL);
14236   child_die = die->child;
14237   while (child_die && child_die->tag)
14238     {
14239       if (child_die->tag == DW_TAG_subrange_type)
14240         {
14241           struct type *child_type = read_type_die (child_die, cu);
14242
14243           if (child_type != NULL)
14244             {
14245               /* The range type was succesfully read.  Save it for the
14246                  array type creation.  */
14247               if ((ndim % DW_FIELD_ALLOC_CHUNK) == 0)
14248                 {
14249                   range_types = (struct type **)
14250                     xrealloc (range_types, (ndim + DW_FIELD_ALLOC_CHUNK)
14251                               * sizeof (struct type *));
14252                   if (ndim == 0)
14253                     make_cleanup (free_current_contents, &range_types);
14254                 }
14255               range_types[ndim++] = child_type;
14256             }
14257         }
14258       child_die = sibling_die (child_die);
14259     }
14260
14261   /* Dwarf2 dimensions are output from left to right, create the
14262      necessary array types in backwards order.  */
14263
14264   type = element_type;
14265
14266   if (read_array_order (die, cu) == DW_ORD_col_major)
14267     {
14268       int i = 0;
14269
14270       while (i < ndim)
14271         type = create_array_type_with_stride (NULL, type, range_types[i++],
14272                                               bit_stride);
14273     }
14274   else
14275     {
14276       while (ndim-- > 0)
14277         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14278                                               bit_stride);
14279     }
14280
14281   /* Understand Dwarf2 support for vector types (like they occur on
14282      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14283      array type.  This is not part of the Dwarf2/3 standard yet, but a
14284      custom vendor extension.  The main difference between a regular
14285      array and the vector variant is that vectors are passed by value
14286      to functions.  */
14287   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14288   if (attr)
14289     make_vector_type (type);
14290
14291   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14292      implementation may choose to implement triple vectors using this
14293      attribute.  */
14294   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14295   if (attr)
14296     {
14297       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14298         TYPE_LENGTH (type) = DW_UNSND (attr);
14299       else
14300         complaint (&symfile_complaints,
14301                    _("DW_AT_byte_size for array type smaller "
14302                      "than the total size of elements"));
14303     }
14304
14305   name = dwarf2_name (die, cu);
14306   if (name)
14307     TYPE_NAME (type) = name;
14308
14309   /* Install the type in the die.  */
14310   set_die_type (die, type, cu);
14311
14312   /* set_die_type should be already done.  */
14313   set_descriptive_type (type, die, cu);
14314
14315   do_cleanups (back_to);
14316
14317   return type;
14318 }
14319
14320 static enum dwarf_array_dim_ordering
14321 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14322 {
14323   struct attribute *attr;
14324
14325   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14326
14327   if (attr)
14328     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14329
14330   /* GNU F77 is a special case, as at 08/2004 array type info is the
14331      opposite order to the dwarf2 specification, but data is still
14332      laid out as per normal fortran.
14333
14334      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14335      version checking.  */
14336
14337   if (cu->language == language_fortran
14338       && cu->producer && strstr (cu->producer, "GNU F77"))
14339     {
14340       return DW_ORD_row_major;
14341     }
14342
14343   switch (cu->language_defn->la_array_ordering)
14344     {
14345     case array_column_major:
14346       return DW_ORD_col_major;
14347     case array_row_major:
14348     default:
14349       return DW_ORD_row_major;
14350     };
14351 }
14352
14353 /* Extract all information from a DW_TAG_set_type DIE and put it in
14354    the DIE's type field.  */
14355
14356 static struct type *
14357 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14358 {
14359   struct type *domain_type, *set_type;
14360   struct attribute *attr;
14361
14362   domain_type = die_type (die, cu);
14363
14364   /* The die_type call above may have already set the type for this DIE.  */
14365   set_type = get_die_type (die, cu);
14366   if (set_type)
14367     return set_type;
14368
14369   set_type = create_set_type (NULL, domain_type);
14370
14371   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14372   if (attr)
14373     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14374
14375   return set_die_type (die, set_type, cu);
14376 }
14377
14378 /* A helper for read_common_block that creates a locexpr baton.
14379    SYM is the symbol which we are marking as computed.
14380    COMMON_DIE is the DIE for the common block.
14381    COMMON_LOC is the location expression attribute for the common
14382    block itself.
14383    MEMBER_LOC is the location expression attribute for the particular
14384    member of the common block that we are processing.
14385    CU is the CU from which the above come.  */
14386
14387 static void
14388 mark_common_block_symbol_computed (struct symbol *sym,
14389                                    struct die_info *common_die,
14390                                    struct attribute *common_loc,
14391                                    struct attribute *member_loc,
14392                                    struct dwarf2_cu *cu)
14393 {
14394   struct objfile *objfile = dwarf2_per_objfile->objfile;
14395   struct dwarf2_locexpr_baton *baton;
14396   gdb_byte *ptr;
14397   unsigned int cu_off;
14398   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14399   LONGEST offset = 0;
14400
14401   gdb_assert (common_loc && member_loc);
14402   gdb_assert (attr_form_is_block (common_loc));
14403   gdb_assert (attr_form_is_block (member_loc)
14404               || attr_form_is_constant (member_loc));
14405
14406   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14407   baton->per_cu = cu->per_cu;
14408   gdb_assert (baton->per_cu);
14409
14410   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14411
14412   if (attr_form_is_constant (member_loc))
14413     {
14414       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14415       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14416     }
14417   else
14418     baton->size += DW_BLOCK (member_loc)->size;
14419
14420   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14421   baton->data = ptr;
14422
14423   *ptr++ = DW_OP_call4;
14424   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14425   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14426   ptr += 4;
14427
14428   if (attr_form_is_constant (member_loc))
14429     {
14430       *ptr++ = DW_OP_addr;
14431       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14432       ptr += cu->header.addr_size;
14433     }
14434   else
14435     {
14436       /* We have to copy the data here, because DW_OP_call4 will only
14437          use a DW_AT_location attribute.  */
14438       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14439       ptr += DW_BLOCK (member_loc)->size;
14440     }
14441
14442   *ptr++ = DW_OP_plus;
14443   gdb_assert (ptr - baton->data == baton->size);
14444
14445   SYMBOL_LOCATION_BATON (sym) = baton;
14446   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14447 }
14448
14449 /* Create appropriate locally-scoped variables for all the
14450    DW_TAG_common_block entries.  Also create a struct common_block
14451    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14452    is used to sepate the common blocks name namespace from regular
14453    variable names.  */
14454
14455 static void
14456 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14457 {
14458   struct attribute *attr;
14459
14460   attr = dwarf2_attr (die, DW_AT_location, cu);
14461   if (attr)
14462     {
14463       /* Support the .debug_loc offsets.  */
14464       if (attr_form_is_block (attr))
14465         {
14466           /* Ok.  */
14467         }
14468       else if (attr_form_is_section_offset (attr))
14469         {
14470           dwarf2_complex_location_expr_complaint ();
14471           attr = NULL;
14472         }
14473       else
14474         {
14475           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14476                                                  "common block member");
14477           attr = NULL;
14478         }
14479     }
14480
14481   if (die->child != NULL)
14482     {
14483       struct objfile *objfile = cu->objfile;
14484       struct die_info *child_die;
14485       size_t n_entries = 0, size;
14486       struct common_block *common_block;
14487       struct symbol *sym;
14488
14489       for (child_die = die->child;
14490            child_die && child_die->tag;
14491            child_die = sibling_die (child_die))
14492         ++n_entries;
14493
14494       size = (sizeof (struct common_block)
14495               + (n_entries - 1) * sizeof (struct symbol *));
14496       common_block
14497         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14498                                                  size);
14499       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14500       common_block->n_entries = 0;
14501
14502       for (child_die = die->child;
14503            child_die && child_die->tag;
14504            child_die = sibling_die (child_die))
14505         {
14506           /* Create the symbol in the DW_TAG_common_block block in the current
14507              symbol scope.  */
14508           sym = new_symbol (child_die, NULL, cu);
14509           if (sym != NULL)
14510             {
14511               struct attribute *member_loc;
14512
14513               common_block->contents[common_block->n_entries++] = sym;
14514
14515               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14516                                         cu);
14517               if (member_loc)
14518                 {
14519                   /* GDB has handled this for a long time, but it is
14520                      not specified by DWARF.  It seems to have been
14521                      emitted by gfortran at least as recently as:
14522                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14523                   complaint (&symfile_complaints,
14524                              _("Variable in common block has "
14525                                "DW_AT_data_member_location "
14526                                "- DIE at 0x%x [in module %s]"),
14527                              to_underlying (child_die->sect_off),
14528                              objfile_name (cu->objfile));
14529
14530                   if (attr_form_is_section_offset (member_loc))
14531                     dwarf2_complex_location_expr_complaint ();
14532                   else if (attr_form_is_constant (member_loc)
14533                            || attr_form_is_block (member_loc))
14534                     {
14535                       if (attr)
14536                         mark_common_block_symbol_computed (sym, die, attr,
14537                                                            member_loc, cu);
14538                     }
14539                   else
14540                     dwarf2_complex_location_expr_complaint ();
14541                 }
14542             }
14543         }
14544
14545       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14546       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14547     }
14548 }
14549
14550 /* Create a type for a C++ namespace.  */
14551
14552 static struct type *
14553 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14554 {
14555   struct objfile *objfile = cu->objfile;
14556   const char *previous_prefix, *name;
14557   int is_anonymous;
14558   struct type *type;
14559
14560   /* For extensions, reuse the type of the original namespace.  */
14561   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14562     {
14563       struct die_info *ext_die;
14564       struct dwarf2_cu *ext_cu = cu;
14565
14566       ext_die = dwarf2_extension (die, &ext_cu);
14567       type = read_type_die (ext_die, ext_cu);
14568
14569       /* EXT_CU may not be the same as CU.
14570          Ensure TYPE is recorded with CU in die_type_hash.  */
14571       return set_die_type (die, type, cu);
14572     }
14573
14574   name = namespace_name (die, &is_anonymous, cu);
14575
14576   /* Now build the name of the current namespace.  */
14577
14578   previous_prefix = determine_prefix (die, cu);
14579   if (previous_prefix[0] != '\0')
14580     name = typename_concat (&objfile->objfile_obstack,
14581                             previous_prefix, name, 0, cu);
14582
14583   /* Create the type.  */
14584   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14585   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14586
14587   return set_die_type (die, type, cu);
14588 }
14589
14590 /* Read a namespace scope.  */
14591
14592 static void
14593 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14594 {
14595   struct objfile *objfile = cu->objfile;
14596   int is_anonymous;
14597
14598   /* Add a symbol associated to this if we haven't seen the namespace
14599      before.  Also, add a using directive if it's an anonymous
14600      namespace.  */
14601
14602   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14603     {
14604       struct type *type;
14605
14606       type = read_type_die (die, cu);
14607       new_symbol (die, type, cu);
14608
14609       namespace_name (die, &is_anonymous, cu);
14610       if (is_anonymous)
14611         {
14612           const char *previous_prefix = determine_prefix (die, cu);
14613
14614           std::vector<const char *> excludes;
14615           add_using_directive (using_directives (cu->language),
14616                                previous_prefix, TYPE_NAME (type), NULL,
14617                                NULL, excludes, 0, &objfile->objfile_obstack);
14618         }
14619     }
14620
14621   if (die->child != NULL)
14622     {
14623       struct die_info *child_die = die->child;
14624
14625       while (child_die && child_die->tag)
14626         {
14627           process_die (child_die, cu);
14628           child_die = sibling_die (child_die);
14629         }
14630     }
14631 }
14632
14633 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14634    imported module.  Still we need that type as local Fortran "use ... only"
14635    declaration imports depend on the created type in determine_prefix.  */
14636
14637 static struct type *
14638 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14639 {
14640   struct objfile *objfile = cu->objfile;
14641   const char *module_name;
14642   struct type *type;
14643
14644   module_name = dwarf2_name (die, cu);
14645   if (!module_name)
14646     complaint (&symfile_complaints,
14647                _("DW_TAG_module has no name, offset 0x%x"),
14648                to_underlying (die->sect_off));
14649   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14650
14651   /* determine_prefix uses TYPE_TAG_NAME.  */
14652   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14653
14654   return set_die_type (die, type, cu);
14655 }
14656
14657 /* Read a Fortran module.  */
14658
14659 static void
14660 read_module (struct die_info *die, struct dwarf2_cu *cu)
14661 {
14662   struct die_info *child_die = die->child;
14663   struct type *type;
14664
14665   type = read_type_die (die, cu);
14666   new_symbol (die, type, cu);
14667
14668   while (child_die && child_die->tag)
14669     {
14670       process_die (child_die, cu);
14671       child_die = sibling_die (child_die);
14672     }
14673 }
14674
14675 /* Return the name of the namespace represented by DIE.  Set
14676    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14677    namespace.  */
14678
14679 static const char *
14680 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14681 {
14682   struct die_info *current_die;
14683   const char *name = NULL;
14684
14685   /* Loop through the extensions until we find a name.  */
14686
14687   for (current_die = die;
14688        current_die != NULL;
14689        current_die = dwarf2_extension (die, &cu))
14690     {
14691       /* We don't use dwarf2_name here so that we can detect the absence
14692          of a name -> anonymous namespace.  */
14693       name = dwarf2_string_attr (die, DW_AT_name, cu);
14694
14695       if (name != NULL)
14696         break;
14697     }
14698
14699   /* Is it an anonymous namespace?  */
14700
14701   *is_anonymous = (name == NULL);
14702   if (*is_anonymous)
14703     name = CP_ANONYMOUS_NAMESPACE_STR;
14704
14705   return name;
14706 }
14707
14708 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14709    the user defined type vector.  */
14710
14711 static struct type *
14712 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14713 {
14714   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14715   struct comp_unit_head *cu_header = &cu->header;
14716   struct type *type;
14717   struct attribute *attr_byte_size;
14718   struct attribute *attr_address_class;
14719   int byte_size, addr_class;
14720   struct type *target_type;
14721
14722   target_type = die_type (die, cu);
14723
14724   /* The die_type call above may have already set the type for this DIE.  */
14725   type = get_die_type (die, cu);
14726   if (type)
14727     return type;
14728
14729   type = lookup_pointer_type (target_type);
14730
14731   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14732   if (attr_byte_size)
14733     byte_size = DW_UNSND (attr_byte_size);
14734   else
14735     byte_size = cu_header->addr_size;
14736
14737   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14738   if (attr_address_class)
14739     addr_class = DW_UNSND (attr_address_class);
14740   else
14741     addr_class = DW_ADDR_none;
14742
14743   /* If the pointer size or address class is different than the
14744      default, create a type variant marked as such and set the
14745      length accordingly.  */
14746   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14747     {
14748       if (gdbarch_address_class_type_flags_p (gdbarch))
14749         {
14750           int type_flags;
14751
14752           type_flags = gdbarch_address_class_type_flags
14753                          (gdbarch, byte_size, addr_class);
14754           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14755                       == 0);
14756           type = make_type_with_address_space (type, type_flags);
14757         }
14758       else if (TYPE_LENGTH (type) != byte_size)
14759         {
14760           complaint (&symfile_complaints,
14761                      _("invalid pointer size %d"), byte_size);
14762         }
14763       else
14764         {
14765           /* Should we also complain about unhandled address classes?  */
14766         }
14767     }
14768
14769   TYPE_LENGTH (type) = byte_size;
14770   return set_die_type (die, type, cu);
14771 }
14772
14773 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14774    the user defined type vector.  */
14775
14776 static struct type *
14777 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14778 {
14779   struct type *type;
14780   struct type *to_type;
14781   struct type *domain;
14782
14783   to_type = die_type (die, cu);
14784   domain = die_containing_type (die, cu);
14785
14786   /* The calls above may have already set the type for this DIE.  */
14787   type = get_die_type (die, cu);
14788   if (type)
14789     return type;
14790
14791   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14792     type = lookup_methodptr_type (to_type);
14793   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14794     {
14795       struct type *new_type = alloc_type (cu->objfile);
14796
14797       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14798                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14799                             TYPE_VARARGS (to_type));
14800       type = lookup_methodptr_type (new_type);
14801     }
14802   else
14803     type = lookup_memberptr_type (to_type, domain);
14804
14805   return set_die_type (die, type, cu);
14806 }
14807
14808 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14809    the user defined type vector.  */
14810
14811 static struct type *
14812 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14813                           enum type_code refcode)
14814 {
14815   struct comp_unit_head *cu_header = &cu->header;
14816   struct type *type, *target_type;
14817   struct attribute *attr;
14818
14819   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14820
14821   target_type = die_type (die, cu);
14822
14823   /* The die_type call above may have already set the type for this DIE.  */
14824   type = get_die_type (die, cu);
14825   if (type)
14826     return type;
14827
14828   type = lookup_reference_type (target_type, refcode);
14829   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14830   if (attr)
14831     {
14832       TYPE_LENGTH (type) = DW_UNSND (attr);
14833     }
14834   else
14835     {
14836       TYPE_LENGTH (type) = cu_header->addr_size;
14837     }
14838   return set_die_type (die, type, cu);
14839 }
14840
14841 /* Add the given cv-qualifiers to the element type of the array.  GCC
14842    outputs DWARF type qualifiers that apply to an array, not the
14843    element type.  But GDB relies on the array element type to carry
14844    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14845    specification.  */
14846
14847 static struct type *
14848 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14849                    struct type *base_type, int cnst, int voltl)
14850 {
14851   struct type *el_type, *inner_array;
14852
14853   base_type = copy_type (base_type);
14854   inner_array = base_type;
14855
14856   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14857     {
14858       TYPE_TARGET_TYPE (inner_array) =
14859         copy_type (TYPE_TARGET_TYPE (inner_array));
14860       inner_array = TYPE_TARGET_TYPE (inner_array);
14861     }
14862
14863   el_type = TYPE_TARGET_TYPE (inner_array);
14864   cnst |= TYPE_CONST (el_type);
14865   voltl |= TYPE_VOLATILE (el_type);
14866   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14867
14868   return set_die_type (die, base_type, cu);
14869 }
14870
14871 static struct type *
14872 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14873 {
14874   struct type *base_type, *cv_type;
14875
14876   base_type = die_type (die, cu);
14877
14878   /* The die_type call above may have already set the type for this DIE.  */
14879   cv_type = get_die_type (die, cu);
14880   if (cv_type)
14881     return cv_type;
14882
14883   /* In case the const qualifier is applied to an array type, the element type
14884      is so qualified, not the array type (section 6.7.3 of C99).  */
14885   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14886     return add_array_cv_type (die, cu, base_type, 1, 0);
14887
14888   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14889   return set_die_type (die, cv_type, cu);
14890 }
14891
14892 static struct type *
14893 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14894 {
14895   struct type *base_type, *cv_type;
14896
14897   base_type = die_type (die, cu);
14898
14899   /* The die_type call above may have already set the type for this DIE.  */
14900   cv_type = get_die_type (die, cu);
14901   if (cv_type)
14902     return cv_type;
14903
14904   /* In case the volatile qualifier is applied to an array type, the
14905      element type is so qualified, not the array type (section 6.7.3
14906      of C99).  */
14907   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14908     return add_array_cv_type (die, cu, base_type, 0, 1);
14909
14910   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14911   return set_die_type (die, cv_type, cu);
14912 }
14913
14914 /* Handle DW_TAG_restrict_type.  */
14915
14916 static struct type *
14917 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14918 {
14919   struct type *base_type, *cv_type;
14920
14921   base_type = die_type (die, cu);
14922
14923   /* The die_type call above may have already set the type for this DIE.  */
14924   cv_type = get_die_type (die, cu);
14925   if (cv_type)
14926     return cv_type;
14927
14928   cv_type = make_restrict_type (base_type);
14929   return set_die_type (die, cv_type, cu);
14930 }
14931
14932 /* Handle DW_TAG_atomic_type.  */
14933
14934 static struct type *
14935 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14936 {
14937   struct type *base_type, *cv_type;
14938
14939   base_type = die_type (die, cu);
14940
14941   /* The die_type call above may have already set the type for this DIE.  */
14942   cv_type = get_die_type (die, cu);
14943   if (cv_type)
14944     return cv_type;
14945
14946   cv_type = make_atomic_type (base_type);
14947   return set_die_type (die, cv_type, cu);
14948 }
14949
14950 /* Extract all information from a DW_TAG_string_type DIE and add to
14951    the user defined type vector.  It isn't really a user defined type,
14952    but it behaves like one, with other DIE's using an AT_user_def_type
14953    attribute to reference it.  */
14954
14955 static struct type *
14956 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14957 {
14958   struct objfile *objfile = cu->objfile;
14959   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14960   struct type *type, *range_type, *index_type, *char_type;
14961   struct attribute *attr;
14962   unsigned int length;
14963
14964   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14965   if (attr)
14966     {
14967       length = DW_UNSND (attr);
14968     }
14969   else
14970     {
14971       /* Check for the DW_AT_byte_size attribute.  */
14972       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14973       if (attr)
14974         {
14975           length = DW_UNSND (attr);
14976         }
14977       else
14978         {
14979           length = 1;
14980         }
14981     }
14982
14983   index_type = objfile_type (objfile)->builtin_int;
14984   range_type = create_static_range_type (NULL, index_type, 1, length);
14985   char_type = language_string_char_type (cu->language_defn, gdbarch);
14986   type = create_string_type (NULL, char_type, range_type);
14987
14988   return set_die_type (die, type, cu);
14989 }
14990
14991 /* Assuming that DIE corresponds to a function, returns nonzero
14992    if the function is prototyped.  */
14993
14994 static int
14995 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14996 {
14997   struct attribute *attr;
14998
14999   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15000   if (attr && (DW_UNSND (attr) != 0))
15001     return 1;
15002
15003   /* The DWARF standard implies that the DW_AT_prototyped attribute
15004      is only meaninful for C, but the concept also extends to other
15005      languages that allow unprototyped functions (Eg: Objective C).
15006      For all other languages, assume that functions are always
15007      prototyped.  */
15008   if (cu->language != language_c
15009       && cu->language != language_objc
15010       && cu->language != language_opencl)
15011     return 1;
15012
15013   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15014      prototyped and unprototyped functions; default to prototyped,
15015      since that is more common in modern code (and RealView warns
15016      about unprototyped functions).  */
15017   if (producer_is_realview (cu->producer))
15018     return 1;
15019
15020   return 0;
15021 }
15022
15023 /* Handle DIES due to C code like:
15024
15025    struct foo
15026    {
15027    int (*funcp)(int a, long l);
15028    int b;
15029    };
15030
15031    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15032
15033 static struct type *
15034 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15035 {
15036   struct objfile *objfile = cu->objfile;
15037   struct type *type;            /* Type that this function returns.  */
15038   struct type *ftype;           /* Function that returns above type.  */
15039   struct attribute *attr;
15040
15041   type = die_type (die, cu);
15042
15043   /* The die_type call above may have already set the type for this DIE.  */
15044   ftype = get_die_type (die, cu);
15045   if (ftype)
15046     return ftype;
15047
15048   ftype = lookup_function_type (type);
15049
15050   if (prototyped_function_p (die, cu))
15051     TYPE_PROTOTYPED (ftype) = 1;
15052
15053   /* Store the calling convention in the type if it's available in
15054      the subroutine die.  Otherwise set the calling convention to
15055      the default value DW_CC_normal.  */
15056   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15057   if (attr)
15058     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15059   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15060     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15061   else
15062     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15063
15064   /* Record whether the function returns normally to its caller or not
15065      if the DWARF producer set that information.  */
15066   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15067   if (attr && (DW_UNSND (attr) != 0))
15068     TYPE_NO_RETURN (ftype) = 1;
15069
15070   /* We need to add the subroutine type to the die immediately so
15071      we don't infinitely recurse when dealing with parameters
15072      declared as the same subroutine type.  */
15073   set_die_type (die, ftype, cu);
15074
15075   if (die->child != NULL)
15076     {
15077       struct type *void_type = objfile_type (objfile)->builtin_void;
15078       struct die_info *child_die;
15079       int nparams, iparams;
15080
15081       /* Count the number of parameters.
15082          FIXME: GDB currently ignores vararg functions, but knows about
15083          vararg member functions.  */
15084       nparams = 0;
15085       child_die = die->child;
15086       while (child_die && child_die->tag)
15087         {
15088           if (child_die->tag == DW_TAG_formal_parameter)
15089             nparams++;
15090           else if (child_die->tag == DW_TAG_unspecified_parameters)
15091             TYPE_VARARGS (ftype) = 1;
15092           child_die = sibling_die (child_die);
15093         }
15094
15095       /* Allocate storage for parameters and fill them in.  */
15096       TYPE_NFIELDS (ftype) = nparams;
15097       TYPE_FIELDS (ftype) = (struct field *)
15098         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15099
15100       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15101          even if we error out during the parameters reading below.  */
15102       for (iparams = 0; iparams < nparams; iparams++)
15103         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15104
15105       iparams = 0;
15106       child_die = die->child;
15107       while (child_die && child_die->tag)
15108         {
15109           if (child_die->tag == DW_TAG_formal_parameter)
15110             {
15111               struct type *arg_type;
15112
15113               /* DWARF version 2 has no clean way to discern C++
15114                  static and non-static member functions.  G++ helps
15115                  GDB by marking the first parameter for non-static
15116                  member functions (which is the this pointer) as
15117                  artificial.  We pass this information to
15118                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15119
15120                  DWARF version 3 added DW_AT_object_pointer, which GCC
15121                  4.5 does not yet generate.  */
15122               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15123               if (attr)
15124                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15125               else
15126                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15127               arg_type = die_type (child_die, cu);
15128
15129               /* RealView does not mark THIS as const, which the testsuite
15130                  expects.  GCC marks THIS as const in method definitions,
15131                  but not in the class specifications (GCC PR 43053).  */
15132               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15133                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15134                 {
15135                   int is_this = 0;
15136                   struct dwarf2_cu *arg_cu = cu;
15137                   const char *name = dwarf2_name (child_die, cu);
15138
15139                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15140                   if (attr)
15141                     {
15142                       /* If the compiler emits this, use it.  */
15143                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15144                         is_this = 1;
15145                     }
15146                   else if (name && strcmp (name, "this") == 0)
15147                     /* Function definitions will have the argument names.  */
15148                     is_this = 1;
15149                   else if (name == NULL && iparams == 0)
15150                     /* Declarations may not have the names, so like
15151                        elsewhere in GDB, assume an artificial first
15152                        argument is "this".  */
15153                     is_this = 1;
15154
15155                   if (is_this)
15156                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15157                                              arg_type, 0);
15158                 }
15159
15160               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15161               iparams++;
15162             }
15163           child_die = sibling_die (child_die);
15164         }
15165     }
15166
15167   return ftype;
15168 }
15169
15170 static struct type *
15171 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15172 {
15173   struct objfile *objfile = cu->objfile;
15174   const char *name = NULL;
15175   struct type *this_type, *target_type;
15176
15177   name = dwarf2_full_name (NULL, die, cu);
15178   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15179   TYPE_TARGET_STUB (this_type) = 1;
15180   set_die_type (die, this_type, cu);
15181   target_type = die_type (die, cu);
15182   if (target_type != this_type)
15183     TYPE_TARGET_TYPE (this_type) = target_type;
15184   else
15185     {
15186       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15187          spec and cause infinite loops in GDB.  */
15188       complaint (&symfile_complaints,
15189                  _("Self-referential DW_TAG_typedef "
15190                    "- DIE at 0x%x [in module %s]"),
15191                  to_underlying (die->sect_off), objfile_name (objfile));
15192       TYPE_TARGET_TYPE (this_type) = NULL;
15193     }
15194   return this_type;
15195 }
15196
15197 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15198    (which may be different from NAME) to the architecture back-end to allow
15199    it to guess the correct format if necessary.  */
15200
15201 static struct type *
15202 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15203                         const char *name_hint)
15204 {
15205   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15206   const struct floatformat **format;
15207   struct type *type;
15208
15209   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15210   if (format)
15211     type = init_float_type (objfile, bits, name, format);
15212   else
15213     type = init_type (objfile, TYPE_CODE_ERROR, bits / TARGET_CHAR_BIT, name);
15214
15215   return type;
15216 }
15217
15218 /* Find a representation of a given base type and install
15219    it in the TYPE field of the die.  */
15220
15221 static struct type *
15222 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15223 {
15224   struct objfile *objfile = cu->objfile;
15225   struct type *type;
15226   struct attribute *attr;
15227   int encoding = 0, bits = 0;
15228   const char *name;
15229
15230   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15231   if (attr)
15232     {
15233       encoding = DW_UNSND (attr);
15234     }
15235   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15236   if (attr)
15237     {
15238       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15239     }
15240   name = dwarf2_name (die, cu);
15241   if (!name)
15242     {
15243       complaint (&symfile_complaints,
15244                  _("DW_AT_name missing from DW_TAG_base_type"));
15245     }
15246
15247   switch (encoding)
15248     {
15249       case DW_ATE_address:
15250         /* Turn DW_ATE_address into a void * pointer.  */
15251         type = init_type (objfile, TYPE_CODE_VOID, 1, NULL);
15252         type = init_pointer_type (objfile, bits, name, type);
15253         break;
15254       case DW_ATE_boolean:
15255         type = init_boolean_type (objfile, bits, 1, name);
15256         break;
15257       case DW_ATE_complex_float:
15258         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15259         type = init_complex_type (objfile, name, type);
15260         break;
15261       case DW_ATE_decimal_float:
15262         type = init_decfloat_type (objfile, bits, name);
15263         break;
15264       case DW_ATE_float:
15265         type = dwarf2_init_float_type (objfile, bits, name, name);
15266         break;
15267       case DW_ATE_signed:
15268         type = init_integer_type (objfile, bits, 0, name);
15269         break;
15270       case DW_ATE_unsigned:
15271         if (cu->language == language_fortran
15272             && name
15273             && startswith (name, "character("))
15274           type = init_character_type (objfile, bits, 1, name);
15275         else
15276           type = init_integer_type (objfile, bits, 1, name);
15277         break;
15278       case DW_ATE_signed_char:
15279         if (cu->language == language_ada || cu->language == language_m2
15280             || cu->language == language_pascal
15281             || cu->language == language_fortran)
15282           type = init_character_type (objfile, bits, 0, name);
15283         else
15284           type = init_integer_type (objfile, bits, 0, name);
15285         break;
15286       case DW_ATE_unsigned_char:
15287         if (cu->language == language_ada || cu->language == language_m2
15288             || cu->language == language_pascal
15289             || cu->language == language_fortran
15290             || cu->language == language_rust)
15291           type = init_character_type (objfile, bits, 1, name);
15292         else
15293           type = init_integer_type (objfile, bits, 1, name);
15294         break;
15295       case DW_ATE_UTF:
15296         {
15297           gdbarch *arch = get_objfile_arch (objfile);
15298
15299           if (bits == 16)
15300             type = builtin_type (arch)->builtin_char16;
15301           else if (bits == 32)
15302             type = builtin_type (arch)->builtin_char32;
15303           else
15304             {
15305               complaint (&symfile_complaints,
15306                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15307                          bits);
15308               type = init_integer_type (objfile, bits, 1, name);
15309             }
15310           return set_die_type (die, type, cu);
15311         }
15312         break;
15313
15314       default:
15315         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15316                    dwarf_type_encoding_name (encoding));
15317         type = init_type (objfile, TYPE_CODE_ERROR,
15318                           bits / TARGET_CHAR_BIT, name);
15319         break;
15320     }
15321
15322   if (name && strcmp (name, "char") == 0)
15323     TYPE_NOSIGN (type) = 1;
15324
15325   return set_die_type (die, type, cu);
15326 }
15327
15328 /* Parse dwarf attribute if it's a block, reference or constant and put the
15329    resulting value of the attribute into struct bound_prop.
15330    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15331
15332 static int
15333 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15334                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15335 {
15336   struct dwarf2_property_baton *baton;
15337   struct obstack *obstack = &cu->objfile->objfile_obstack;
15338
15339   if (attr == NULL || prop == NULL)
15340     return 0;
15341
15342   if (attr_form_is_block (attr))
15343     {
15344       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15345       baton->referenced_type = NULL;
15346       baton->locexpr.per_cu = cu->per_cu;
15347       baton->locexpr.size = DW_BLOCK (attr)->size;
15348       baton->locexpr.data = DW_BLOCK (attr)->data;
15349       prop->data.baton = baton;
15350       prop->kind = PROP_LOCEXPR;
15351       gdb_assert (prop->data.baton != NULL);
15352     }
15353   else if (attr_form_is_ref (attr))
15354     {
15355       struct dwarf2_cu *target_cu = cu;
15356       struct die_info *target_die;
15357       struct attribute *target_attr;
15358
15359       target_die = follow_die_ref (die, attr, &target_cu);
15360       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15361       if (target_attr == NULL)
15362         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15363                                    target_cu);
15364       if (target_attr == NULL)
15365         return 0;
15366
15367       switch (target_attr->name)
15368         {
15369           case DW_AT_location:
15370             if (attr_form_is_section_offset (target_attr))
15371               {
15372                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15373                 baton->referenced_type = die_type (target_die, target_cu);
15374                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15375                 prop->data.baton = baton;
15376                 prop->kind = PROP_LOCLIST;
15377                 gdb_assert (prop->data.baton != NULL);
15378               }
15379             else if (attr_form_is_block (target_attr))
15380               {
15381                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15382                 baton->referenced_type = die_type (target_die, target_cu);
15383                 baton->locexpr.per_cu = cu->per_cu;
15384                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15385                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15386                 prop->data.baton = baton;
15387                 prop->kind = PROP_LOCEXPR;
15388                 gdb_assert (prop->data.baton != NULL);
15389               }
15390             else
15391               {
15392                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15393                                                        "dynamic property");
15394                 return 0;
15395               }
15396             break;
15397           case DW_AT_data_member_location:
15398             {
15399               LONGEST offset;
15400
15401               if (!handle_data_member_location (target_die, target_cu,
15402                                                 &offset))
15403                 return 0;
15404
15405               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15406               baton->referenced_type = read_type_die (target_die->parent,
15407                                                       target_cu);
15408               baton->offset_info.offset = offset;
15409               baton->offset_info.type = die_type (target_die, target_cu);
15410               prop->data.baton = baton;
15411               prop->kind = PROP_ADDR_OFFSET;
15412               break;
15413             }
15414         }
15415     }
15416   else if (attr_form_is_constant (attr))
15417     {
15418       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15419       prop->kind = PROP_CONST;
15420     }
15421   else
15422     {
15423       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15424                                              dwarf2_name (die, cu));
15425       return 0;
15426     }
15427
15428   return 1;
15429 }
15430
15431 /* Read the given DW_AT_subrange DIE.  */
15432
15433 static struct type *
15434 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15435 {
15436   struct type *base_type, *orig_base_type;
15437   struct type *range_type;
15438   struct attribute *attr;
15439   struct dynamic_prop low, high;
15440   int low_default_is_valid;
15441   int high_bound_is_count = 0;
15442   const char *name;
15443   LONGEST negative_mask;
15444
15445   orig_base_type = die_type (die, cu);
15446   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15447      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15448      creating the range type, but we use the result of check_typedef
15449      when examining properties of the type.  */
15450   base_type = check_typedef (orig_base_type);
15451
15452   /* The die_type call above may have already set the type for this DIE.  */
15453   range_type = get_die_type (die, cu);
15454   if (range_type)
15455     return range_type;
15456
15457   low.kind = PROP_CONST;
15458   high.kind = PROP_CONST;
15459   high.data.const_val = 0;
15460
15461   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15462      omitting DW_AT_lower_bound.  */
15463   switch (cu->language)
15464     {
15465     case language_c:
15466     case language_cplus:
15467       low.data.const_val = 0;
15468       low_default_is_valid = 1;
15469       break;
15470     case language_fortran:
15471       low.data.const_val = 1;
15472       low_default_is_valid = 1;
15473       break;
15474     case language_d:
15475     case language_objc:
15476     case language_rust:
15477       low.data.const_val = 0;
15478       low_default_is_valid = (cu->header.version >= 4);
15479       break;
15480     case language_ada:
15481     case language_m2:
15482     case language_pascal:
15483       low.data.const_val = 1;
15484       low_default_is_valid = (cu->header.version >= 4);
15485       break;
15486     default:
15487       low.data.const_val = 0;
15488       low_default_is_valid = 0;
15489       break;
15490     }
15491
15492   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15493   if (attr)
15494     attr_to_dynamic_prop (attr, die, cu, &low);
15495   else if (!low_default_is_valid)
15496     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15497                                       "- DIE at 0x%x [in module %s]"),
15498                to_underlying (die->sect_off), objfile_name (cu->objfile));
15499
15500   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15501   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15502     {
15503       attr = dwarf2_attr (die, DW_AT_count, cu);
15504       if (attr_to_dynamic_prop (attr, die, cu, &high))
15505         {
15506           /* If bounds are constant do the final calculation here.  */
15507           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15508             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15509           else
15510             high_bound_is_count = 1;
15511         }
15512     }
15513
15514   /* Dwarf-2 specifications explicitly allows to create subrange types
15515      without specifying a base type.
15516      In that case, the base type must be set to the type of
15517      the lower bound, upper bound or count, in that order, if any of these
15518      three attributes references an object that has a type.
15519      If no base type is found, the Dwarf-2 specifications say that
15520      a signed integer type of size equal to the size of an address should
15521      be used.
15522      For the following C code: `extern char gdb_int [];'
15523      GCC produces an empty range DIE.
15524      FIXME: muller/2010-05-28: Possible references to object for low bound,
15525      high bound or count are not yet handled by this code.  */
15526   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15527     {
15528       struct objfile *objfile = cu->objfile;
15529       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15530       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15531       struct type *int_type = objfile_type (objfile)->builtin_int;
15532
15533       /* Test "int", "long int", and "long long int" objfile types,
15534          and select the first one having a size above or equal to the
15535          architecture address size.  */
15536       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15537         base_type = int_type;
15538       else
15539         {
15540           int_type = objfile_type (objfile)->builtin_long;
15541           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15542             base_type = int_type;
15543           else
15544             {
15545               int_type = objfile_type (objfile)->builtin_long_long;
15546               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15547                 base_type = int_type;
15548             }
15549         }
15550     }
15551
15552   /* Normally, the DWARF producers are expected to use a signed
15553      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15554      But this is unfortunately not always the case, as witnessed
15555      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15556      is used instead.  To work around that ambiguity, we treat
15557      the bounds as signed, and thus sign-extend their values, when
15558      the base type is signed.  */
15559   negative_mask =
15560     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15561   if (low.kind == PROP_CONST
15562       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15563     low.data.const_val |= negative_mask;
15564   if (high.kind == PROP_CONST
15565       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15566     high.data.const_val |= negative_mask;
15567
15568   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15569
15570   if (high_bound_is_count)
15571     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15572
15573   /* Ada expects an empty array on no boundary attributes.  */
15574   if (attr == NULL && cu->language != language_ada)
15575     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15576
15577   name = dwarf2_name (die, cu);
15578   if (name)
15579     TYPE_NAME (range_type) = name;
15580
15581   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15582   if (attr)
15583     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15584
15585   set_die_type (die, range_type, cu);
15586
15587   /* set_die_type should be already done.  */
15588   set_descriptive_type (range_type, die, cu);
15589
15590   return range_type;
15591 }
15592
15593 static struct type *
15594 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15595 {
15596   struct type *type;
15597
15598   /* For now, we only support the C meaning of an unspecified type: void.  */
15599
15600   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15601   TYPE_NAME (type) = dwarf2_name (die, cu);
15602
15603   return set_die_type (die, type, cu);
15604 }
15605
15606 /* Read a single die and all its descendents.  Set the die's sibling
15607    field to NULL; set other fields in the die correctly, and set all
15608    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15609    location of the info_ptr after reading all of those dies.  PARENT
15610    is the parent of the die in question.  */
15611
15612 static struct die_info *
15613 read_die_and_children (const struct die_reader_specs *reader,
15614                        const gdb_byte *info_ptr,
15615                        const gdb_byte **new_info_ptr,
15616                        struct die_info *parent)
15617 {
15618   struct die_info *die;
15619   const gdb_byte *cur_ptr;
15620   int has_children;
15621
15622   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15623   if (die == NULL)
15624     {
15625       *new_info_ptr = cur_ptr;
15626       return NULL;
15627     }
15628   store_in_ref_table (die, reader->cu);
15629
15630   if (has_children)
15631     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15632   else
15633     {
15634       die->child = NULL;
15635       *new_info_ptr = cur_ptr;
15636     }
15637
15638   die->sibling = NULL;
15639   die->parent = parent;
15640   return die;
15641 }
15642
15643 /* Read a die, all of its descendents, and all of its siblings; set
15644    all of the fields of all of the dies correctly.  Arguments are as
15645    in read_die_and_children.  */
15646
15647 static struct die_info *
15648 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15649                          const gdb_byte *info_ptr,
15650                          const gdb_byte **new_info_ptr,
15651                          struct die_info *parent)
15652 {
15653   struct die_info *first_die, *last_sibling;
15654   const gdb_byte *cur_ptr;
15655
15656   cur_ptr = info_ptr;
15657   first_die = last_sibling = NULL;
15658
15659   while (1)
15660     {
15661       struct die_info *die
15662         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15663
15664       if (die == NULL)
15665         {
15666           *new_info_ptr = cur_ptr;
15667           return first_die;
15668         }
15669
15670       if (!first_die)
15671         first_die = die;
15672       else
15673         last_sibling->sibling = die;
15674
15675       last_sibling = die;
15676     }
15677 }
15678
15679 /* Read a die, all of its descendents, and all of its siblings; set
15680    all of the fields of all of the dies correctly.  Arguments are as
15681    in read_die_and_children.
15682    This the main entry point for reading a DIE and all its children.  */
15683
15684 static struct die_info *
15685 read_die_and_siblings (const struct die_reader_specs *reader,
15686                        const gdb_byte *info_ptr,
15687                        const gdb_byte **new_info_ptr,
15688                        struct die_info *parent)
15689 {
15690   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15691                                                   new_info_ptr, parent);
15692
15693   if (dwarf_die_debug)
15694     {
15695       fprintf_unfiltered (gdb_stdlog,
15696                           "Read die from %s@0x%x of %s:\n",
15697                           get_section_name (reader->die_section),
15698                           (unsigned) (info_ptr - reader->die_section->buffer),
15699                           bfd_get_filename (reader->abfd));
15700       dump_die (die, dwarf_die_debug);
15701     }
15702
15703   return die;
15704 }
15705
15706 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15707    attributes.
15708    The caller is responsible for filling in the extra attributes
15709    and updating (*DIEP)->num_attrs.
15710    Set DIEP to point to a newly allocated die with its information,
15711    except for its child, sibling, and parent fields.
15712    Set HAS_CHILDREN to tell whether the die has children or not.  */
15713
15714 static const gdb_byte *
15715 read_full_die_1 (const struct die_reader_specs *reader,
15716                  struct die_info **diep, const gdb_byte *info_ptr,
15717                  int *has_children, int num_extra_attrs)
15718 {
15719   unsigned int abbrev_number, bytes_read, i;
15720   struct abbrev_info *abbrev;
15721   struct die_info *die;
15722   struct dwarf2_cu *cu = reader->cu;
15723   bfd *abfd = reader->abfd;
15724
15725   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15726   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15727   info_ptr += bytes_read;
15728   if (!abbrev_number)
15729     {
15730       *diep = NULL;
15731       *has_children = 0;
15732       return info_ptr;
15733     }
15734
15735   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15736   if (!abbrev)
15737     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15738            abbrev_number,
15739            bfd_get_filename (abfd));
15740
15741   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15742   die->sect_off = sect_off;
15743   die->tag = abbrev->tag;
15744   die->abbrev = abbrev_number;
15745
15746   /* Make the result usable.
15747      The caller needs to update num_attrs after adding the extra
15748      attributes.  */
15749   die->num_attrs = abbrev->num_attrs;
15750
15751   for (i = 0; i < abbrev->num_attrs; ++i)
15752     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15753                                info_ptr);
15754
15755   *diep = die;
15756   *has_children = abbrev->has_children;
15757   return info_ptr;
15758 }
15759
15760 /* Read a die and all its attributes.
15761    Set DIEP to point to a newly allocated die with its information,
15762    except for its child, sibling, and parent fields.
15763    Set HAS_CHILDREN to tell whether the die has children or not.  */
15764
15765 static const gdb_byte *
15766 read_full_die (const struct die_reader_specs *reader,
15767                struct die_info **diep, const gdb_byte *info_ptr,
15768                int *has_children)
15769 {
15770   const gdb_byte *result;
15771
15772   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15773
15774   if (dwarf_die_debug)
15775     {
15776       fprintf_unfiltered (gdb_stdlog,
15777                           "Read die from %s@0x%x of %s:\n",
15778                           get_section_name (reader->die_section),
15779                           (unsigned) (info_ptr - reader->die_section->buffer),
15780                           bfd_get_filename (reader->abfd));
15781       dump_die (*diep, dwarf_die_debug);
15782     }
15783
15784   return result;
15785 }
15786 \f
15787 /* Abbreviation tables.
15788
15789    In DWARF version 2, the description of the debugging information is
15790    stored in a separate .debug_abbrev section.  Before we read any
15791    dies from a section we read in all abbreviations and install them
15792    in a hash table.  */
15793
15794 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15795
15796 static struct abbrev_info *
15797 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15798 {
15799   struct abbrev_info *abbrev;
15800
15801   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15802   memset (abbrev, 0, sizeof (struct abbrev_info));
15803
15804   return abbrev;
15805 }
15806
15807 /* Add an abbreviation to the table.  */
15808
15809 static void
15810 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15811                          unsigned int abbrev_number,
15812                          struct abbrev_info *abbrev)
15813 {
15814   unsigned int hash_number;
15815
15816   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15817   abbrev->next = abbrev_table->abbrevs[hash_number];
15818   abbrev_table->abbrevs[hash_number] = abbrev;
15819 }
15820
15821 /* Look up an abbrev in the table.
15822    Returns NULL if the abbrev is not found.  */
15823
15824 static struct abbrev_info *
15825 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15826                             unsigned int abbrev_number)
15827 {
15828   unsigned int hash_number;
15829   struct abbrev_info *abbrev;
15830
15831   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15832   abbrev = abbrev_table->abbrevs[hash_number];
15833
15834   while (abbrev)
15835     {
15836       if (abbrev->number == abbrev_number)
15837         return abbrev;
15838       abbrev = abbrev->next;
15839     }
15840   return NULL;
15841 }
15842
15843 /* Read in an abbrev table.  */
15844
15845 static struct abbrev_table *
15846 abbrev_table_read_table (struct dwarf2_section_info *section,
15847                          sect_offset sect_off)
15848 {
15849   struct objfile *objfile = dwarf2_per_objfile->objfile;
15850   bfd *abfd = get_section_bfd_owner (section);
15851   struct abbrev_table *abbrev_table;
15852   const gdb_byte *abbrev_ptr;
15853   struct abbrev_info *cur_abbrev;
15854   unsigned int abbrev_number, bytes_read, abbrev_name;
15855   unsigned int abbrev_form;
15856   struct attr_abbrev *cur_attrs;
15857   unsigned int allocated_attrs;
15858
15859   abbrev_table = XNEW (struct abbrev_table);
15860   abbrev_table->sect_off = sect_off;
15861   obstack_init (&abbrev_table->abbrev_obstack);
15862   abbrev_table->abbrevs =
15863     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15864                ABBREV_HASH_SIZE);
15865   memset (abbrev_table->abbrevs, 0,
15866           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15867
15868   dwarf2_read_section (objfile, section);
15869   abbrev_ptr = section->buffer + to_underlying (sect_off);
15870   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15871   abbrev_ptr += bytes_read;
15872
15873   allocated_attrs = ATTR_ALLOC_CHUNK;
15874   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15875
15876   /* Loop until we reach an abbrev number of 0.  */
15877   while (abbrev_number)
15878     {
15879       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15880
15881       /* read in abbrev header */
15882       cur_abbrev->number = abbrev_number;
15883       cur_abbrev->tag
15884         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15885       abbrev_ptr += bytes_read;
15886       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15887       abbrev_ptr += 1;
15888
15889       /* now read in declarations */
15890       for (;;)
15891         {
15892           LONGEST implicit_const;
15893
15894           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15895           abbrev_ptr += bytes_read;
15896           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15897           abbrev_ptr += bytes_read;
15898           if (abbrev_form == DW_FORM_implicit_const)
15899             {
15900               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15901                                                    &bytes_read);
15902               abbrev_ptr += bytes_read;
15903             }
15904           else
15905             {
15906               /* Initialize it due to a false compiler warning.  */
15907               implicit_const = -1;
15908             }
15909
15910           if (abbrev_name == 0)
15911             break;
15912
15913           if (cur_abbrev->num_attrs == allocated_attrs)
15914             {
15915               allocated_attrs += ATTR_ALLOC_CHUNK;
15916               cur_attrs
15917                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15918             }
15919
15920           cur_attrs[cur_abbrev->num_attrs].name
15921             = (enum dwarf_attribute) abbrev_name;
15922           cur_attrs[cur_abbrev->num_attrs].form
15923             = (enum dwarf_form) abbrev_form;
15924           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15925           ++cur_abbrev->num_attrs;
15926         }
15927
15928       cur_abbrev->attrs =
15929         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15930                    cur_abbrev->num_attrs);
15931       memcpy (cur_abbrev->attrs, cur_attrs,
15932               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15933
15934       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15935
15936       /* Get next abbreviation.
15937          Under Irix6 the abbreviations for a compilation unit are not
15938          always properly terminated with an abbrev number of 0.
15939          Exit loop if we encounter an abbreviation which we have
15940          already read (which means we are about to read the abbreviations
15941          for the next compile unit) or if the end of the abbreviation
15942          table is reached.  */
15943       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15944         break;
15945       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15946       abbrev_ptr += bytes_read;
15947       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15948         break;
15949     }
15950
15951   xfree (cur_attrs);
15952   return abbrev_table;
15953 }
15954
15955 /* Free the resources held by ABBREV_TABLE.  */
15956
15957 static void
15958 abbrev_table_free (struct abbrev_table *abbrev_table)
15959 {
15960   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15961   xfree (abbrev_table);
15962 }
15963
15964 /* Same as abbrev_table_free but as a cleanup.
15965    We pass in a pointer to the pointer to the table so that we can
15966    set the pointer to NULL when we're done.  It also simplifies
15967    build_type_psymtabs_1.  */
15968
15969 static void
15970 abbrev_table_free_cleanup (void *table_ptr)
15971 {
15972   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15973
15974   if (*abbrev_table_ptr != NULL)
15975     abbrev_table_free (*abbrev_table_ptr);
15976   *abbrev_table_ptr = NULL;
15977 }
15978
15979 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15980
15981 static void
15982 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15983                      struct dwarf2_section_info *abbrev_section)
15984 {
15985   cu->abbrev_table =
15986     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15987 }
15988
15989 /* Release the memory used by the abbrev table for a compilation unit.  */
15990
15991 static void
15992 dwarf2_free_abbrev_table (void *ptr_to_cu)
15993 {
15994   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15995
15996   if (cu->abbrev_table != NULL)
15997     abbrev_table_free (cu->abbrev_table);
15998   /* Set this to NULL so that we SEGV if we try to read it later,
15999      and also because free_comp_unit verifies this is NULL.  */
16000   cu->abbrev_table = NULL;
16001 }
16002 \f
16003 /* Returns nonzero if TAG represents a type that we might generate a partial
16004    symbol for.  */
16005
16006 static int
16007 is_type_tag_for_partial (int tag)
16008 {
16009   switch (tag)
16010     {
16011 #if 0
16012     /* Some types that would be reasonable to generate partial symbols for,
16013        that we don't at present.  */
16014     case DW_TAG_array_type:
16015     case DW_TAG_file_type:
16016     case DW_TAG_ptr_to_member_type:
16017     case DW_TAG_set_type:
16018     case DW_TAG_string_type:
16019     case DW_TAG_subroutine_type:
16020 #endif
16021     case DW_TAG_base_type:
16022     case DW_TAG_class_type:
16023     case DW_TAG_interface_type:
16024     case DW_TAG_enumeration_type:
16025     case DW_TAG_structure_type:
16026     case DW_TAG_subrange_type:
16027     case DW_TAG_typedef:
16028     case DW_TAG_union_type:
16029       return 1;
16030     default:
16031       return 0;
16032     }
16033 }
16034
16035 /* Load all DIEs that are interesting for partial symbols into memory.  */
16036
16037 static struct partial_die_info *
16038 load_partial_dies (const struct die_reader_specs *reader,
16039                    const gdb_byte *info_ptr, int building_psymtab)
16040 {
16041   struct dwarf2_cu *cu = reader->cu;
16042   struct objfile *objfile = cu->objfile;
16043   struct partial_die_info *part_die;
16044   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16045   struct abbrev_info *abbrev;
16046   unsigned int bytes_read;
16047   unsigned int load_all = 0;
16048   int nesting_level = 1;
16049
16050   parent_die = NULL;
16051   last_die = NULL;
16052
16053   gdb_assert (cu->per_cu != NULL);
16054   if (cu->per_cu->load_all_dies)
16055     load_all = 1;
16056
16057   cu->partial_dies
16058     = htab_create_alloc_ex (cu->header.length / 12,
16059                             partial_die_hash,
16060                             partial_die_eq,
16061                             NULL,
16062                             &cu->comp_unit_obstack,
16063                             hashtab_obstack_allocate,
16064                             dummy_obstack_deallocate);
16065
16066   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16067
16068   while (1)
16069     {
16070       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16071
16072       /* A NULL abbrev means the end of a series of children.  */
16073       if (abbrev == NULL)
16074         {
16075           if (--nesting_level == 0)
16076             {
16077               /* PART_DIE was probably the last thing allocated on the
16078                  comp_unit_obstack, so we could call obstack_free
16079                  here.  We don't do that because the waste is small,
16080                  and will be cleaned up when we're done with this
16081                  compilation unit.  This way, we're also more robust
16082                  against other users of the comp_unit_obstack.  */
16083               return first_die;
16084             }
16085           info_ptr += bytes_read;
16086           last_die = parent_die;
16087           parent_die = parent_die->die_parent;
16088           continue;
16089         }
16090
16091       /* Check for template arguments.  We never save these; if
16092          they're seen, we just mark the parent, and go on our way.  */
16093       if (parent_die != NULL
16094           && cu->language == language_cplus
16095           && (abbrev->tag == DW_TAG_template_type_param
16096               || abbrev->tag == DW_TAG_template_value_param))
16097         {
16098           parent_die->has_template_arguments = 1;
16099
16100           if (!load_all)
16101             {
16102               /* We don't need a partial DIE for the template argument.  */
16103               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16104               continue;
16105             }
16106         }
16107
16108       /* We only recurse into c++ subprograms looking for template arguments.
16109          Skip their other children.  */
16110       if (!load_all
16111           && cu->language == language_cplus
16112           && parent_die != NULL
16113           && parent_die->tag == DW_TAG_subprogram)
16114         {
16115           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16116           continue;
16117         }
16118
16119       /* Check whether this DIE is interesting enough to save.  Normally
16120          we would not be interested in members here, but there may be
16121          later variables referencing them via DW_AT_specification (for
16122          static members).  */
16123       if (!load_all
16124           && !is_type_tag_for_partial (abbrev->tag)
16125           && abbrev->tag != DW_TAG_constant
16126           && abbrev->tag != DW_TAG_enumerator
16127           && abbrev->tag != DW_TAG_subprogram
16128           && abbrev->tag != DW_TAG_lexical_block
16129           && abbrev->tag != DW_TAG_variable
16130           && abbrev->tag != DW_TAG_namespace
16131           && abbrev->tag != DW_TAG_module
16132           && abbrev->tag != DW_TAG_member
16133           && abbrev->tag != DW_TAG_imported_unit
16134           && abbrev->tag != DW_TAG_imported_declaration)
16135         {
16136           /* Otherwise we skip to the next sibling, if any.  */
16137           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16138           continue;
16139         }
16140
16141       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16142                                    info_ptr);
16143
16144       /* This two-pass algorithm for processing partial symbols has a
16145          high cost in cache pressure.  Thus, handle some simple cases
16146          here which cover the majority of C partial symbols.  DIEs
16147          which neither have specification tags in them, nor could have
16148          specification tags elsewhere pointing at them, can simply be
16149          processed and discarded.
16150
16151          This segment is also optional; scan_partial_symbols and
16152          add_partial_symbol will handle these DIEs if we chain
16153          them in normally.  When compilers which do not emit large
16154          quantities of duplicate debug information are more common,
16155          this code can probably be removed.  */
16156
16157       /* Any complete simple types at the top level (pretty much all
16158          of them, for a language without namespaces), can be processed
16159          directly.  */
16160       if (parent_die == NULL
16161           && part_die->has_specification == 0
16162           && part_die->is_declaration == 0
16163           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16164               || part_die->tag == DW_TAG_base_type
16165               || part_die->tag == DW_TAG_subrange_type))
16166         {
16167           if (building_psymtab && part_die->name != NULL)
16168             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16169                                  VAR_DOMAIN, LOC_TYPEDEF,
16170                                  &objfile->static_psymbols,
16171                                  0, cu->language, objfile);
16172           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16173           continue;
16174         }
16175
16176       /* The exception for DW_TAG_typedef with has_children above is
16177          a workaround of GCC PR debug/47510.  In the case of this complaint
16178          type_name_no_tag_or_error will error on such types later.
16179
16180          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16181          it could not find the child DIEs referenced later, this is checked
16182          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16183
16184       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16185         complaint (&symfile_complaints,
16186                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16187                      "- DIE at 0x%x [in module %s]"),
16188                    to_underlying (part_die->sect_off), objfile_name (objfile));
16189
16190       /* If we're at the second level, and we're an enumerator, and
16191          our parent has no specification (meaning possibly lives in a
16192          namespace elsewhere), then we can add the partial symbol now
16193          instead of queueing it.  */
16194       if (part_die->tag == DW_TAG_enumerator
16195           && parent_die != NULL
16196           && parent_die->die_parent == NULL
16197           && parent_die->tag == DW_TAG_enumeration_type
16198           && parent_die->has_specification == 0)
16199         {
16200           if (part_die->name == NULL)
16201             complaint (&symfile_complaints,
16202                        _("malformed enumerator DIE ignored"));
16203           else if (building_psymtab)
16204             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16205                                  VAR_DOMAIN, LOC_CONST,
16206                                  cu->language == language_cplus
16207                                  ? &objfile->global_psymbols
16208                                  : &objfile->static_psymbols,
16209                                  0, cu->language, objfile);
16210
16211           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16212           continue;
16213         }
16214
16215       /* We'll save this DIE so link it in.  */
16216       part_die->die_parent = parent_die;
16217       part_die->die_sibling = NULL;
16218       part_die->die_child = NULL;
16219
16220       if (last_die && last_die == parent_die)
16221         last_die->die_child = part_die;
16222       else if (last_die)
16223         last_die->die_sibling = part_die;
16224
16225       last_die = part_die;
16226
16227       if (first_die == NULL)
16228         first_die = part_die;
16229
16230       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16231          find interesting need to be in the hash table, because we
16232          also have the parent/sibling/child chains; only those that we
16233          might refer to by offset later during partial symbol reading.
16234
16235          For now this means things that might have be the target of a
16236          DW_AT_specification, DW_AT_abstract_origin, or
16237          DW_AT_extension.  DW_AT_extension will refer only to
16238          namespaces; DW_AT_abstract_origin refers to functions (and
16239          many things under the function DIE, but we do not recurse
16240          into function DIEs during partial symbol reading) and
16241          possibly variables as well; DW_AT_specification refers to
16242          declarations.  Declarations ought to have the DW_AT_declaration
16243          flag.  It happens that GCC forgets to put it in sometimes, but
16244          only for functions, not for types.
16245
16246          Adding more things than necessary to the hash table is harmless
16247          except for the performance cost.  Adding too few will result in
16248          wasted time in find_partial_die, when we reread the compilation
16249          unit with load_all_dies set.  */
16250
16251       if (load_all
16252           || abbrev->tag == DW_TAG_constant
16253           || abbrev->tag == DW_TAG_subprogram
16254           || abbrev->tag == DW_TAG_variable
16255           || abbrev->tag == DW_TAG_namespace
16256           || part_die->is_declaration)
16257         {
16258           void **slot;
16259
16260           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16261                                            to_underlying (part_die->sect_off),
16262                                            INSERT);
16263           *slot = part_die;
16264         }
16265
16266       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16267
16268       /* For some DIEs we want to follow their children (if any).  For C
16269          we have no reason to follow the children of structures; for other
16270          languages we have to, so that we can get at method physnames
16271          to infer fully qualified class names, for DW_AT_specification,
16272          and for C++ template arguments.  For C++, we also look one level
16273          inside functions to find template arguments (if the name of the
16274          function does not already contain the template arguments).
16275
16276          For Ada, we need to scan the children of subprograms and lexical
16277          blocks as well because Ada allows the definition of nested
16278          entities that could be interesting for the debugger, such as
16279          nested subprograms for instance.  */
16280       if (last_die->has_children
16281           && (load_all
16282               || last_die->tag == DW_TAG_namespace
16283               || last_die->tag == DW_TAG_module
16284               || last_die->tag == DW_TAG_enumeration_type
16285               || (cu->language == language_cplus
16286                   && last_die->tag == DW_TAG_subprogram
16287                   && (last_die->name == NULL
16288                       || strchr (last_die->name, '<') == NULL))
16289               || (cu->language != language_c
16290                   && (last_die->tag == DW_TAG_class_type
16291                       || last_die->tag == DW_TAG_interface_type
16292                       || last_die->tag == DW_TAG_structure_type
16293                       || last_die->tag == DW_TAG_union_type))
16294               || (cu->language == language_ada
16295                   && (last_die->tag == DW_TAG_subprogram
16296                       || last_die->tag == DW_TAG_lexical_block))))
16297         {
16298           nesting_level++;
16299           parent_die = last_die;
16300           continue;
16301         }
16302
16303       /* Otherwise we skip to the next sibling, if any.  */
16304       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16305
16306       /* Back to the top, do it again.  */
16307     }
16308 }
16309
16310 /* Read a minimal amount of information into the minimal die structure.  */
16311
16312 static const gdb_byte *
16313 read_partial_die (const struct die_reader_specs *reader,
16314                   struct partial_die_info *part_die,
16315                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16316                   const gdb_byte *info_ptr)
16317 {
16318   struct dwarf2_cu *cu = reader->cu;
16319   struct objfile *objfile = cu->objfile;
16320   const gdb_byte *buffer = reader->buffer;
16321   unsigned int i;
16322   struct attribute attr;
16323   int has_low_pc_attr = 0;
16324   int has_high_pc_attr = 0;
16325   int high_pc_relative = 0;
16326
16327   memset (part_die, 0, sizeof (struct partial_die_info));
16328
16329   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16330
16331   info_ptr += abbrev_len;
16332
16333   if (abbrev == NULL)
16334     return info_ptr;
16335
16336   part_die->tag = abbrev->tag;
16337   part_die->has_children = abbrev->has_children;
16338
16339   for (i = 0; i < abbrev->num_attrs; ++i)
16340     {
16341       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16342
16343       /* Store the data if it is of an attribute we want to keep in a
16344          partial symbol table.  */
16345       switch (attr.name)
16346         {
16347         case DW_AT_name:
16348           switch (part_die->tag)
16349             {
16350             case DW_TAG_compile_unit:
16351             case DW_TAG_partial_unit:
16352             case DW_TAG_type_unit:
16353               /* Compilation units have a DW_AT_name that is a filename, not
16354                  a source language identifier.  */
16355             case DW_TAG_enumeration_type:
16356             case DW_TAG_enumerator:
16357               /* These tags always have simple identifiers already; no need
16358                  to canonicalize them.  */
16359               part_die->name = DW_STRING (&attr);
16360               break;
16361             default:
16362               part_die->name
16363                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16364                                             &objfile->per_bfd->storage_obstack);
16365               break;
16366             }
16367           break;
16368         case DW_AT_linkage_name:
16369         case DW_AT_MIPS_linkage_name:
16370           /* Note that both forms of linkage name might appear.  We
16371              assume they will be the same, and we only store the last
16372              one we see.  */
16373           if (cu->language == language_ada)
16374             part_die->name = DW_STRING (&attr);
16375           part_die->linkage_name = DW_STRING (&attr);
16376           break;
16377         case DW_AT_low_pc:
16378           has_low_pc_attr = 1;
16379           part_die->lowpc = attr_value_as_address (&attr);
16380           break;
16381         case DW_AT_high_pc:
16382           has_high_pc_attr = 1;
16383           part_die->highpc = attr_value_as_address (&attr);
16384           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16385                 high_pc_relative = 1;
16386           break;
16387         case DW_AT_location:
16388           /* Support the .debug_loc offsets.  */
16389           if (attr_form_is_block (&attr))
16390             {
16391                part_die->d.locdesc = DW_BLOCK (&attr);
16392             }
16393           else if (attr_form_is_section_offset (&attr))
16394             {
16395               dwarf2_complex_location_expr_complaint ();
16396             }
16397           else
16398             {
16399               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16400                                                      "partial symbol information");
16401             }
16402           break;
16403         case DW_AT_external:
16404           part_die->is_external = DW_UNSND (&attr);
16405           break;
16406         case DW_AT_declaration:
16407           part_die->is_declaration = DW_UNSND (&attr);
16408           break;
16409         case DW_AT_type:
16410           part_die->has_type = 1;
16411           break;
16412         case DW_AT_abstract_origin:
16413         case DW_AT_specification:
16414         case DW_AT_extension:
16415           part_die->has_specification = 1;
16416           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16417           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16418                                    || cu->per_cu->is_dwz);
16419           break;
16420         case DW_AT_sibling:
16421           /* Ignore absolute siblings, they might point outside of
16422              the current compile unit.  */
16423           if (attr.form == DW_FORM_ref_addr)
16424             complaint (&symfile_complaints,
16425                        _("ignoring absolute DW_AT_sibling"));
16426           else
16427             {
16428               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16429               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16430
16431               if (sibling_ptr < info_ptr)
16432                 complaint (&symfile_complaints,
16433                            _("DW_AT_sibling points backwards"));
16434               else if (sibling_ptr > reader->buffer_end)
16435                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16436               else
16437                 part_die->sibling = sibling_ptr;
16438             }
16439           break;
16440         case DW_AT_byte_size:
16441           part_die->has_byte_size = 1;
16442           break;
16443         case DW_AT_const_value:
16444           part_die->has_const_value = 1;
16445           break;
16446         case DW_AT_calling_convention:
16447           /* DWARF doesn't provide a way to identify a program's source-level
16448              entry point.  DW_AT_calling_convention attributes are only meant
16449              to describe functions' calling conventions.
16450
16451              However, because it's a necessary piece of information in
16452              Fortran, and before DWARF 4 DW_CC_program was the only
16453              piece of debugging information whose definition refers to
16454              a 'main program' at all, several compilers marked Fortran
16455              main programs with DW_CC_program --- even when those
16456              functions use the standard calling conventions.
16457
16458              Although DWARF now specifies a way to provide this
16459              information, we support this practice for backward
16460              compatibility.  */
16461           if (DW_UNSND (&attr) == DW_CC_program
16462               && cu->language == language_fortran)
16463             part_die->main_subprogram = 1;
16464           break;
16465         case DW_AT_inline:
16466           if (DW_UNSND (&attr) == DW_INL_inlined
16467               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16468             part_die->may_be_inlined = 1;
16469           break;
16470
16471         case DW_AT_import:
16472           if (part_die->tag == DW_TAG_imported_unit)
16473             {
16474               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16475               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16476                                   || cu->per_cu->is_dwz);
16477             }
16478           break;
16479
16480         case DW_AT_main_subprogram:
16481           part_die->main_subprogram = DW_UNSND (&attr);
16482           break;
16483
16484         default:
16485           break;
16486         }
16487     }
16488
16489   if (high_pc_relative)
16490     part_die->highpc += part_die->lowpc;
16491
16492   if (has_low_pc_attr && has_high_pc_attr)
16493     {
16494       /* When using the GNU linker, .gnu.linkonce. sections are used to
16495          eliminate duplicate copies of functions and vtables and such.
16496          The linker will arbitrarily choose one and discard the others.
16497          The AT_*_pc values for such functions refer to local labels in
16498          these sections.  If the section from that file was discarded, the
16499          labels are not in the output, so the relocs get a value of 0.
16500          If this is a discarded function, mark the pc bounds as invalid,
16501          so that GDB will ignore it.  */
16502       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16503         {
16504           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16505
16506           complaint (&symfile_complaints,
16507                      _("DW_AT_low_pc %s is zero "
16508                        "for DIE at 0x%x [in module %s]"),
16509                      paddress (gdbarch, part_die->lowpc),
16510                      to_underlying (part_die->sect_off), objfile_name (objfile));
16511         }
16512       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16513       else if (part_die->lowpc >= part_die->highpc)
16514         {
16515           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16516
16517           complaint (&symfile_complaints,
16518                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16519                        "for DIE at 0x%x [in module %s]"),
16520                      paddress (gdbarch, part_die->lowpc),
16521                      paddress (gdbarch, part_die->highpc),
16522                      to_underlying (part_die->sect_off),
16523                      objfile_name (objfile));
16524         }
16525       else
16526         part_die->has_pc_info = 1;
16527     }
16528
16529   return info_ptr;
16530 }
16531
16532 /* Find a cached partial DIE at OFFSET in CU.  */
16533
16534 static struct partial_die_info *
16535 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16536 {
16537   struct partial_die_info *lookup_die = NULL;
16538   struct partial_die_info part_die;
16539
16540   part_die.sect_off = sect_off;
16541   lookup_die = ((struct partial_die_info *)
16542                 htab_find_with_hash (cu->partial_dies, &part_die,
16543                                      to_underlying (sect_off)));
16544
16545   return lookup_die;
16546 }
16547
16548 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16549    except in the case of .debug_types DIEs which do not reference
16550    outside their CU (they do however referencing other types via
16551    DW_FORM_ref_sig8).  */
16552
16553 static struct partial_die_info *
16554 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16555 {
16556   struct objfile *objfile = cu->objfile;
16557   struct dwarf2_per_cu_data *per_cu = NULL;
16558   struct partial_die_info *pd = NULL;
16559
16560   if (offset_in_dwz == cu->per_cu->is_dwz
16561       && offset_in_cu_p (&cu->header, sect_off))
16562     {
16563       pd = find_partial_die_in_comp_unit (sect_off, cu);
16564       if (pd != NULL)
16565         return pd;
16566       /* We missed recording what we needed.
16567          Load all dies and try again.  */
16568       per_cu = cu->per_cu;
16569     }
16570   else
16571     {
16572       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16573       if (cu->per_cu->is_debug_types)
16574         {
16575           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16576                    " external reference to offset 0x%x [in module %s].\n"),
16577                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16578                  bfd_get_filename (objfile->obfd));
16579         }
16580       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16581                                                  objfile);
16582
16583       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16584         load_partial_comp_unit (per_cu);
16585
16586       per_cu->cu->last_used = 0;
16587       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16588     }
16589
16590   /* If we didn't find it, and not all dies have been loaded,
16591      load them all and try again.  */
16592
16593   if (pd == NULL && per_cu->load_all_dies == 0)
16594     {
16595       per_cu->load_all_dies = 1;
16596
16597       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16598          THIS_CU->cu may already be in use.  So we can't just free it and
16599          replace its DIEs with the ones we read in.  Instead, we leave those
16600          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16601          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16602          set.  */
16603       load_partial_comp_unit (per_cu);
16604
16605       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16606     }
16607
16608   if (pd == NULL)
16609     internal_error (__FILE__, __LINE__,
16610                     _("could not find partial DIE 0x%x "
16611                       "in cache [from module %s]\n"),
16612                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16613   return pd;
16614 }
16615
16616 /* See if we can figure out if the class lives in a namespace.  We do
16617    this by looking for a member function; its demangled name will
16618    contain namespace info, if there is any.  */
16619
16620 static void
16621 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16622                                   struct dwarf2_cu *cu)
16623 {
16624   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16625      what template types look like, because the demangler
16626      frequently doesn't give the same name as the debug info.  We
16627      could fix this by only using the demangled name to get the
16628      prefix (but see comment in read_structure_type).  */
16629
16630   struct partial_die_info *real_pdi;
16631   struct partial_die_info *child_pdi;
16632
16633   /* If this DIE (this DIE's specification, if any) has a parent, then
16634      we should not do this.  We'll prepend the parent's fully qualified
16635      name when we create the partial symbol.  */
16636
16637   real_pdi = struct_pdi;
16638   while (real_pdi->has_specification)
16639     real_pdi = find_partial_die (real_pdi->spec_offset,
16640                                  real_pdi->spec_is_dwz, cu);
16641
16642   if (real_pdi->die_parent != NULL)
16643     return;
16644
16645   for (child_pdi = struct_pdi->die_child;
16646        child_pdi != NULL;
16647        child_pdi = child_pdi->die_sibling)
16648     {
16649       if (child_pdi->tag == DW_TAG_subprogram
16650           && child_pdi->linkage_name != NULL)
16651         {
16652           char *actual_class_name
16653             = language_class_name_from_physname (cu->language_defn,
16654                                                  child_pdi->linkage_name);
16655           if (actual_class_name != NULL)
16656             {
16657               struct_pdi->name
16658                 = ((const char *)
16659                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16660                                   actual_class_name,
16661                                   strlen (actual_class_name)));
16662               xfree (actual_class_name);
16663             }
16664           break;
16665         }
16666     }
16667 }
16668
16669 /* Adjust PART_DIE before generating a symbol for it.  This function
16670    may set the is_external flag or change the DIE's name.  */
16671
16672 static void
16673 fixup_partial_die (struct partial_die_info *part_die,
16674                    struct dwarf2_cu *cu)
16675 {
16676   /* Once we've fixed up a die, there's no point in doing so again.
16677      This also avoids a memory leak if we were to call
16678      guess_partial_die_structure_name multiple times.  */
16679   if (part_die->fixup_called)
16680     return;
16681
16682   /* If we found a reference attribute and the DIE has no name, try
16683      to find a name in the referred to DIE.  */
16684
16685   if (part_die->name == NULL && part_die->has_specification)
16686     {
16687       struct partial_die_info *spec_die;
16688
16689       spec_die = find_partial_die (part_die->spec_offset,
16690                                    part_die->spec_is_dwz, cu);
16691
16692       fixup_partial_die (spec_die, cu);
16693
16694       if (spec_die->name)
16695         {
16696           part_die->name = spec_die->name;
16697
16698           /* Copy DW_AT_external attribute if it is set.  */
16699           if (spec_die->is_external)
16700             part_die->is_external = spec_die->is_external;
16701         }
16702     }
16703
16704   /* Set default names for some unnamed DIEs.  */
16705
16706   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16707     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16708
16709   /* If there is no parent die to provide a namespace, and there are
16710      children, see if we can determine the namespace from their linkage
16711      name.  */
16712   if (cu->language == language_cplus
16713       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16714       && part_die->die_parent == NULL
16715       && part_die->has_children
16716       && (part_die->tag == DW_TAG_class_type
16717           || part_die->tag == DW_TAG_structure_type
16718           || part_die->tag == DW_TAG_union_type))
16719     guess_partial_die_structure_name (part_die, cu);
16720
16721   /* GCC might emit a nameless struct or union that has a linkage
16722      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16723   if (part_die->name == NULL
16724       && (part_die->tag == DW_TAG_class_type
16725           || part_die->tag == DW_TAG_interface_type
16726           || part_die->tag == DW_TAG_structure_type
16727           || part_die->tag == DW_TAG_union_type)
16728       && part_die->linkage_name != NULL)
16729     {
16730       char *demangled;
16731
16732       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16733       if (demangled)
16734         {
16735           const char *base;
16736
16737           /* Strip any leading namespaces/classes, keep only the base name.
16738              DW_AT_name for named DIEs does not contain the prefixes.  */
16739           base = strrchr (demangled, ':');
16740           if (base && base > demangled && base[-1] == ':')
16741             base++;
16742           else
16743             base = demangled;
16744
16745           part_die->name
16746             = ((const char *)
16747                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16748                               base, strlen (base)));
16749           xfree (demangled);
16750         }
16751     }
16752
16753   part_die->fixup_called = 1;
16754 }
16755
16756 /* Read an attribute value described by an attribute form.  */
16757
16758 static const gdb_byte *
16759 read_attribute_value (const struct die_reader_specs *reader,
16760                       struct attribute *attr, unsigned form,
16761                       LONGEST implicit_const, const gdb_byte *info_ptr)
16762 {
16763   struct dwarf2_cu *cu = reader->cu;
16764   struct objfile *objfile = cu->objfile;
16765   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16766   bfd *abfd = reader->abfd;
16767   struct comp_unit_head *cu_header = &cu->header;
16768   unsigned int bytes_read;
16769   struct dwarf_block *blk;
16770
16771   attr->form = (enum dwarf_form) form;
16772   switch (form)
16773     {
16774     case DW_FORM_ref_addr:
16775       if (cu->header.version == 2)
16776         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16777       else
16778         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16779                                        &cu->header, &bytes_read);
16780       info_ptr += bytes_read;
16781       break;
16782     case DW_FORM_GNU_ref_alt:
16783       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16784       info_ptr += bytes_read;
16785       break;
16786     case DW_FORM_addr:
16787       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16788       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16789       info_ptr += bytes_read;
16790       break;
16791     case DW_FORM_block2:
16792       blk = dwarf_alloc_block (cu);
16793       blk->size = read_2_bytes (abfd, info_ptr);
16794       info_ptr += 2;
16795       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16796       info_ptr += blk->size;
16797       DW_BLOCK (attr) = blk;
16798       break;
16799     case DW_FORM_block4:
16800       blk = dwarf_alloc_block (cu);
16801       blk->size = read_4_bytes (abfd, info_ptr);
16802       info_ptr += 4;
16803       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16804       info_ptr += blk->size;
16805       DW_BLOCK (attr) = blk;
16806       break;
16807     case DW_FORM_data2:
16808       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16809       info_ptr += 2;
16810       break;
16811     case DW_FORM_data4:
16812       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16813       info_ptr += 4;
16814       break;
16815     case DW_FORM_data8:
16816       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16817       info_ptr += 8;
16818       break;
16819     case DW_FORM_data16:
16820       blk = dwarf_alloc_block (cu);
16821       blk->size = 16;
16822       blk->data = read_n_bytes (abfd, info_ptr, 16);
16823       info_ptr += 16;
16824       DW_BLOCK (attr) = blk;
16825       break;
16826     case DW_FORM_sec_offset:
16827       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16828       info_ptr += bytes_read;
16829       break;
16830     case DW_FORM_string:
16831       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16832       DW_STRING_IS_CANONICAL (attr) = 0;
16833       info_ptr += bytes_read;
16834       break;
16835     case DW_FORM_strp:
16836       if (!cu->per_cu->is_dwz)
16837         {
16838           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16839                                                    &bytes_read);
16840           DW_STRING_IS_CANONICAL (attr) = 0;
16841           info_ptr += bytes_read;
16842           break;
16843         }
16844       /* FALLTHROUGH */
16845     case DW_FORM_line_strp:
16846       if (!cu->per_cu->is_dwz)
16847         {
16848           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16849                                                         cu_header, &bytes_read);
16850           DW_STRING_IS_CANONICAL (attr) = 0;
16851           info_ptr += bytes_read;
16852           break;
16853         }
16854       /* FALLTHROUGH */
16855     case DW_FORM_GNU_strp_alt:
16856       {
16857         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16858         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16859                                           &bytes_read);
16860
16861         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16862         DW_STRING_IS_CANONICAL (attr) = 0;
16863         info_ptr += bytes_read;
16864       }
16865       break;
16866     case DW_FORM_exprloc:
16867     case DW_FORM_block:
16868       blk = dwarf_alloc_block (cu);
16869       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16870       info_ptr += bytes_read;
16871       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16872       info_ptr += blk->size;
16873       DW_BLOCK (attr) = blk;
16874       break;
16875     case DW_FORM_block1:
16876       blk = dwarf_alloc_block (cu);
16877       blk->size = read_1_byte (abfd, info_ptr);
16878       info_ptr += 1;
16879       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16880       info_ptr += blk->size;
16881       DW_BLOCK (attr) = blk;
16882       break;
16883     case DW_FORM_data1:
16884       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16885       info_ptr += 1;
16886       break;
16887     case DW_FORM_flag:
16888       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16889       info_ptr += 1;
16890       break;
16891     case DW_FORM_flag_present:
16892       DW_UNSND (attr) = 1;
16893       break;
16894     case DW_FORM_sdata:
16895       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16896       info_ptr += bytes_read;
16897       break;
16898     case DW_FORM_udata:
16899       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16900       info_ptr += bytes_read;
16901       break;
16902     case DW_FORM_ref1:
16903       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16904                          + read_1_byte (abfd, info_ptr));
16905       info_ptr += 1;
16906       break;
16907     case DW_FORM_ref2:
16908       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16909                          + read_2_bytes (abfd, info_ptr));
16910       info_ptr += 2;
16911       break;
16912     case DW_FORM_ref4:
16913       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16914                          + read_4_bytes (abfd, info_ptr));
16915       info_ptr += 4;
16916       break;
16917     case DW_FORM_ref8:
16918       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16919                          + read_8_bytes (abfd, info_ptr));
16920       info_ptr += 8;
16921       break;
16922     case DW_FORM_ref_sig8:
16923       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16924       info_ptr += 8;
16925       break;
16926     case DW_FORM_ref_udata:
16927       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16928                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16929       info_ptr += bytes_read;
16930       break;
16931     case DW_FORM_indirect:
16932       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16933       info_ptr += bytes_read;
16934       if (form == DW_FORM_implicit_const)
16935         {
16936           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16937           info_ptr += bytes_read;
16938         }
16939       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16940                                        info_ptr);
16941       break;
16942     case DW_FORM_implicit_const:
16943       DW_SND (attr) = implicit_const;
16944       break;
16945     case DW_FORM_GNU_addr_index:
16946       if (reader->dwo_file == NULL)
16947         {
16948           /* For now flag a hard error.
16949              Later we can turn this into a complaint.  */
16950           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16951                  dwarf_form_name (form),
16952                  bfd_get_filename (abfd));
16953         }
16954       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16955       info_ptr += bytes_read;
16956       break;
16957     case DW_FORM_GNU_str_index:
16958       if (reader->dwo_file == NULL)
16959         {
16960           /* For now flag a hard error.
16961              Later we can turn this into a complaint if warranted.  */
16962           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16963                  dwarf_form_name (form),
16964                  bfd_get_filename (abfd));
16965         }
16966       {
16967         ULONGEST str_index =
16968           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16969
16970         DW_STRING (attr) = read_str_index (reader, str_index);
16971         DW_STRING_IS_CANONICAL (attr) = 0;
16972         info_ptr += bytes_read;
16973       }
16974       break;
16975     default:
16976       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16977              dwarf_form_name (form),
16978              bfd_get_filename (abfd));
16979     }
16980
16981   /* Super hack.  */
16982   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16983     attr->form = DW_FORM_GNU_ref_alt;
16984
16985   /* We have seen instances where the compiler tried to emit a byte
16986      size attribute of -1 which ended up being encoded as an unsigned
16987      0xffffffff.  Although 0xffffffff is technically a valid size value,
16988      an object of this size seems pretty unlikely so we can relatively
16989      safely treat these cases as if the size attribute was invalid and
16990      treat them as zero by default.  */
16991   if (attr->name == DW_AT_byte_size
16992       && form == DW_FORM_data4
16993       && DW_UNSND (attr) >= 0xffffffff)
16994     {
16995       complaint
16996         (&symfile_complaints,
16997          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16998          hex_string (DW_UNSND (attr)));
16999       DW_UNSND (attr) = 0;
17000     }
17001
17002   return info_ptr;
17003 }
17004
17005 /* Read an attribute described by an abbreviated attribute.  */
17006
17007 static const gdb_byte *
17008 read_attribute (const struct die_reader_specs *reader,
17009                 struct attribute *attr, struct attr_abbrev *abbrev,
17010                 const gdb_byte *info_ptr)
17011 {
17012   attr->name = abbrev->name;
17013   return read_attribute_value (reader, attr, abbrev->form,
17014                                abbrev->implicit_const, info_ptr);
17015 }
17016
17017 /* Read dwarf information from a buffer.  */
17018
17019 static unsigned int
17020 read_1_byte (bfd *abfd, const gdb_byte *buf)
17021 {
17022   return bfd_get_8 (abfd, buf);
17023 }
17024
17025 static int
17026 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17027 {
17028   return bfd_get_signed_8 (abfd, buf);
17029 }
17030
17031 static unsigned int
17032 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17033 {
17034   return bfd_get_16 (abfd, buf);
17035 }
17036
17037 static int
17038 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17039 {
17040   return bfd_get_signed_16 (abfd, buf);
17041 }
17042
17043 static unsigned int
17044 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17045 {
17046   return bfd_get_32 (abfd, buf);
17047 }
17048
17049 static int
17050 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17051 {
17052   return bfd_get_signed_32 (abfd, buf);
17053 }
17054
17055 static ULONGEST
17056 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17057 {
17058   return bfd_get_64 (abfd, buf);
17059 }
17060
17061 static CORE_ADDR
17062 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17063               unsigned int *bytes_read)
17064 {
17065   struct comp_unit_head *cu_header = &cu->header;
17066   CORE_ADDR retval = 0;
17067
17068   if (cu_header->signed_addr_p)
17069     {
17070       switch (cu_header->addr_size)
17071         {
17072         case 2:
17073           retval = bfd_get_signed_16 (abfd, buf);
17074           break;
17075         case 4:
17076           retval = bfd_get_signed_32 (abfd, buf);
17077           break;
17078         case 8:
17079           retval = bfd_get_signed_64 (abfd, buf);
17080           break;
17081         default:
17082           internal_error (__FILE__, __LINE__,
17083                           _("read_address: bad switch, signed [in module %s]"),
17084                           bfd_get_filename (abfd));
17085         }
17086     }
17087   else
17088     {
17089       switch (cu_header->addr_size)
17090         {
17091         case 2:
17092           retval = bfd_get_16 (abfd, buf);
17093           break;
17094         case 4:
17095           retval = bfd_get_32 (abfd, buf);
17096           break;
17097         case 8:
17098           retval = bfd_get_64 (abfd, buf);
17099           break;
17100         default:
17101           internal_error (__FILE__, __LINE__,
17102                           _("read_address: bad switch, "
17103                             "unsigned [in module %s]"),
17104                           bfd_get_filename (abfd));
17105         }
17106     }
17107
17108   *bytes_read = cu_header->addr_size;
17109   return retval;
17110 }
17111
17112 /* Read the initial length from a section.  The (draft) DWARF 3
17113    specification allows the initial length to take up either 4 bytes
17114    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17115    bytes describe the length and all offsets will be 8 bytes in length
17116    instead of 4.
17117
17118    An older, non-standard 64-bit format is also handled by this
17119    function.  The older format in question stores the initial length
17120    as an 8-byte quantity without an escape value.  Lengths greater
17121    than 2^32 aren't very common which means that the initial 4 bytes
17122    is almost always zero.  Since a length value of zero doesn't make
17123    sense for the 32-bit format, this initial zero can be considered to
17124    be an escape value which indicates the presence of the older 64-bit
17125    format.  As written, the code can't detect (old format) lengths
17126    greater than 4GB.  If it becomes necessary to handle lengths
17127    somewhat larger than 4GB, we could allow other small values (such
17128    as the non-sensical values of 1, 2, and 3) to also be used as
17129    escape values indicating the presence of the old format.
17130
17131    The value returned via bytes_read should be used to increment the
17132    relevant pointer after calling read_initial_length().
17133
17134    [ Note:  read_initial_length() and read_offset() are based on the
17135      document entitled "DWARF Debugging Information Format", revision
17136      3, draft 8, dated November 19, 2001.  This document was obtained
17137      from:
17138
17139         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17140
17141      This document is only a draft and is subject to change.  (So beware.)
17142
17143      Details regarding the older, non-standard 64-bit format were
17144      determined empirically by examining 64-bit ELF files produced by
17145      the SGI toolchain on an IRIX 6.5 machine.
17146
17147      - Kevin, July 16, 2002
17148    ] */
17149
17150 static LONGEST
17151 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17152 {
17153   LONGEST length = bfd_get_32 (abfd, buf);
17154
17155   if (length == 0xffffffff)
17156     {
17157       length = bfd_get_64 (abfd, buf + 4);
17158       *bytes_read = 12;
17159     }
17160   else if (length == 0)
17161     {
17162       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17163       length = bfd_get_64 (abfd, buf);
17164       *bytes_read = 8;
17165     }
17166   else
17167     {
17168       *bytes_read = 4;
17169     }
17170
17171   return length;
17172 }
17173
17174 /* Cover function for read_initial_length.
17175    Returns the length of the object at BUF, and stores the size of the
17176    initial length in *BYTES_READ and stores the size that offsets will be in
17177    *OFFSET_SIZE.
17178    If the initial length size is not equivalent to that specified in
17179    CU_HEADER then issue a complaint.
17180    This is useful when reading non-comp-unit headers.  */
17181
17182 static LONGEST
17183 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17184                                         const struct comp_unit_head *cu_header,
17185                                         unsigned int *bytes_read,
17186                                         unsigned int *offset_size)
17187 {
17188   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17189
17190   gdb_assert (cu_header->initial_length_size == 4
17191               || cu_header->initial_length_size == 8
17192               || cu_header->initial_length_size == 12);
17193
17194   if (cu_header->initial_length_size != *bytes_read)
17195     complaint (&symfile_complaints,
17196                _("intermixed 32-bit and 64-bit DWARF sections"));
17197
17198   *offset_size = (*bytes_read == 4) ? 4 : 8;
17199   return length;
17200 }
17201
17202 /* Read an offset from the data stream.  The size of the offset is
17203    given by cu_header->offset_size.  */
17204
17205 static LONGEST
17206 read_offset (bfd *abfd, const gdb_byte *buf,
17207              const struct comp_unit_head *cu_header,
17208              unsigned int *bytes_read)
17209 {
17210   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17211
17212   *bytes_read = cu_header->offset_size;
17213   return offset;
17214 }
17215
17216 /* Read an offset from the data stream.  */
17217
17218 static LONGEST
17219 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17220 {
17221   LONGEST retval = 0;
17222
17223   switch (offset_size)
17224     {
17225     case 4:
17226       retval = bfd_get_32 (abfd, buf);
17227       break;
17228     case 8:
17229       retval = bfd_get_64 (abfd, buf);
17230       break;
17231     default:
17232       internal_error (__FILE__, __LINE__,
17233                       _("read_offset_1: bad switch [in module %s]"),
17234                       bfd_get_filename (abfd));
17235     }
17236
17237   return retval;
17238 }
17239
17240 static const gdb_byte *
17241 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17242 {
17243   /* If the size of a host char is 8 bits, we can return a pointer
17244      to the buffer, otherwise we have to copy the data to a buffer
17245      allocated on the temporary obstack.  */
17246   gdb_assert (HOST_CHAR_BIT == 8);
17247   return buf;
17248 }
17249
17250 static const char *
17251 read_direct_string (bfd *abfd, const gdb_byte *buf,
17252                     unsigned int *bytes_read_ptr)
17253 {
17254   /* If the size of a host char is 8 bits, we can return a pointer
17255      to the string, otherwise we have to copy the string to a buffer
17256      allocated on the temporary obstack.  */
17257   gdb_assert (HOST_CHAR_BIT == 8);
17258   if (*buf == '\0')
17259     {
17260       *bytes_read_ptr = 1;
17261       return NULL;
17262     }
17263   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17264   return (const char *) buf;
17265 }
17266
17267 /* Return pointer to string at section SECT offset STR_OFFSET with error
17268    reporting strings FORM_NAME and SECT_NAME.  */
17269
17270 static const char *
17271 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17272                                      struct dwarf2_section_info *sect,
17273                                      const char *form_name,
17274                                      const char *sect_name)
17275 {
17276   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17277   if (sect->buffer == NULL)
17278     error (_("%s used without %s section [in module %s]"),
17279            form_name, sect_name, bfd_get_filename (abfd));
17280   if (str_offset >= sect->size)
17281     error (_("%s pointing outside of %s section [in module %s]"),
17282            form_name, sect_name, bfd_get_filename (abfd));
17283   gdb_assert (HOST_CHAR_BIT == 8);
17284   if (sect->buffer[str_offset] == '\0')
17285     return NULL;
17286   return (const char *) (sect->buffer + str_offset);
17287 }
17288
17289 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17290
17291 static const char *
17292 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17293 {
17294   return read_indirect_string_at_offset_from (abfd, str_offset,
17295                                               &dwarf2_per_objfile->str,
17296                                               "DW_FORM_strp", ".debug_str");
17297 }
17298
17299 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17300
17301 static const char *
17302 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17303 {
17304   return read_indirect_string_at_offset_from (abfd, str_offset,
17305                                               &dwarf2_per_objfile->line_str,
17306                                               "DW_FORM_line_strp",
17307                                               ".debug_line_str");
17308 }
17309
17310 /* Read a string at offset STR_OFFSET in the .debug_str section from
17311    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17312    the string consists of a single NUL byte, return NULL; otherwise
17313    return a pointer to the string.  */
17314
17315 static const char *
17316 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17317 {
17318   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17319
17320   if (dwz->str.buffer == NULL)
17321     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17322              "section [in module %s]"),
17323            bfd_get_filename (dwz->dwz_bfd));
17324   if (str_offset >= dwz->str.size)
17325     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17326              ".debug_str section [in module %s]"),
17327            bfd_get_filename (dwz->dwz_bfd));
17328   gdb_assert (HOST_CHAR_BIT == 8);
17329   if (dwz->str.buffer[str_offset] == '\0')
17330     return NULL;
17331   return (const char *) (dwz->str.buffer + str_offset);
17332 }
17333
17334 /* Return pointer to string at .debug_str offset as read from BUF.
17335    BUF is assumed to be in a compilation unit described by CU_HEADER.
17336    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17337
17338 static const char *
17339 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17340                       const struct comp_unit_head *cu_header,
17341                       unsigned int *bytes_read_ptr)
17342 {
17343   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17344
17345   return read_indirect_string_at_offset (abfd, str_offset);
17346 }
17347
17348 /* Return pointer to string at .debug_line_str offset as read from BUF.
17349    BUF is assumed to be in a compilation unit described by CU_HEADER.
17350    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17351
17352 static const char *
17353 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17354                            const struct comp_unit_head *cu_header,
17355                            unsigned int *bytes_read_ptr)
17356 {
17357   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17358
17359   return read_indirect_line_string_at_offset (abfd, str_offset);
17360 }
17361
17362 ULONGEST
17363 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17364                           unsigned int *bytes_read_ptr)
17365 {
17366   ULONGEST result;
17367   unsigned int num_read;
17368   int shift;
17369   unsigned char byte;
17370
17371   result = 0;
17372   shift = 0;
17373   num_read = 0;
17374   while (1)
17375     {
17376       byte = bfd_get_8 (abfd, buf);
17377       buf++;
17378       num_read++;
17379       result |= ((ULONGEST) (byte & 127) << shift);
17380       if ((byte & 128) == 0)
17381         {
17382           break;
17383         }
17384       shift += 7;
17385     }
17386   *bytes_read_ptr = num_read;
17387   return result;
17388 }
17389
17390 static LONGEST
17391 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17392                     unsigned int *bytes_read_ptr)
17393 {
17394   LONGEST result;
17395   int shift, num_read;
17396   unsigned char byte;
17397
17398   result = 0;
17399   shift = 0;
17400   num_read = 0;
17401   while (1)
17402     {
17403       byte = bfd_get_8 (abfd, buf);
17404       buf++;
17405       num_read++;
17406       result |= ((LONGEST) (byte & 127) << shift);
17407       shift += 7;
17408       if ((byte & 128) == 0)
17409         {
17410           break;
17411         }
17412     }
17413   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17414     result |= -(((LONGEST) 1) << shift);
17415   *bytes_read_ptr = num_read;
17416   return result;
17417 }
17418
17419 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17420    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17421    ADDR_SIZE is the size of addresses from the CU header.  */
17422
17423 static CORE_ADDR
17424 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17425 {
17426   struct objfile *objfile = dwarf2_per_objfile->objfile;
17427   bfd *abfd = objfile->obfd;
17428   const gdb_byte *info_ptr;
17429
17430   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17431   if (dwarf2_per_objfile->addr.buffer == NULL)
17432     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17433            objfile_name (objfile));
17434   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17435     error (_("DW_FORM_addr_index pointing outside of "
17436              ".debug_addr section [in module %s]"),
17437            objfile_name (objfile));
17438   info_ptr = (dwarf2_per_objfile->addr.buffer
17439               + addr_base + addr_index * addr_size);
17440   if (addr_size == 4)
17441     return bfd_get_32 (abfd, info_ptr);
17442   else
17443     return bfd_get_64 (abfd, info_ptr);
17444 }
17445
17446 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17447
17448 static CORE_ADDR
17449 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17450 {
17451   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17452 }
17453
17454 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17455
17456 static CORE_ADDR
17457 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17458                              unsigned int *bytes_read)
17459 {
17460   bfd *abfd = cu->objfile->obfd;
17461   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17462
17463   return read_addr_index (cu, addr_index);
17464 }
17465
17466 /* Data structure to pass results from dwarf2_read_addr_index_reader
17467    back to dwarf2_read_addr_index.  */
17468
17469 struct dwarf2_read_addr_index_data
17470 {
17471   ULONGEST addr_base;
17472   int addr_size;
17473 };
17474
17475 /* die_reader_func for dwarf2_read_addr_index.  */
17476
17477 static void
17478 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17479                                const gdb_byte *info_ptr,
17480                                struct die_info *comp_unit_die,
17481                                int has_children,
17482                                void *data)
17483 {
17484   struct dwarf2_cu *cu = reader->cu;
17485   struct dwarf2_read_addr_index_data *aidata =
17486     (struct dwarf2_read_addr_index_data *) data;
17487
17488   aidata->addr_base = cu->addr_base;
17489   aidata->addr_size = cu->header.addr_size;
17490 }
17491
17492 /* Given an index in .debug_addr, fetch the value.
17493    NOTE: This can be called during dwarf expression evaluation,
17494    long after the debug information has been read, and thus per_cu->cu
17495    may no longer exist.  */
17496
17497 CORE_ADDR
17498 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17499                         unsigned int addr_index)
17500 {
17501   struct objfile *objfile = per_cu->objfile;
17502   struct dwarf2_cu *cu = per_cu->cu;
17503   ULONGEST addr_base;
17504   int addr_size;
17505
17506   /* This is intended to be called from outside this file.  */
17507   dw2_setup (objfile);
17508
17509   /* We need addr_base and addr_size.
17510      If we don't have PER_CU->cu, we have to get it.
17511      Nasty, but the alternative is storing the needed info in PER_CU,
17512      which at this point doesn't seem justified: it's not clear how frequently
17513      it would get used and it would increase the size of every PER_CU.
17514      Entry points like dwarf2_per_cu_addr_size do a similar thing
17515      so we're not in uncharted territory here.
17516      Alas we need to be a bit more complicated as addr_base is contained
17517      in the DIE.
17518
17519      We don't need to read the entire CU(/TU).
17520      We just need the header and top level die.
17521
17522      IWBN to use the aging mechanism to let us lazily later discard the CU.
17523      For now we skip this optimization.  */
17524
17525   if (cu != NULL)
17526     {
17527       addr_base = cu->addr_base;
17528       addr_size = cu->header.addr_size;
17529     }
17530   else
17531     {
17532       struct dwarf2_read_addr_index_data aidata;
17533
17534       /* Note: We can't use init_cutu_and_read_dies_simple here,
17535          we need addr_base.  */
17536       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17537                                dwarf2_read_addr_index_reader, &aidata);
17538       addr_base = aidata.addr_base;
17539       addr_size = aidata.addr_size;
17540     }
17541
17542   return read_addr_index_1 (addr_index, addr_base, addr_size);
17543 }
17544
17545 /* Given a DW_FORM_GNU_str_index, fetch the string.
17546    This is only used by the Fission support.  */
17547
17548 static const char *
17549 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17550 {
17551   struct objfile *objfile = dwarf2_per_objfile->objfile;
17552   const char *objf_name = objfile_name (objfile);
17553   bfd *abfd = objfile->obfd;
17554   struct dwarf2_cu *cu = reader->cu;
17555   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17556   struct dwarf2_section_info *str_offsets_section =
17557     &reader->dwo_file->sections.str_offsets;
17558   const gdb_byte *info_ptr;
17559   ULONGEST str_offset;
17560   static const char form_name[] = "DW_FORM_GNU_str_index";
17561
17562   dwarf2_read_section (objfile, str_section);
17563   dwarf2_read_section (objfile, str_offsets_section);
17564   if (str_section->buffer == NULL)
17565     error (_("%s used without .debug_str.dwo section"
17566              " in CU at offset 0x%x [in module %s]"),
17567            form_name, to_underlying (cu->header.sect_off), objf_name);
17568   if (str_offsets_section->buffer == NULL)
17569     error (_("%s used without .debug_str_offsets.dwo section"
17570              " in CU at offset 0x%x [in module %s]"),
17571            form_name, to_underlying (cu->header.sect_off), objf_name);
17572   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17573     error (_("%s pointing outside of .debug_str_offsets.dwo"
17574              " section in CU at offset 0x%x [in module %s]"),
17575            form_name, to_underlying (cu->header.sect_off), objf_name);
17576   info_ptr = (str_offsets_section->buffer
17577               + str_index * cu->header.offset_size);
17578   if (cu->header.offset_size == 4)
17579     str_offset = bfd_get_32 (abfd, info_ptr);
17580   else
17581     str_offset = bfd_get_64 (abfd, info_ptr);
17582   if (str_offset >= str_section->size)
17583     error (_("Offset from %s pointing outside of"
17584              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17585            form_name, to_underlying (cu->header.sect_off), objf_name);
17586   return (const char *) (str_section->buffer + str_offset);
17587 }
17588
17589 /* Return the length of an LEB128 number in BUF.  */
17590
17591 static int
17592 leb128_size (const gdb_byte *buf)
17593 {
17594   const gdb_byte *begin = buf;
17595   gdb_byte byte;
17596
17597   while (1)
17598     {
17599       byte = *buf++;
17600       if ((byte & 128) == 0)
17601         return buf - begin;
17602     }
17603 }
17604
17605 static void
17606 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17607 {
17608   switch (lang)
17609     {
17610     case DW_LANG_C89:
17611     case DW_LANG_C99:
17612     case DW_LANG_C11:
17613     case DW_LANG_C:
17614     case DW_LANG_UPC:
17615       cu->language = language_c;
17616       break;
17617     case DW_LANG_Java:
17618     case DW_LANG_C_plus_plus:
17619     case DW_LANG_C_plus_plus_11:
17620     case DW_LANG_C_plus_plus_14:
17621       cu->language = language_cplus;
17622       break;
17623     case DW_LANG_D:
17624       cu->language = language_d;
17625       break;
17626     case DW_LANG_Fortran77:
17627     case DW_LANG_Fortran90:
17628     case DW_LANG_Fortran95:
17629     case DW_LANG_Fortran03:
17630     case DW_LANG_Fortran08:
17631       cu->language = language_fortran;
17632       break;
17633     case DW_LANG_Go:
17634       cu->language = language_go;
17635       break;
17636     case DW_LANG_Mips_Assembler:
17637       cu->language = language_asm;
17638       break;
17639     case DW_LANG_Ada83:
17640     case DW_LANG_Ada95:
17641       cu->language = language_ada;
17642       break;
17643     case DW_LANG_Modula2:
17644       cu->language = language_m2;
17645       break;
17646     case DW_LANG_Pascal83:
17647       cu->language = language_pascal;
17648       break;
17649     case DW_LANG_ObjC:
17650       cu->language = language_objc;
17651       break;
17652     case DW_LANG_Rust:
17653     case DW_LANG_Rust_old:
17654       cu->language = language_rust;
17655       break;
17656     case DW_LANG_Cobol74:
17657     case DW_LANG_Cobol85:
17658     default:
17659       cu->language = language_minimal;
17660       break;
17661     }
17662   cu->language_defn = language_def (cu->language);
17663 }
17664
17665 /* Return the named attribute or NULL if not there.  */
17666
17667 static struct attribute *
17668 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17669 {
17670   for (;;)
17671     {
17672       unsigned int i;
17673       struct attribute *spec = NULL;
17674
17675       for (i = 0; i < die->num_attrs; ++i)
17676         {
17677           if (die->attrs[i].name == name)
17678             return &die->attrs[i];
17679           if (die->attrs[i].name == DW_AT_specification
17680               || die->attrs[i].name == DW_AT_abstract_origin)
17681             spec = &die->attrs[i];
17682         }
17683
17684       if (!spec)
17685         break;
17686
17687       die = follow_die_ref (die, spec, &cu);
17688     }
17689
17690   return NULL;
17691 }
17692
17693 /* Return the named attribute or NULL if not there,
17694    but do not follow DW_AT_specification, etc.
17695    This is for use in contexts where we're reading .debug_types dies.
17696    Following DW_AT_specification, DW_AT_abstract_origin will take us
17697    back up the chain, and we want to go down.  */
17698
17699 static struct attribute *
17700 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17701 {
17702   unsigned int i;
17703
17704   for (i = 0; i < die->num_attrs; ++i)
17705     if (die->attrs[i].name == name)
17706       return &die->attrs[i];
17707
17708   return NULL;
17709 }
17710
17711 /* Return the string associated with a string-typed attribute, or NULL if it
17712    is either not found or is of an incorrect type.  */
17713
17714 static const char *
17715 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17716 {
17717   struct attribute *attr;
17718   const char *str = NULL;
17719
17720   attr = dwarf2_attr (die, name, cu);
17721
17722   if (attr != NULL)
17723     {
17724       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17725           || attr->form == DW_FORM_string
17726           || attr->form == DW_FORM_GNU_str_index
17727           || attr->form == DW_FORM_GNU_strp_alt)
17728         str = DW_STRING (attr);
17729       else
17730         complaint (&symfile_complaints,
17731                    _("string type expected for attribute %s for "
17732                      "DIE at 0x%x in module %s"),
17733                    dwarf_attr_name (name), to_underlying (die->sect_off),
17734                    objfile_name (cu->objfile));
17735     }
17736
17737   return str;
17738 }
17739
17740 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17741    and holds a non-zero value.  This function should only be used for
17742    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17743
17744 static int
17745 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17746 {
17747   struct attribute *attr = dwarf2_attr (die, name, cu);
17748
17749   return (attr && DW_UNSND (attr));
17750 }
17751
17752 static int
17753 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17754 {
17755   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17756      which value is non-zero.  However, we have to be careful with
17757      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17758      (via dwarf2_flag_true_p) follows this attribute.  So we may
17759      end up accidently finding a declaration attribute that belongs
17760      to a different DIE referenced by the specification attribute,
17761      even though the given DIE does not have a declaration attribute.  */
17762   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17763           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17764 }
17765
17766 /* Return the die giving the specification for DIE, if there is
17767    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17768    containing the return value on output.  If there is no
17769    specification, but there is an abstract origin, that is
17770    returned.  */
17771
17772 static struct die_info *
17773 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17774 {
17775   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17776                                              *spec_cu);
17777
17778   if (spec_attr == NULL)
17779     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17780
17781   if (spec_attr == NULL)
17782     return NULL;
17783   else
17784     return follow_die_ref (die, spec_attr, spec_cu);
17785 }
17786
17787 /* Stub for free_line_header to match void * callback types.  */
17788
17789 static void
17790 free_line_header_voidp (void *arg)
17791 {
17792   struct line_header *lh = (struct line_header *) arg;
17793
17794   delete lh;
17795 }
17796
17797 void
17798 line_header::add_include_dir (const char *include_dir)
17799 {
17800   if (dwarf_line_debug >= 2)
17801     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17802                         include_dirs.size () + 1, include_dir);
17803
17804   include_dirs.push_back (include_dir);
17805 }
17806
17807 void
17808 line_header::add_file_name (const char *name,
17809                             dir_index d_index,
17810                             unsigned int mod_time,
17811                             unsigned int length)
17812 {
17813   if (dwarf_line_debug >= 2)
17814     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17815                         (unsigned) file_names.size () + 1, name);
17816
17817   file_names.emplace_back (name, d_index, mod_time, length);
17818 }
17819
17820 /* A convenience function to find the proper .debug_line section for a CU.  */
17821
17822 static struct dwarf2_section_info *
17823 get_debug_line_section (struct dwarf2_cu *cu)
17824 {
17825   struct dwarf2_section_info *section;
17826
17827   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17828      DWO file.  */
17829   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17830     section = &cu->dwo_unit->dwo_file->sections.line;
17831   else if (cu->per_cu->is_dwz)
17832     {
17833       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17834
17835       section = &dwz->line;
17836     }
17837   else
17838     section = &dwarf2_per_objfile->line;
17839
17840   return section;
17841 }
17842
17843 /* Read directory or file name entry format, starting with byte of
17844    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17845    entries count and the entries themselves in the described entry
17846    format.  */
17847
17848 static void
17849 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17850                         struct line_header *lh,
17851                         const struct comp_unit_head *cu_header,
17852                         void (*callback) (struct line_header *lh,
17853                                           const char *name,
17854                                           dir_index d_index,
17855                                           unsigned int mod_time,
17856                                           unsigned int length))
17857 {
17858   gdb_byte format_count, formati;
17859   ULONGEST data_count, datai;
17860   const gdb_byte *buf = *bufp;
17861   const gdb_byte *format_header_data;
17862   int i;
17863   unsigned int bytes_read;
17864
17865   format_count = read_1_byte (abfd, buf);
17866   buf += 1;
17867   format_header_data = buf;
17868   for (formati = 0; formati < format_count; formati++)
17869     {
17870       read_unsigned_leb128 (abfd, buf, &bytes_read);
17871       buf += bytes_read;
17872       read_unsigned_leb128 (abfd, buf, &bytes_read);
17873       buf += bytes_read;
17874     }
17875
17876   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17877   buf += bytes_read;
17878   for (datai = 0; datai < data_count; datai++)
17879     {
17880       const gdb_byte *format = format_header_data;
17881       struct file_entry fe;
17882
17883       for (formati = 0; formati < format_count; formati++)
17884         {
17885           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17886           format += bytes_read;
17887
17888           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17889           format += bytes_read;
17890
17891           gdb::optional<const char *> string;
17892           gdb::optional<unsigned int> uint;
17893
17894           switch (form)
17895             {
17896             case DW_FORM_string:
17897               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17898               buf += bytes_read;
17899               break;
17900
17901             case DW_FORM_line_strp:
17902               string.emplace (read_indirect_line_string (abfd, buf,
17903                                                          cu_header,
17904                                                          &bytes_read));
17905               buf += bytes_read;
17906               break;
17907
17908             case DW_FORM_data1:
17909               uint.emplace (read_1_byte (abfd, buf));
17910               buf += 1;
17911               break;
17912
17913             case DW_FORM_data2:
17914               uint.emplace (read_2_bytes (abfd, buf));
17915               buf += 2;
17916               break;
17917
17918             case DW_FORM_data4:
17919               uint.emplace (read_4_bytes (abfd, buf));
17920               buf += 4;
17921               break;
17922
17923             case DW_FORM_data8:
17924               uint.emplace (read_8_bytes (abfd, buf));
17925               buf += 8;
17926               break;
17927
17928             case DW_FORM_udata:
17929               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17930               buf += bytes_read;
17931               break;
17932
17933             case DW_FORM_block:
17934               /* It is valid only for DW_LNCT_timestamp which is ignored by
17935                  current GDB.  */
17936               break;
17937             }
17938
17939           switch (content_type)
17940             {
17941             case DW_LNCT_path:
17942               if (string.has_value ())
17943                 fe.name = *string;
17944               break;
17945             case DW_LNCT_directory_index:
17946               if (uint.has_value ())
17947                 fe.d_index = (dir_index) *uint;
17948               break;
17949             case DW_LNCT_timestamp:
17950               if (uint.has_value ())
17951                 fe.mod_time = *uint;
17952               break;
17953             case DW_LNCT_size:
17954               if (uint.has_value ())
17955                 fe.length = *uint;
17956               break;
17957             case DW_LNCT_MD5:
17958               break;
17959             default:
17960               complaint (&symfile_complaints,
17961                          _("Unknown format content type %s"),
17962                          pulongest (content_type));
17963             }
17964         }
17965
17966       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17967     }
17968
17969   *bufp = buf;
17970 }
17971
17972 /* Read the statement program header starting at OFFSET in
17973    .debug_line, or .debug_line.dwo.  Return a pointer
17974    to a struct line_header, allocated using xmalloc.
17975    Returns NULL if there is a problem reading the header, e.g., if it
17976    has a version we don't understand.
17977
17978    NOTE: the strings in the include directory and file name tables of
17979    the returned object point into the dwarf line section buffer,
17980    and must not be freed.  */
17981
17982 static line_header_up
17983 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17984 {
17985   const gdb_byte *line_ptr;
17986   unsigned int bytes_read, offset_size;
17987   int i;
17988   const char *cur_dir, *cur_file;
17989   struct dwarf2_section_info *section;
17990   bfd *abfd;
17991
17992   section = get_debug_line_section (cu);
17993   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17994   if (section->buffer == NULL)
17995     {
17996       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17997         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17998       else
17999         complaint (&symfile_complaints, _("missing .debug_line section"));
18000       return 0;
18001     }
18002
18003   /* We can't do this until we know the section is non-empty.
18004      Only then do we know we have such a section.  */
18005   abfd = get_section_bfd_owner (section);
18006
18007   /* Make sure that at least there's room for the total_length field.
18008      That could be 12 bytes long, but we're just going to fudge that.  */
18009   if (to_underlying (sect_off) + 4 >= section->size)
18010     {
18011       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18012       return 0;
18013     }
18014
18015   line_header_up lh (new line_header ());
18016
18017   lh->sect_off = sect_off;
18018   lh->offset_in_dwz = cu->per_cu->is_dwz;
18019
18020   line_ptr = section->buffer + to_underlying (sect_off);
18021
18022   /* Read in the header.  */
18023   lh->total_length =
18024     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18025                                             &bytes_read, &offset_size);
18026   line_ptr += bytes_read;
18027   if (line_ptr + lh->total_length > (section->buffer + section->size))
18028     {
18029       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18030       return 0;
18031     }
18032   lh->statement_program_end = line_ptr + lh->total_length;
18033   lh->version = read_2_bytes (abfd, line_ptr);
18034   line_ptr += 2;
18035   if (lh->version > 5)
18036     {
18037       /* This is a version we don't understand.  The format could have
18038          changed in ways we don't handle properly so just punt.  */
18039       complaint (&symfile_complaints,
18040                  _("unsupported version in .debug_line section"));
18041       return NULL;
18042     }
18043   if (lh->version >= 5)
18044     {
18045       gdb_byte segment_selector_size;
18046
18047       /* Skip address size.  */
18048       read_1_byte (abfd, line_ptr);
18049       line_ptr += 1;
18050
18051       segment_selector_size = read_1_byte (abfd, line_ptr);
18052       line_ptr += 1;
18053       if (segment_selector_size != 0)
18054         {
18055           complaint (&symfile_complaints,
18056                      _("unsupported segment selector size %u "
18057                        "in .debug_line section"),
18058                      segment_selector_size);
18059           return NULL;
18060         }
18061     }
18062   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18063   line_ptr += offset_size;
18064   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18065   line_ptr += 1;
18066   if (lh->version >= 4)
18067     {
18068       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18069       line_ptr += 1;
18070     }
18071   else
18072     lh->maximum_ops_per_instruction = 1;
18073
18074   if (lh->maximum_ops_per_instruction == 0)
18075     {
18076       lh->maximum_ops_per_instruction = 1;
18077       complaint (&symfile_complaints,
18078                  _("invalid maximum_ops_per_instruction "
18079                    "in `.debug_line' section"));
18080     }
18081
18082   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18083   line_ptr += 1;
18084   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18085   line_ptr += 1;
18086   lh->line_range = read_1_byte (abfd, line_ptr);
18087   line_ptr += 1;
18088   lh->opcode_base = read_1_byte (abfd, line_ptr);
18089   line_ptr += 1;
18090   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18091
18092   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18093   for (i = 1; i < lh->opcode_base; ++i)
18094     {
18095       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18096       line_ptr += 1;
18097     }
18098
18099   if (lh->version >= 5)
18100     {
18101       /* Read directory table.  */
18102       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18103                               [] (struct line_header *lh, const char *name,
18104                                   dir_index d_index, unsigned int mod_time,
18105                                   unsigned int length)
18106         {
18107           lh->add_include_dir (name);
18108         });
18109
18110       /* Read file name table.  */
18111       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18112                               [] (struct line_header *lh, const char *name,
18113                                   dir_index d_index, unsigned int mod_time,
18114                                   unsigned int length)
18115         {
18116           lh->add_file_name (name, d_index, mod_time, length);
18117         });
18118     }
18119   else
18120     {
18121       /* Read directory table.  */
18122       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18123         {
18124           line_ptr += bytes_read;
18125           lh->add_include_dir (cur_dir);
18126         }
18127       line_ptr += bytes_read;
18128
18129       /* Read file name table.  */
18130       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18131         {
18132           unsigned int mod_time, length;
18133           dir_index d_index;
18134
18135           line_ptr += bytes_read;
18136           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18137           line_ptr += bytes_read;
18138           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18139           line_ptr += bytes_read;
18140           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18141           line_ptr += bytes_read;
18142
18143           lh->add_file_name (cur_file, d_index, mod_time, length);
18144         }
18145       line_ptr += bytes_read;
18146     }
18147   lh->statement_program_start = line_ptr;
18148
18149   if (line_ptr > (section->buffer + section->size))
18150     complaint (&symfile_complaints,
18151                _("line number info header doesn't "
18152                  "fit in `.debug_line' section"));
18153
18154   return lh;
18155 }
18156
18157 /* Subroutine of dwarf_decode_lines to simplify it.
18158    Return the file name of the psymtab for included file FILE_INDEX
18159    in line header LH of PST.
18160    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18161    If space for the result is malloc'd, it will be freed by a cleanup.
18162    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18163
18164    The function creates dangling cleanup registration.  */
18165
18166 static const char *
18167 psymtab_include_file_name (const struct line_header *lh, int file_index,
18168                            const struct partial_symtab *pst,
18169                            const char *comp_dir)
18170 {
18171   const file_entry &fe = lh->file_names[file_index];
18172   const char *include_name = fe.name;
18173   const char *include_name_to_compare = include_name;
18174   const char *pst_filename;
18175   char *copied_name = NULL;
18176   int file_is_pst;
18177
18178   const char *dir_name = fe.include_dir (lh);
18179
18180   if (!IS_ABSOLUTE_PATH (include_name)
18181       && (dir_name != NULL || comp_dir != NULL))
18182     {
18183       /* Avoid creating a duplicate psymtab for PST.
18184          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18185          Before we do the comparison, however, we need to account
18186          for DIR_NAME and COMP_DIR.
18187          First prepend dir_name (if non-NULL).  If we still don't
18188          have an absolute path prepend comp_dir (if non-NULL).
18189          However, the directory we record in the include-file's
18190          psymtab does not contain COMP_DIR (to match the
18191          corresponding symtab(s)).
18192
18193          Example:
18194
18195          bash$ cd /tmp
18196          bash$ gcc -g ./hello.c
18197          include_name = "hello.c"
18198          dir_name = "."
18199          DW_AT_comp_dir = comp_dir = "/tmp"
18200          DW_AT_name = "./hello.c"
18201
18202       */
18203
18204       if (dir_name != NULL)
18205         {
18206           char *tem = concat (dir_name, SLASH_STRING,
18207                               include_name, (char *)NULL);
18208
18209           make_cleanup (xfree, tem);
18210           include_name = tem;
18211           include_name_to_compare = include_name;
18212         }
18213       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18214         {
18215           char *tem = concat (comp_dir, SLASH_STRING,
18216                               include_name, (char *)NULL);
18217
18218           make_cleanup (xfree, tem);
18219           include_name_to_compare = tem;
18220         }
18221     }
18222
18223   pst_filename = pst->filename;
18224   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18225     {
18226       copied_name = concat (pst->dirname, SLASH_STRING,
18227                             pst_filename, (char *)NULL);
18228       pst_filename = copied_name;
18229     }
18230
18231   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18232
18233   if (copied_name != NULL)
18234     xfree (copied_name);
18235
18236   if (file_is_pst)
18237     return NULL;
18238   return include_name;
18239 }
18240
18241 /* State machine to track the state of the line number program.  */
18242
18243 class lnp_state_machine
18244 {
18245 public:
18246   /* Initialize a machine state for the start of a line number
18247      program.  */
18248   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18249
18250   file_entry *current_file ()
18251   {
18252     /* lh->file_names is 0-based, but the file name numbers in the
18253        statement program are 1-based.  */
18254     return m_line_header->file_name_at (m_file);
18255   }
18256
18257   /* Record the line in the state machine.  END_SEQUENCE is true if
18258      we're processing the end of a sequence.  */
18259   void record_line (bool end_sequence);
18260
18261   /* Check address and if invalid nop-out the rest of the lines in this
18262      sequence.  */
18263   void check_line_address (struct dwarf2_cu *cu,
18264                            const gdb_byte *line_ptr,
18265                            CORE_ADDR lowpc, CORE_ADDR address);
18266
18267   void handle_set_discriminator (unsigned int discriminator)
18268   {
18269     m_discriminator = discriminator;
18270     m_line_has_non_zero_discriminator |= discriminator != 0;
18271   }
18272
18273   /* Handle DW_LNE_set_address.  */
18274   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18275   {
18276     m_op_index = 0;
18277     address += baseaddr;
18278     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18279   }
18280
18281   /* Handle DW_LNS_advance_pc.  */
18282   void handle_advance_pc (CORE_ADDR adjust);
18283
18284   /* Handle a special opcode.  */
18285   void handle_special_opcode (unsigned char op_code);
18286
18287   /* Handle DW_LNS_advance_line.  */
18288   void handle_advance_line (int line_delta)
18289   {
18290     advance_line (line_delta);
18291   }
18292
18293   /* Handle DW_LNS_set_file.  */
18294   void handle_set_file (file_name_index file);
18295
18296   /* Handle DW_LNS_negate_stmt.  */
18297   void handle_negate_stmt ()
18298   {
18299     m_is_stmt = !m_is_stmt;
18300   }
18301
18302   /* Handle DW_LNS_const_add_pc.  */
18303   void handle_const_add_pc ();
18304
18305   /* Handle DW_LNS_fixed_advance_pc.  */
18306   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18307   {
18308     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18309     m_op_index = 0;
18310   }
18311
18312   /* Handle DW_LNS_copy.  */
18313   void handle_copy ()
18314   {
18315     record_line (false);
18316     m_discriminator = 0;
18317   }
18318
18319   /* Handle DW_LNE_end_sequence.  */
18320   void handle_end_sequence ()
18321   {
18322     m_record_line_callback = ::record_line;
18323   }
18324
18325 private:
18326   /* Advance the line by LINE_DELTA.  */
18327   void advance_line (int line_delta)
18328   {
18329     m_line += line_delta;
18330
18331     if (line_delta != 0)
18332       m_line_has_non_zero_discriminator = m_discriminator != 0;
18333   }
18334
18335   gdbarch *m_gdbarch;
18336
18337   /* True if we're recording lines.
18338      Otherwise we're building partial symtabs and are just interested in
18339      finding include files mentioned by the line number program.  */
18340   bool m_record_lines_p;
18341
18342   /* The line number header.  */
18343   line_header *m_line_header;
18344
18345   /* These are part of the standard DWARF line number state machine,
18346      and initialized according to the DWARF spec.  */
18347
18348   unsigned char m_op_index = 0;
18349   /* The line table index (1-based) of the current file.  */
18350   file_name_index m_file = (file_name_index) 1;
18351   unsigned int m_line = 1;
18352
18353   /* These are initialized in the constructor.  */
18354
18355   CORE_ADDR m_address;
18356   bool m_is_stmt;
18357   unsigned int m_discriminator;
18358
18359   /* Additional bits of state we need to track.  */
18360
18361   /* The last file that we called dwarf2_start_subfile for.
18362      This is only used for TLLs.  */
18363   unsigned int m_last_file = 0;
18364   /* The last file a line number was recorded for.  */
18365   struct subfile *m_last_subfile = NULL;
18366
18367   /* The function to call to record a line.  */
18368   record_line_ftype *m_record_line_callback = NULL;
18369
18370   /* The last line number that was recorded, used to coalesce
18371      consecutive entries for the same line.  This can happen, for
18372      example, when discriminators are present.  PR 17276.  */
18373   unsigned int m_last_line = 0;
18374   bool m_line_has_non_zero_discriminator = false;
18375 };
18376
18377 void
18378 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18379 {
18380   CORE_ADDR addr_adj = (((m_op_index + adjust)
18381                          / m_line_header->maximum_ops_per_instruction)
18382                         * m_line_header->minimum_instruction_length);
18383   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18384   m_op_index = ((m_op_index + adjust)
18385                 % m_line_header->maximum_ops_per_instruction);
18386 }
18387
18388 void
18389 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18390 {
18391   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18392   CORE_ADDR addr_adj = (((m_op_index
18393                           + (adj_opcode / m_line_header->line_range))
18394                          / m_line_header->maximum_ops_per_instruction)
18395                         * m_line_header->minimum_instruction_length);
18396   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18397   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18398                 % m_line_header->maximum_ops_per_instruction);
18399
18400   int line_delta = (m_line_header->line_base
18401                     + (adj_opcode % m_line_header->line_range));
18402   advance_line (line_delta);
18403   record_line (false);
18404   m_discriminator = 0;
18405 }
18406
18407 void
18408 lnp_state_machine::handle_set_file (file_name_index file)
18409 {
18410   m_file = file;
18411
18412   const file_entry *fe = current_file ();
18413   if (fe == NULL)
18414     dwarf2_debug_line_missing_file_complaint ();
18415   else if (m_record_lines_p)
18416     {
18417       const char *dir = fe->include_dir (m_line_header);
18418
18419       m_last_subfile = current_subfile;
18420       m_line_has_non_zero_discriminator = m_discriminator != 0;
18421       dwarf2_start_subfile (fe->name, dir);
18422     }
18423 }
18424
18425 void
18426 lnp_state_machine::handle_const_add_pc ()
18427 {
18428   CORE_ADDR adjust
18429     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18430
18431   CORE_ADDR addr_adj
18432     = (((m_op_index + adjust)
18433         / m_line_header->maximum_ops_per_instruction)
18434        * m_line_header->minimum_instruction_length);
18435
18436   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18437   m_op_index = ((m_op_index + adjust)
18438                 % m_line_header->maximum_ops_per_instruction);
18439 }
18440
18441 /* Ignore this record_line request.  */
18442
18443 static void
18444 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18445 {
18446   return;
18447 }
18448
18449 /* Return non-zero if we should add LINE to the line number table.
18450    LINE is the line to add, LAST_LINE is the last line that was added,
18451    LAST_SUBFILE is the subfile for LAST_LINE.
18452    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18453    had a non-zero discriminator.
18454
18455    We have to be careful in the presence of discriminators.
18456    E.g., for this line:
18457
18458      for (i = 0; i < 100000; i++);
18459
18460    clang can emit four line number entries for that one line,
18461    each with a different discriminator.
18462    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18463
18464    However, we want gdb to coalesce all four entries into one.
18465    Otherwise the user could stepi into the middle of the line and
18466    gdb would get confused about whether the pc really was in the
18467    middle of the line.
18468
18469    Things are further complicated by the fact that two consecutive
18470    line number entries for the same line is a heuristic used by gcc
18471    to denote the end of the prologue.  So we can't just discard duplicate
18472    entries, we have to be selective about it.  The heuristic we use is
18473    that we only collapse consecutive entries for the same line if at least
18474    one of those entries has a non-zero discriminator.  PR 17276.
18475
18476    Note: Addresses in the line number state machine can never go backwards
18477    within one sequence, thus this coalescing is ok.  */
18478
18479 static int
18480 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18481                      int line_has_non_zero_discriminator,
18482                      struct subfile *last_subfile)
18483 {
18484   if (current_subfile != last_subfile)
18485     return 1;
18486   if (line != last_line)
18487     return 1;
18488   /* Same line for the same file that we've seen already.
18489      As a last check, for pr 17276, only record the line if the line
18490      has never had a non-zero discriminator.  */
18491   if (!line_has_non_zero_discriminator)
18492     return 1;
18493   return 0;
18494 }
18495
18496 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18497    in the line table of subfile SUBFILE.  */
18498
18499 static void
18500 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18501                      unsigned int line, CORE_ADDR address,
18502                      record_line_ftype p_record_line)
18503 {
18504   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18505
18506   if (dwarf_line_debug)
18507     {
18508       fprintf_unfiltered (gdb_stdlog,
18509                           "Recording line %u, file %s, address %s\n",
18510                           line, lbasename (subfile->name),
18511                           paddress (gdbarch, address));
18512     }
18513
18514   (*p_record_line) (subfile, line, addr);
18515 }
18516
18517 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18518    Mark the end of a set of line number records.
18519    The arguments are the same as for dwarf_record_line_1.
18520    If SUBFILE is NULL the request is ignored.  */
18521
18522 static void
18523 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18524                    CORE_ADDR address, record_line_ftype p_record_line)
18525 {
18526   if (subfile == NULL)
18527     return;
18528
18529   if (dwarf_line_debug)
18530     {
18531       fprintf_unfiltered (gdb_stdlog,
18532                           "Finishing current line, file %s, address %s\n",
18533                           lbasename (subfile->name),
18534                           paddress (gdbarch, address));
18535     }
18536
18537   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18538 }
18539
18540 void
18541 lnp_state_machine::record_line (bool end_sequence)
18542 {
18543   if (dwarf_line_debug)
18544     {
18545       fprintf_unfiltered (gdb_stdlog,
18546                           "Processing actual line %u: file %u,"
18547                           " address %s, is_stmt %u, discrim %u\n",
18548                           m_line, to_underlying (m_file),
18549                           paddress (m_gdbarch, m_address),
18550                           m_is_stmt, m_discriminator);
18551     }
18552
18553   file_entry *fe = current_file ();
18554
18555   if (fe == NULL)
18556     dwarf2_debug_line_missing_file_complaint ();
18557   /* For now we ignore lines not starting on an instruction boundary.
18558      But not when processing end_sequence for compatibility with the
18559      previous version of the code.  */
18560   else if (m_op_index == 0 || end_sequence)
18561     {
18562       fe->included_p = 1;
18563       if (m_record_lines_p && m_is_stmt)
18564         {
18565           if (m_last_subfile != current_subfile || end_sequence)
18566             {
18567               dwarf_finish_line (m_gdbarch, m_last_subfile,
18568                                  m_address, m_record_line_callback);
18569             }
18570
18571           if (!end_sequence)
18572             {
18573               if (dwarf_record_line_p (m_line, m_last_line,
18574                                        m_line_has_non_zero_discriminator,
18575                                        m_last_subfile))
18576                 {
18577                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18578                                        m_line, m_address,
18579                                        m_record_line_callback);
18580                 }
18581               m_last_subfile = current_subfile;
18582               m_last_line = m_line;
18583             }
18584         }
18585     }
18586 }
18587
18588 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18589                                       bool record_lines_p)
18590 {
18591   m_gdbarch = arch;
18592   m_record_lines_p = record_lines_p;
18593   m_line_header = lh;
18594
18595   m_record_line_callback = ::record_line;
18596
18597   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18598      was a line entry for it so that the backend has a chance to adjust it
18599      and also record it in case it needs it.  This is currently used by MIPS
18600      code, cf. `mips_adjust_dwarf2_line'.  */
18601   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18602   m_is_stmt = lh->default_is_stmt;
18603   m_discriminator = 0;
18604 }
18605
18606 void
18607 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18608                                        const gdb_byte *line_ptr,
18609                                        CORE_ADDR lowpc, CORE_ADDR address)
18610 {
18611   /* If address < lowpc then it's not a usable value, it's outside the
18612      pc range of the CU.  However, we restrict the test to only address
18613      values of zero to preserve GDB's previous behaviour which is to
18614      handle the specific case of a function being GC'd by the linker.  */
18615
18616   if (address == 0 && address < lowpc)
18617     {
18618       /* This line table is for a function which has been
18619          GCd by the linker.  Ignore it.  PR gdb/12528 */
18620
18621       struct objfile *objfile = cu->objfile;
18622       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18623
18624       complaint (&symfile_complaints,
18625                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18626                  line_offset, objfile_name (objfile));
18627       m_record_line_callback = noop_record_line;
18628       /* Note: record_line_callback is left as noop_record_line until
18629          we see DW_LNE_end_sequence.  */
18630     }
18631 }
18632
18633 /* Subroutine of dwarf_decode_lines to simplify it.
18634    Process the line number information in LH.
18635    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18636    program in order to set included_p for every referenced header.  */
18637
18638 static void
18639 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18640                       const int decode_for_pst_p, CORE_ADDR lowpc)
18641 {
18642   const gdb_byte *line_ptr, *extended_end;
18643   const gdb_byte *line_end;
18644   unsigned int bytes_read, extended_len;
18645   unsigned char op_code, extended_op;
18646   CORE_ADDR baseaddr;
18647   struct objfile *objfile = cu->objfile;
18648   bfd *abfd = objfile->obfd;
18649   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18650   /* True if we're recording line info (as opposed to building partial
18651      symtabs and just interested in finding include files mentioned by
18652      the line number program).  */
18653   bool record_lines_p = !decode_for_pst_p;
18654
18655   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18656
18657   line_ptr = lh->statement_program_start;
18658   line_end = lh->statement_program_end;
18659
18660   /* Read the statement sequences until there's nothing left.  */
18661   while (line_ptr < line_end)
18662     {
18663       /* The DWARF line number program state machine.  Reset the state
18664          machine at the start of each sequence.  */
18665       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18666       bool end_sequence = false;
18667
18668       if (record_lines_p)
18669         {
18670           /* Start a subfile for the current file of the state
18671              machine.  */
18672           const file_entry *fe = state_machine.current_file ();
18673
18674           if (fe != NULL)
18675             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18676         }
18677
18678       /* Decode the table.  */
18679       while (line_ptr < line_end && !end_sequence)
18680         {
18681           op_code = read_1_byte (abfd, line_ptr);
18682           line_ptr += 1;
18683
18684           if (op_code >= lh->opcode_base)
18685             {
18686               /* Special opcode.  */
18687               state_machine.handle_special_opcode (op_code);
18688             }
18689           else switch (op_code)
18690             {
18691             case DW_LNS_extended_op:
18692               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18693                                                    &bytes_read);
18694               line_ptr += bytes_read;
18695               extended_end = line_ptr + extended_len;
18696               extended_op = read_1_byte (abfd, line_ptr);
18697               line_ptr += 1;
18698               switch (extended_op)
18699                 {
18700                 case DW_LNE_end_sequence:
18701                   state_machine.handle_end_sequence ();
18702                   end_sequence = true;
18703                   break;
18704                 case DW_LNE_set_address:
18705                   {
18706                     CORE_ADDR address
18707                       = read_address (abfd, line_ptr, cu, &bytes_read);
18708                     line_ptr += bytes_read;
18709
18710                     state_machine.check_line_address (cu, line_ptr,
18711                                                       lowpc, address);
18712                     state_machine.handle_set_address (baseaddr, address);
18713                   }
18714                   break;
18715                 case DW_LNE_define_file:
18716                   {
18717                     const char *cur_file;
18718                     unsigned int mod_time, length;
18719                     dir_index dindex;
18720
18721                     cur_file = read_direct_string (abfd, line_ptr,
18722                                                    &bytes_read);
18723                     line_ptr += bytes_read;
18724                     dindex = (dir_index)
18725                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18726                     line_ptr += bytes_read;
18727                     mod_time =
18728                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18729                     line_ptr += bytes_read;
18730                     length =
18731                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18732                     line_ptr += bytes_read;
18733                     lh->add_file_name (cur_file, dindex, mod_time, length);
18734                   }
18735                   break;
18736                 case DW_LNE_set_discriminator:
18737                   {
18738                     /* The discriminator is not interesting to the
18739                        debugger; just ignore it.  We still need to
18740                        check its value though:
18741                        if there are consecutive entries for the same
18742                        (non-prologue) line we want to coalesce them.
18743                        PR 17276.  */
18744                     unsigned int discr
18745                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18746                     line_ptr += bytes_read;
18747
18748                     state_machine.handle_set_discriminator (discr);
18749                   }
18750                   break;
18751                 default:
18752                   complaint (&symfile_complaints,
18753                              _("mangled .debug_line section"));
18754                   return;
18755                 }
18756               /* Make sure that we parsed the extended op correctly.  If e.g.
18757                  we expected a different address size than the producer used,
18758                  we may have read the wrong number of bytes.  */
18759               if (line_ptr != extended_end)
18760                 {
18761                   complaint (&symfile_complaints,
18762                              _("mangled .debug_line section"));
18763                   return;
18764                 }
18765               break;
18766             case DW_LNS_copy:
18767               state_machine.handle_copy ();
18768               break;
18769             case DW_LNS_advance_pc:
18770               {
18771                 CORE_ADDR adjust
18772                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18773                 line_ptr += bytes_read;
18774
18775                 state_machine.handle_advance_pc (adjust);
18776               }
18777               break;
18778             case DW_LNS_advance_line:
18779               {
18780                 int line_delta
18781                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18782                 line_ptr += bytes_read;
18783
18784                 state_machine.handle_advance_line (line_delta);
18785               }
18786               break;
18787             case DW_LNS_set_file:
18788               {
18789                 file_name_index file
18790                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18791                                                             &bytes_read);
18792                 line_ptr += bytes_read;
18793
18794                 state_machine.handle_set_file (file);
18795               }
18796               break;
18797             case DW_LNS_set_column:
18798               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18799               line_ptr += bytes_read;
18800               break;
18801             case DW_LNS_negate_stmt:
18802               state_machine.handle_negate_stmt ();
18803               break;
18804             case DW_LNS_set_basic_block:
18805               break;
18806             /* Add to the address register of the state machine the
18807                address increment value corresponding to special opcode
18808                255.  I.e., this value is scaled by the minimum
18809                instruction length since special opcode 255 would have
18810                scaled the increment.  */
18811             case DW_LNS_const_add_pc:
18812               state_machine.handle_const_add_pc ();
18813               break;
18814             case DW_LNS_fixed_advance_pc:
18815               {
18816                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18817                 line_ptr += 2;
18818
18819                 state_machine.handle_fixed_advance_pc (addr_adj);
18820               }
18821               break;
18822             default:
18823               {
18824                 /* Unknown standard opcode, ignore it.  */
18825                 int i;
18826
18827                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18828                   {
18829                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18830                     line_ptr += bytes_read;
18831                   }
18832               }
18833             }
18834         }
18835
18836       if (!end_sequence)
18837         dwarf2_debug_line_missing_end_sequence_complaint ();
18838
18839       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18840          in which case we still finish recording the last line).  */
18841       state_machine.record_line (true);
18842     }
18843 }
18844
18845 /* Decode the Line Number Program (LNP) for the given line_header
18846    structure and CU.  The actual information extracted and the type
18847    of structures created from the LNP depends on the value of PST.
18848
18849    1. If PST is NULL, then this procedure uses the data from the program
18850       to create all necessary symbol tables, and their linetables.
18851
18852    2. If PST is not NULL, this procedure reads the program to determine
18853       the list of files included by the unit represented by PST, and
18854       builds all the associated partial symbol tables.
18855
18856    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18857    It is used for relative paths in the line table.
18858    NOTE: When processing partial symtabs (pst != NULL),
18859    comp_dir == pst->dirname.
18860
18861    NOTE: It is important that psymtabs have the same file name (via strcmp)
18862    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18863    symtab we don't use it in the name of the psymtabs we create.
18864    E.g. expand_line_sal requires this when finding psymtabs to expand.
18865    A good testcase for this is mb-inline.exp.
18866
18867    LOWPC is the lowest address in CU (or 0 if not known).
18868
18869    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18870    for its PC<->lines mapping information.  Otherwise only the filename
18871    table is read in.  */
18872
18873 static void
18874 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18875                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18876                     CORE_ADDR lowpc, int decode_mapping)
18877 {
18878   struct objfile *objfile = cu->objfile;
18879   const int decode_for_pst_p = (pst != NULL);
18880
18881   if (decode_mapping)
18882     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18883
18884   if (decode_for_pst_p)
18885     {
18886       int file_index;
18887
18888       /* Now that we're done scanning the Line Header Program, we can
18889          create the psymtab of each included file.  */
18890       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18891         if (lh->file_names[file_index].included_p == 1)
18892           {
18893             const char *include_name =
18894               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18895             if (include_name != NULL)
18896               dwarf2_create_include_psymtab (include_name, pst, objfile);
18897           }
18898     }
18899   else
18900     {
18901       /* Make sure a symtab is created for every file, even files
18902          which contain only variables (i.e. no code with associated
18903          line numbers).  */
18904       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18905       int i;
18906
18907       for (i = 0; i < lh->file_names.size (); i++)
18908         {
18909           file_entry &fe = lh->file_names[i];
18910
18911           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18912
18913           if (current_subfile->symtab == NULL)
18914             {
18915               current_subfile->symtab
18916                 = allocate_symtab (cust, current_subfile->name);
18917             }
18918           fe.symtab = current_subfile->symtab;
18919         }
18920     }
18921 }
18922
18923 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18924    DIRNAME the name of the source directory which contains FILENAME
18925    or NULL if not known.
18926    This routine tries to keep line numbers from identical absolute and
18927    relative file names in a common subfile.
18928
18929    Using the `list' example from the GDB testsuite, which resides in
18930    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18931    of /srcdir/list0.c yields the following debugging information for list0.c:
18932
18933    DW_AT_name:          /srcdir/list0.c
18934    DW_AT_comp_dir:      /compdir
18935    files.files[0].name: list0.h
18936    files.files[0].dir:  /srcdir
18937    files.files[1].name: list0.c
18938    files.files[1].dir:  /srcdir
18939
18940    The line number information for list0.c has to end up in a single
18941    subfile, so that `break /srcdir/list0.c:1' works as expected.
18942    start_subfile will ensure that this happens provided that we pass the
18943    concatenation of files.files[1].dir and files.files[1].name as the
18944    subfile's name.  */
18945
18946 static void
18947 dwarf2_start_subfile (const char *filename, const char *dirname)
18948 {
18949   char *copy = NULL;
18950
18951   /* In order not to lose the line information directory,
18952      we concatenate it to the filename when it makes sense.
18953      Note that the Dwarf3 standard says (speaking of filenames in line
18954      information): ``The directory index is ignored for file names
18955      that represent full path names''.  Thus ignoring dirname in the
18956      `else' branch below isn't an issue.  */
18957
18958   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18959     {
18960       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18961       filename = copy;
18962     }
18963
18964   start_subfile (filename);
18965
18966   if (copy != NULL)
18967     xfree (copy);
18968 }
18969
18970 /* Start a symtab for DWARF.
18971    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18972
18973 static struct compunit_symtab *
18974 dwarf2_start_symtab (struct dwarf2_cu *cu,
18975                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18976 {
18977   struct compunit_symtab *cust
18978     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18979
18980   record_debugformat ("DWARF 2");
18981   record_producer (cu->producer);
18982
18983   /* We assume that we're processing GCC output.  */
18984   processing_gcc_compilation = 2;
18985
18986   cu->processing_has_namespace_info = 0;
18987
18988   return cust;
18989 }
18990
18991 static void
18992 var_decode_location (struct attribute *attr, struct symbol *sym,
18993                      struct dwarf2_cu *cu)
18994 {
18995   struct objfile *objfile = cu->objfile;
18996   struct comp_unit_head *cu_header = &cu->header;
18997
18998   /* NOTE drow/2003-01-30: There used to be a comment and some special
18999      code here to turn a symbol with DW_AT_external and a
19000      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19001      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19002      with some versions of binutils) where shared libraries could have
19003      relocations against symbols in their debug information - the
19004      minimal symbol would have the right address, but the debug info
19005      would not.  It's no longer necessary, because we will explicitly
19006      apply relocations when we read in the debug information now.  */
19007
19008   /* A DW_AT_location attribute with no contents indicates that a
19009      variable has been optimized away.  */
19010   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19011     {
19012       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19013       return;
19014     }
19015
19016   /* Handle one degenerate form of location expression specially, to
19017      preserve GDB's previous behavior when section offsets are
19018      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19019      then mark this symbol as LOC_STATIC.  */
19020
19021   if (attr_form_is_block (attr)
19022       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19023            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19024           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19025               && (DW_BLOCK (attr)->size
19026                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19027     {
19028       unsigned int dummy;
19029
19030       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19031         SYMBOL_VALUE_ADDRESS (sym) =
19032           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19033       else
19034         SYMBOL_VALUE_ADDRESS (sym) =
19035           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19036       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19037       fixup_symbol_section (sym, objfile);
19038       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19039                                               SYMBOL_SECTION (sym));
19040       return;
19041     }
19042
19043   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19044      expression evaluator, and use LOC_COMPUTED only when necessary
19045      (i.e. when the value of a register or memory location is
19046      referenced, or a thread-local block, etc.).  Then again, it might
19047      not be worthwhile.  I'm assuming that it isn't unless performance
19048      or memory numbers show me otherwise.  */
19049
19050   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19051
19052   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19053     cu->has_loclist = 1;
19054 }
19055
19056 /* Given a pointer to a DWARF information entry, figure out if we need
19057    to make a symbol table entry for it, and if so, create a new entry
19058    and return a pointer to it.
19059    If TYPE is NULL, determine symbol type from the die, otherwise
19060    used the passed type.
19061    If SPACE is not NULL, use it to hold the new symbol.  If it is
19062    NULL, allocate a new symbol on the objfile's obstack.  */
19063
19064 static struct symbol *
19065 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19066                  struct symbol *space)
19067 {
19068   struct objfile *objfile = cu->objfile;
19069   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19070   struct symbol *sym = NULL;
19071   const char *name;
19072   struct attribute *attr = NULL;
19073   struct attribute *attr2 = NULL;
19074   CORE_ADDR baseaddr;
19075   struct pending **list_to_add = NULL;
19076
19077   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19078
19079   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19080
19081   name = dwarf2_name (die, cu);
19082   if (name)
19083     {
19084       const char *linkagename;
19085       int suppress_add = 0;
19086
19087       if (space)
19088         sym = space;
19089       else
19090         sym = allocate_symbol (objfile);
19091       OBJSTAT (objfile, n_syms++);
19092
19093       /* Cache this symbol's name and the name's demangled form (if any).  */
19094       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19095       linkagename = dwarf2_physname (name, die, cu);
19096       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19097
19098       /* Fortran does not have mangling standard and the mangling does differ
19099          between gfortran, iFort etc.  */
19100       if (cu->language == language_fortran
19101           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19102         symbol_set_demangled_name (&(sym->ginfo),
19103                                    dwarf2_full_name (name, die, cu),
19104                                    NULL);
19105
19106       /* Default assumptions.
19107          Use the passed type or decode it from the die.  */
19108       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19109       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19110       if (type != NULL)
19111         SYMBOL_TYPE (sym) = type;
19112       else
19113         SYMBOL_TYPE (sym) = die_type (die, cu);
19114       attr = dwarf2_attr (die,
19115                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19116                           cu);
19117       if (attr)
19118         {
19119           SYMBOL_LINE (sym) = DW_UNSND (attr);
19120         }
19121
19122       attr = dwarf2_attr (die,
19123                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19124                           cu);
19125       if (attr)
19126         {
19127           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19128           struct file_entry *fe;
19129
19130           if (cu->line_header != NULL)
19131             fe = cu->line_header->file_name_at (file_index);
19132           else
19133             fe = NULL;
19134
19135           if (fe == NULL)
19136             complaint (&symfile_complaints,
19137                        _("file index out of range"));
19138           else
19139             symbol_set_symtab (sym, fe->symtab);
19140         }
19141
19142       switch (die->tag)
19143         {
19144         case DW_TAG_label:
19145           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19146           if (attr)
19147             {
19148               CORE_ADDR addr;
19149
19150               addr = attr_value_as_address (attr);
19151               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19152               SYMBOL_VALUE_ADDRESS (sym) = addr;
19153             }
19154           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19155           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19156           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19157           add_symbol_to_list (sym, cu->list_in_scope);
19158           break;
19159         case DW_TAG_subprogram:
19160           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19161              finish_block.  */
19162           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19163           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19164           if ((attr2 && (DW_UNSND (attr2) != 0))
19165               || cu->language == language_ada)
19166             {
19167               /* Subprograms marked external are stored as a global symbol.
19168                  Ada subprograms, whether marked external or not, are always
19169                  stored as a global symbol, because we want to be able to
19170                  access them globally.  For instance, we want to be able
19171                  to break on a nested subprogram without having to
19172                  specify the context.  */
19173               list_to_add = &global_symbols;
19174             }
19175           else
19176             {
19177               list_to_add = cu->list_in_scope;
19178             }
19179           break;
19180         case DW_TAG_inlined_subroutine:
19181           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19182              finish_block.  */
19183           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19184           SYMBOL_INLINED (sym) = 1;
19185           list_to_add = cu->list_in_scope;
19186           break;
19187         case DW_TAG_template_value_param:
19188           suppress_add = 1;
19189           /* Fall through.  */
19190         case DW_TAG_constant:
19191         case DW_TAG_variable:
19192         case DW_TAG_member:
19193           /* Compilation with minimal debug info may result in
19194              variables with missing type entries.  Change the
19195              misleading `void' type to something sensible.  */
19196           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19197             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19198
19199           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19200           /* In the case of DW_TAG_member, we should only be called for
19201              static const members.  */
19202           if (die->tag == DW_TAG_member)
19203             {
19204               /* dwarf2_add_field uses die_is_declaration,
19205                  so we do the same.  */
19206               gdb_assert (die_is_declaration (die, cu));
19207               gdb_assert (attr);
19208             }
19209           if (attr)
19210             {
19211               dwarf2_const_value (attr, sym, cu);
19212               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19213               if (!suppress_add)
19214                 {
19215                   if (attr2 && (DW_UNSND (attr2) != 0))
19216                     list_to_add = &global_symbols;
19217                   else
19218                     list_to_add = cu->list_in_scope;
19219                 }
19220               break;
19221             }
19222           attr = dwarf2_attr (die, DW_AT_location, cu);
19223           if (attr)
19224             {
19225               var_decode_location (attr, sym, cu);
19226               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19227
19228               /* Fortran explicitly imports any global symbols to the local
19229                  scope by DW_TAG_common_block.  */
19230               if (cu->language == language_fortran && die->parent
19231                   && die->parent->tag == DW_TAG_common_block)
19232                 attr2 = NULL;
19233
19234               if (SYMBOL_CLASS (sym) == LOC_STATIC
19235                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19236                   && !dwarf2_per_objfile->has_section_at_zero)
19237                 {
19238                   /* When a static variable is eliminated by the linker,
19239                      the corresponding debug information is not stripped
19240                      out, but the variable address is set to null;
19241                      do not add such variables into symbol table.  */
19242                 }
19243               else if (attr2 && (DW_UNSND (attr2) != 0))
19244                 {
19245                   /* Workaround gfortran PR debug/40040 - it uses
19246                      DW_AT_location for variables in -fPIC libraries which may
19247                      get overriden by other libraries/executable and get
19248                      a different address.  Resolve it by the minimal symbol
19249                      which may come from inferior's executable using copy
19250                      relocation.  Make this workaround only for gfortran as for
19251                      other compilers GDB cannot guess the minimal symbol
19252                      Fortran mangling kind.  */
19253                   if (cu->language == language_fortran && die->parent
19254                       && die->parent->tag == DW_TAG_module
19255                       && cu->producer
19256                       && startswith (cu->producer, "GNU Fortran"))
19257                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19258
19259                   /* A variable with DW_AT_external is never static,
19260                      but it may be block-scoped.  */
19261                   list_to_add = (cu->list_in_scope == &file_symbols
19262                                  ? &global_symbols : cu->list_in_scope);
19263                 }
19264               else
19265                 list_to_add = cu->list_in_scope;
19266             }
19267           else
19268             {
19269               /* We do not know the address of this symbol.
19270                  If it is an external symbol and we have type information
19271                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19272                  The address of the variable will then be determined from
19273                  the minimal symbol table whenever the variable is
19274                  referenced.  */
19275               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19276
19277               /* Fortran explicitly imports any global symbols to the local
19278                  scope by DW_TAG_common_block.  */
19279               if (cu->language == language_fortran && die->parent
19280                   && die->parent->tag == DW_TAG_common_block)
19281                 {
19282                   /* SYMBOL_CLASS doesn't matter here because
19283                      read_common_block is going to reset it.  */
19284                   if (!suppress_add)
19285                     list_to_add = cu->list_in_scope;
19286                 }
19287               else if (attr2 && (DW_UNSND (attr2) != 0)
19288                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19289                 {
19290                   /* A variable with DW_AT_external is never static, but it
19291                      may be block-scoped.  */
19292                   list_to_add = (cu->list_in_scope == &file_symbols
19293                                  ? &global_symbols : cu->list_in_scope);
19294
19295                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19296                 }
19297               else if (!die_is_declaration (die, cu))
19298                 {
19299                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19300                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19301                   if (!suppress_add)
19302                     list_to_add = cu->list_in_scope;
19303                 }
19304             }
19305           break;
19306         case DW_TAG_formal_parameter:
19307           /* If we are inside a function, mark this as an argument.  If
19308              not, we might be looking at an argument to an inlined function
19309              when we do not have enough information to show inlined frames;
19310              pretend it's a local variable in that case so that the user can
19311              still see it.  */
19312           if (context_stack_depth > 0
19313               && context_stack[context_stack_depth - 1].name != NULL)
19314             SYMBOL_IS_ARGUMENT (sym) = 1;
19315           attr = dwarf2_attr (die, DW_AT_location, cu);
19316           if (attr)
19317             {
19318               var_decode_location (attr, sym, cu);
19319             }
19320           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19321           if (attr)
19322             {
19323               dwarf2_const_value (attr, sym, cu);
19324             }
19325
19326           list_to_add = cu->list_in_scope;
19327           break;
19328         case DW_TAG_unspecified_parameters:
19329           /* From varargs functions; gdb doesn't seem to have any
19330              interest in this information, so just ignore it for now.
19331              (FIXME?) */
19332           break;
19333         case DW_TAG_template_type_param:
19334           suppress_add = 1;
19335           /* Fall through.  */
19336         case DW_TAG_class_type:
19337         case DW_TAG_interface_type:
19338         case DW_TAG_structure_type:
19339         case DW_TAG_union_type:
19340         case DW_TAG_set_type:
19341         case DW_TAG_enumeration_type:
19342           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19343           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19344
19345           {
19346             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19347                really ever be static objects: otherwise, if you try
19348                to, say, break of a class's method and you're in a file
19349                which doesn't mention that class, it won't work unless
19350                the check for all static symbols in lookup_symbol_aux
19351                saves you.  See the OtherFileClass tests in
19352                gdb.c++/namespace.exp.  */
19353
19354             if (!suppress_add)
19355               {
19356                 list_to_add = (cu->list_in_scope == &file_symbols
19357                                && cu->language == language_cplus
19358                                ? &global_symbols : cu->list_in_scope);
19359
19360                 /* The semantics of C++ state that "struct foo {
19361                    ... }" also defines a typedef for "foo".  */
19362                 if (cu->language == language_cplus
19363                     || cu->language == language_ada
19364                     || cu->language == language_d
19365                     || cu->language == language_rust)
19366                   {
19367                     /* The symbol's name is already allocated along
19368                        with this objfile, so we don't need to
19369                        duplicate it for the type.  */
19370                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19371                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19372                   }
19373               }
19374           }
19375           break;
19376         case DW_TAG_typedef:
19377           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19378           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19379           list_to_add = cu->list_in_scope;
19380           break;
19381         case DW_TAG_base_type:
19382         case DW_TAG_subrange_type:
19383           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19384           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19385           list_to_add = cu->list_in_scope;
19386           break;
19387         case DW_TAG_enumerator:
19388           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19389           if (attr)
19390             {
19391               dwarf2_const_value (attr, sym, cu);
19392             }
19393           {
19394             /* NOTE: carlton/2003-11-10: See comment above in the
19395                DW_TAG_class_type, etc. block.  */
19396
19397             list_to_add = (cu->list_in_scope == &file_symbols
19398                            && cu->language == language_cplus
19399                            ? &global_symbols : cu->list_in_scope);
19400           }
19401           break;
19402         case DW_TAG_imported_declaration:
19403         case DW_TAG_namespace:
19404           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19405           list_to_add = &global_symbols;
19406           break;
19407         case DW_TAG_module:
19408           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19409           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19410           list_to_add = &global_symbols;
19411           break;
19412         case DW_TAG_common_block:
19413           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19414           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19415           add_symbol_to_list (sym, cu->list_in_scope);
19416           break;
19417         default:
19418           /* Not a tag we recognize.  Hopefully we aren't processing
19419              trash data, but since we must specifically ignore things
19420              we don't recognize, there is nothing else we should do at
19421              this point.  */
19422           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19423                      dwarf_tag_name (die->tag));
19424           break;
19425         }
19426
19427       if (suppress_add)
19428         {
19429           sym->hash_next = objfile->template_symbols;
19430           objfile->template_symbols = sym;
19431           list_to_add = NULL;
19432         }
19433
19434       if (list_to_add != NULL)
19435         add_symbol_to_list (sym, list_to_add);
19436
19437       /* For the benefit of old versions of GCC, check for anonymous
19438          namespaces based on the demangled name.  */
19439       if (!cu->processing_has_namespace_info
19440           && cu->language == language_cplus)
19441         cp_scan_for_anonymous_namespaces (sym, objfile);
19442     }
19443   return (sym);
19444 }
19445
19446 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19447
19448 static struct symbol *
19449 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19450 {
19451   return new_symbol_full (die, type, cu, NULL);
19452 }
19453
19454 /* Given an attr with a DW_FORM_dataN value in host byte order,
19455    zero-extend it as appropriate for the symbol's type.  The DWARF
19456    standard (v4) is not entirely clear about the meaning of using
19457    DW_FORM_dataN for a constant with a signed type, where the type is
19458    wider than the data.  The conclusion of a discussion on the DWARF
19459    list was that this is unspecified.  We choose to always zero-extend
19460    because that is the interpretation long in use by GCC.  */
19461
19462 static gdb_byte *
19463 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19464                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19465 {
19466   struct objfile *objfile = cu->objfile;
19467   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19468                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19469   LONGEST l = DW_UNSND (attr);
19470
19471   if (bits < sizeof (*value) * 8)
19472     {
19473       l &= ((LONGEST) 1 << bits) - 1;
19474       *value = l;
19475     }
19476   else if (bits == sizeof (*value) * 8)
19477     *value = l;
19478   else
19479     {
19480       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19481       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19482       return bytes;
19483     }
19484
19485   return NULL;
19486 }
19487
19488 /* Read a constant value from an attribute.  Either set *VALUE, or if
19489    the value does not fit in *VALUE, set *BYTES - either already
19490    allocated on the objfile obstack, or newly allocated on OBSTACK,
19491    or, set *BATON, if we translated the constant to a location
19492    expression.  */
19493
19494 static void
19495 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19496                          const char *name, struct obstack *obstack,
19497                          struct dwarf2_cu *cu,
19498                          LONGEST *value, const gdb_byte **bytes,
19499                          struct dwarf2_locexpr_baton **baton)
19500 {
19501   struct objfile *objfile = cu->objfile;
19502   struct comp_unit_head *cu_header = &cu->header;
19503   struct dwarf_block *blk;
19504   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19505                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19506
19507   *value = 0;
19508   *bytes = NULL;
19509   *baton = NULL;
19510
19511   switch (attr->form)
19512     {
19513     case DW_FORM_addr:
19514     case DW_FORM_GNU_addr_index:
19515       {
19516         gdb_byte *data;
19517
19518         if (TYPE_LENGTH (type) != cu_header->addr_size)
19519           dwarf2_const_value_length_mismatch_complaint (name,
19520                                                         cu_header->addr_size,
19521                                                         TYPE_LENGTH (type));
19522         /* Symbols of this form are reasonably rare, so we just
19523            piggyback on the existing location code rather than writing
19524            a new implementation of symbol_computed_ops.  */
19525         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19526         (*baton)->per_cu = cu->per_cu;
19527         gdb_assert ((*baton)->per_cu);
19528
19529         (*baton)->size = 2 + cu_header->addr_size;
19530         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19531         (*baton)->data = data;
19532
19533         data[0] = DW_OP_addr;
19534         store_unsigned_integer (&data[1], cu_header->addr_size,
19535                                 byte_order, DW_ADDR (attr));
19536         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19537       }
19538       break;
19539     case DW_FORM_string:
19540     case DW_FORM_strp:
19541     case DW_FORM_GNU_str_index:
19542     case DW_FORM_GNU_strp_alt:
19543       /* DW_STRING is already allocated on the objfile obstack, point
19544          directly to it.  */
19545       *bytes = (const gdb_byte *) DW_STRING (attr);
19546       break;
19547     case DW_FORM_block1:
19548     case DW_FORM_block2:
19549     case DW_FORM_block4:
19550     case DW_FORM_block:
19551     case DW_FORM_exprloc:
19552     case DW_FORM_data16:
19553       blk = DW_BLOCK (attr);
19554       if (TYPE_LENGTH (type) != blk->size)
19555         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19556                                                       TYPE_LENGTH (type));
19557       *bytes = blk->data;
19558       break;
19559
19560       /* The DW_AT_const_value attributes are supposed to carry the
19561          symbol's value "represented as it would be on the target
19562          architecture."  By the time we get here, it's already been
19563          converted to host endianness, so we just need to sign- or
19564          zero-extend it as appropriate.  */
19565     case DW_FORM_data1:
19566       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19567       break;
19568     case DW_FORM_data2:
19569       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19570       break;
19571     case DW_FORM_data4:
19572       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19573       break;
19574     case DW_FORM_data8:
19575       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19576       break;
19577
19578     case DW_FORM_sdata:
19579     case DW_FORM_implicit_const:
19580       *value = DW_SND (attr);
19581       break;
19582
19583     case DW_FORM_udata:
19584       *value = DW_UNSND (attr);
19585       break;
19586
19587     default:
19588       complaint (&symfile_complaints,
19589                  _("unsupported const value attribute form: '%s'"),
19590                  dwarf_form_name (attr->form));
19591       *value = 0;
19592       break;
19593     }
19594 }
19595
19596
19597 /* Copy constant value from an attribute to a symbol.  */
19598
19599 static void
19600 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19601                     struct dwarf2_cu *cu)
19602 {
19603   struct objfile *objfile = cu->objfile;
19604   LONGEST value;
19605   const gdb_byte *bytes;
19606   struct dwarf2_locexpr_baton *baton;
19607
19608   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19609                            SYMBOL_PRINT_NAME (sym),
19610                            &objfile->objfile_obstack, cu,
19611                            &value, &bytes, &baton);
19612
19613   if (baton != NULL)
19614     {
19615       SYMBOL_LOCATION_BATON (sym) = baton;
19616       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19617     }
19618   else if (bytes != NULL)
19619      {
19620       SYMBOL_VALUE_BYTES (sym) = bytes;
19621       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19622     }
19623   else
19624     {
19625       SYMBOL_VALUE (sym) = value;
19626       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19627     }
19628 }
19629
19630 /* Return the type of the die in question using its DW_AT_type attribute.  */
19631
19632 static struct type *
19633 die_type (struct die_info *die, struct dwarf2_cu *cu)
19634 {
19635   struct attribute *type_attr;
19636
19637   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19638   if (!type_attr)
19639     {
19640       /* A missing DW_AT_type represents a void type.  */
19641       return objfile_type (cu->objfile)->builtin_void;
19642     }
19643
19644   return lookup_die_type (die, type_attr, cu);
19645 }
19646
19647 /* True iff CU's producer generates GNAT Ada auxiliary information
19648    that allows to find parallel types through that information instead
19649    of having to do expensive parallel lookups by type name.  */
19650
19651 static int
19652 need_gnat_info (struct dwarf2_cu *cu)
19653 {
19654   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19655      of GNAT produces this auxiliary information, without any indication
19656      that it is produced.  Part of enhancing the FSF version of GNAT
19657      to produce that information will be to put in place an indicator
19658      that we can use in order to determine whether the descriptive type
19659      info is available or not.  One suggestion that has been made is
19660      to use a new attribute, attached to the CU die.  For now, assume
19661      that the descriptive type info is not available.  */
19662   return 0;
19663 }
19664
19665 /* Return the auxiliary type of the die in question using its
19666    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19667    attribute is not present.  */
19668
19669 static struct type *
19670 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19671 {
19672   struct attribute *type_attr;
19673
19674   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19675   if (!type_attr)
19676     return NULL;
19677
19678   return lookup_die_type (die, type_attr, cu);
19679 }
19680
19681 /* If DIE has a descriptive_type attribute, then set the TYPE's
19682    descriptive type accordingly.  */
19683
19684 static void
19685 set_descriptive_type (struct type *type, struct die_info *die,
19686                       struct dwarf2_cu *cu)
19687 {
19688   struct type *descriptive_type = die_descriptive_type (die, cu);
19689
19690   if (descriptive_type)
19691     {
19692       ALLOCATE_GNAT_AUX_TYPE (type);
19693       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19694     }
19695 }
19696
19697 /* Return the containing type of the die in question using its
19698    DW_AT_containing_type attribute.  */
19699
19700 static struct type *
19701 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19702 {
19703   struct attribute *type_attr;
19704
19705   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19706   if (!type_attr)
19707     error (_("Dwarf Error: Problem turning containing type into gdb type "
19708              "[in module %s]"), objfile_name (cu->objfile));
19709
19710   return lookup_die_type (die, type_attr, cu);
19711 }
19712
19713 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19714
19715 static struct type *
19716 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19717 {
19718   struct objfile *objfile = dwarf2_per_objfile->objfile;
19719   char *message, *saved;
19720
19721   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19722                         objfile_name (objfile),
19723                         to_underlying (cu->header.sect_off),
19724                         to_underlying (die->sect_off));
19725   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19726                                   message, strlen (message));
19727   xfree (message);
19728
19729   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19730 }
19731
19732 /* Look up the type of DIE in CU using its type attribute ATTR.
19733    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19734    DW_AT_containing_type.
19735    If there is no type substitute an error marker.  */
19736
19737 static struct type *
19738 lookup_die_type (struct die_info *die, const struct attribute *attr,
19739                  struct dwarf2_cu *cu)
19740 {
19741   struct objfile *objfile = cu->objfile;
19742   struct type *this_type;
19743
19744   gdb_assert (attr->name == DW_AT_type
19745               || attr->name == DW_AT_GNAT_descriptive_type
19746               || attr->name == DW_AT_containing_type);
19747
19748   /* First see if we have it cached.  */
19749
19750   if (attr->form == DW_FORM_GNU_ref_alt)
19751     {
19752       struct dwarf2_per_cu_data *per_cu;
19753       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19754
19755       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19756       this_type = get_die_type_at_offset (sect_off, per_cu);
19757     }
19758   else if (attr_form_is_ref (attr))
19759     {
19760       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19761
19762       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19763     }
19764   else if (attr->form == DW_FORM_ref_sig8)
19765     {
19766       ULONGEST signature = DW_SIGNATURE (attr);
19767
19768       return get_signatured_type (die, signature, cu);
19769     }
19770   else
19771     {
19772       complaint (&symfile_complaints,
19773                  _("Dwarf Error: Bad type attribute %s in DIE"
19774                    " at 0x%x [in module %s]"),
19775                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19776                  objfile_name (objfile));
19777       return build_error_marker_type (cu, die);
19778     }
19779
19780   /* If not cached we need to read it in.  */
19781
19782   if (this_type == NULL)
19783     {
19784       struct die_info *type_die = NULL;
19785       struct dwarf2_cu *type_cu = cu;
19786
19787       if (attr_form_is_ref (attr))
19788         type_die = follow_die_ref (die, attr, &type_cu);
19789       if (type_die == NULL)
19790         return build_error_marker_type (cu, die);
19791       /* If we find the type now, it's probably because the type came
19792          from an inter-CU reference and the type's CU got expanded before
19793          ours.  */
19794       this_type = read_type_die (type_die, type_cu);
19795     }
19796
19797   /* If we still don't have a type use an error marker.  */
19798
19799   if (this_type == NULL)
19800     return build_error_marker_type (cu, die);
19801
19802   return this_type;
19803 }
19804
19805 /* Return the type in DIE, CU.
19806    Returns NULL for invalid types.
19807
19808    This first does a lookup in die_type_hash,
19809    and only reads the die in if necessary.
19810
19811    NOTE: This can be called when reading in partial or full symbols.  */
19812
19813 static struct type *
19814 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19815 {
19816   struct type *this_type;
19817
19818   this_type = get_die_type (die, cu);
19819   if (this_type)
19820     return this_type;
19821
19822   return read_type_die_1 (die, cu);
19823 }
19824
19825 /* Read the type in DIE, CU.
19826    Returns NULL for invalid types.  */
19827
19828 static struct type *
19829 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19830 {
19831   struct type *this_type = NULL;
19832
19833   switch (die->tag)
19834     {
19835     case DW_TAG_class_type:
19836     case DW_TAG_interface_type:
19837     case DW_TAG_structure_type:
19838     case DW_TAG_union_type:
19839       this_type = read_structure_type (die, cu);
19840       break;
19841     case DW_TAG_enumeration_type:
19842       this_type = read_enumeration_type (die, cu);
19843       break;
19844     case DW_TAG_subprogram:
19845     case DW_TAG_subroutine_type:
19846     case DW_TAG_inlined_subroutine:
19847       this_type = read_subroutine_type (die, cu);
19848       break;
19849     case DW_TAG_array_type:
19850       this_type = read_array_type (die, cu);
19851       break;
19852     case DW_TAG_set_type:
19853       this_type = read_set_type (die, cu);
19854       break;
19855     case DW_TAG_pointer_type:
19856       this_type = read_tag_pointer_type (die, cu);
19857       break;
19858     case DW_TAG_ptr_to_member_type:
19859       this_type = read_tag_ptr_to_member_type (die, cu);
19860       break;
19861     case DW_TAG_reference_type:
19862       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19863       break;
19864     case DW_TAG_rvalue_reference_type:
19865       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19866       break;
19867     case DW_TAG_const_type:
19868       this_type = read_tag_const_type (die, cu);
19869       break;
19870     case DW_TAG_volatile_type:
19871       this_type = read_tag_volatile_type (die, cu);
19872       break;
19873     case DW_TAG_restrict_type:
19874       this_type = read_tag_restrict_type (die, cu);
19875       break;
19876     case DW_TAG_string_type:
19877       this_type = read_tag_string_type (die, cu);
19878       break;
19879     case DW_TAG_typedef:
19880       this_type = read_typedef (die, cu);
19881       break;
19882     case DW_TAG_subrange_type:
19883       this_type = read_subrange_type (die, cu);
19884       break;
19885     case DW_TAG_base_type:
19886       this_type = read_base_type (die, cu);
19887       break;
19888     case DW_TAG_unspecified_type:
19889       this_type = read_unspecified_type (die, cu);
19890       break;
19891     case DW_TAG_namespace:
19892       this_type = read_namespace_type (die, cu);
19893       break;
19894     case DW_TAG_module:
19895       this_type = read_module_type (die, cu);
19896       break;
19897     case DW_TAG_atomic_type:
19898       this_type = read_tag_atomic_type (die, cu);
19899       break;
19900     default:
19901       complaint (&symfile_complaints,
19902                  _("unexpected tag in read_type_die: '%s'"),
19903                  dwarf_tag_name (die->tag));
19904       break;
19905     }
19906
19907   return this_type;
19908 }
19909
19910 /* See if we can figure out if the class lives in a namespace.  We do
19911    this by looking for a member function; its demangled name will
19912    contain namespace info, if there is any.
19913    Return the computed name or NULL.
19914    Space for the result is allocated on the objfile's obstack.
19915    This is the full-die version of guess_partial_die_structure_name.
19916    In this case we know DIE has no useful parent.  */
19917
19918 static char *
19919 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19920 {
19921   struct die_info *spec_die;
19922   struct dwarf2_cu *spec_cu;
19923   struct die_info *child;
19924
19925   spec_cu = cu;
19926   spec_die = die_specification (die, &spec_cu);
19927   if (spec_die != NULL)
19928     {
19929       die = spec_die;
19930       cu = spec_cu;
19931     }
19932
19933   for (child = die->child;
19934        child != NULL;
19935        child = child->sibling)
19936     {
19937       if (child->tag == DW_TAG_subprogram)
19938         {
19939           const char *linkage_name = dw2_linkage_name (child, cu);
19940
19941           if (linkage_name != NULL)
19942             {
19943               char *actual_name
19944                 = language_class_name_from_physname (cu->language_defn,
19945                                                      linkage_name);
19946               char *name = NULL;
19947
19948               if (actual_name != NULL)
19949                 {
19950                   const char *die_name = dwarf2_name (die, cu);
19951
19952                   if (die_name != NULL
19953                       && strcmp (die_name, actual_name) != 0)
19954                     {
19955                       /* Strip off the class name from the full name.
19956                          We want the prefix.  */
19957                       int die_name_len = strlen (die_name);
19958                       int actual_name_len = strlen (actual_name);
19959
19960                       /* Test for '::' as a sanity check.  */
19961                       if (actual_name_len > die_name_len + 2
19962                           && actual_name[actual_name_len
19963                                          - die_name_len - 1] == ':')
19964                         name = (char *) obstack_copy0 (
19965                           &cu->objfile->per_bfd->storage_obstack,
19966                           actual_name, actual_name_len - die_name_len - 2);
19967                     }
19968                 }
19969               xfree (actual_name);
19970               return name;
19971             }
19972         }
19973     }
19974
19975   return NULL;
19976 }
19977
19978 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19979    prefix part in such case.  See
19980    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19981
19982 static const char *
19983 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19984 {
19985   struct attribute *attr;
19986   const char *base;
19987
19988   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19989       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19990     return NULL;
19991
19992   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19993     return NULL;
19994
19995   attr = dw2_linkage_name_attr (die, cu);
19996   if (attr == NULL || DW_STRING (attr) == NULL)
19997     return NULL;
19998
19999   /* dwarf2_name had to be already called.  */
20000   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20001
20002   /* Strip the base name, keep any leading namespaces/classes.  */
20003   base = strrchr (DW_STRING (attr), ':');
20004   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20005     return "";
20006
20007   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20008                                  DW_STRING (attr),
20009                                  &base[-1] - DW_STRING (attr));
20010 }
20011
20012 /* Return the name of the namespace/class that DIE is defined within,
20013    or "" if we can't tell.  The caller should not xfree the result.
20014
20015    For example, if we're within the method foo() in the following
20016    code:
20017
20018    namespace N {
20019      class C {
20020        void foo () {
20021        }
20022      };
20023    }
20024
20025    then determine_prefix on foo's die will return "N::C".  */
20026
20027 static const char *
20028 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20029 {
20030   struct die_info *parent, *spec_die;
20031   struct dwarf2_cu *spec_cu;
20032   struct type *parent_type;
20033   const char *retval;
20034
20035   if (cu->language != language_cplus
20036       && cu->language != language_fortran && cu->language != language_d
20037       && cu->language != language_rust)
20038     return "";
20039
20040   retval = anonymous_struct_prefix (die, cu);
20041   if (retval)
20042     return retval;
20043
20044   /* We have to be careful in the presence of DW_AT_specification.
20045      For example, with GCC 3.4, given the code
20046
20047      namespace N {
20048        void foo() {
20049          // Definition of N::foo.
20050        }
20051      }
20052
20053      then we'll have a tree of DIEs like this:
20054
20055      1: DW_TAG_compile_unit
20056        2: DW_TAG_namespace        // N
20057          3: DW_TAG_subprogram     // declaration of N::foo
20058        4: DW_TAG_subprogram       // definition of N::foo
20059             DW_AT_specification   // refers to die #3
20060
20061      Thus, when processing die #4, we have to pretend that we're in
20062      the context of its DW_AT_specification, namely the contex of die
20063      #3.  */
20064   spec_cu = cu;
20065   spec_die = die_specification (die, &spec_cu);
20066   if (spec_die == NULL)
20067     parent = die->parent;
20068   else
20069     {
20070       parent = spec_die->parent;
20071       cu = spec_cu;
20072     }
20073
20074   if (parent == NULL)
20075     return "";
20076   else if (parent->building_fullname)
20077     {
20078       const char *name;
20079       const char *parent_name;
20080
20081       /* It has been seen on RealView 2.2 built binaries,
20082          DW_TAG_template_type_param types actually _defined_ as
20083          children of the parent class:
20084
20085          enum E {};
20086          template class <class Enum> Class{};
20087          Class<enum E> class_e;
20088
20089          1: DW_TAG_class_type (Class)
20090            2: DW_TAG_enumeration_type (E)
20091              3: DW_TAG_enumerator (enum1:0)
20092              3: DW_TAG_enumerator (enum2:1)
20093              ...
20094            2: DW_TAG_template_type_param
20095               DW_AT_type  DW_FORM_ref_udata (E)
20096
20097          Besides being broken debug info, it can put GDB into an
20098          infinite loop.  Consider:
20099
20100          When we're building the full name for Class<E>, we'll start
20101          at Class, and go look over its template type parameters,
20102          finding E.  We'll then try to build the full name of E, and
20103          reach here.  We're now trying to build the full name of E,
20104          and look over the parent DIE for containing scope.  In the
20105          broken case, if we followed the parent DIE of E, we'd again
20106          find Class, and once again go look at its template type
20107          arguments, etc., etc.  Simply don't consider such parent die
20108          as source-level parent of this die (it can't be, the language
20109          doesn't allow it), and break the loop here.  */
20110       name = dwarf2_name (die, cu);
20111       parent_name = dwarf2_name (parent, cu);
20112       complaint (&symfile_complaints,
20113                  _("template param type '%s' defined within parent '%s'"),
20114                  name ? name : "<unknown>",
20115                  parent_name ? parent_name : "<unknown>");
20116       return "";
20117     }
20118   else
20119     switch (parent->tag)
20120       {
20121       case DW_TAG_namespace:
20122         parent_type = read_type_die (parent, cu);
20123         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20124            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20125            Work around this problem here.  */
20126         if (cu->language == language_cplus
20127             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20128           return "";
20129         /* We give a name to even anonymous namespaces.  */
20130         return TYPE_TAG_NAME (parent_type);
20131       case DW_TAG_class_type:
20132       case DW_TAG_interface_type:
20133       case DW_TAG_structure_type:
20134       case DW_TAG_union_type:
20135       case DW_TAG_module:
20136         parent_type = read_type_die (parent, cu);
20137         if (TYPE_TAG_NAME (parent_type) != NULL)
20138           return TYPE_TAG_NAME (parent_type);
20139         else
20140           /* An anonymous structure is only allowed non-static data
20141              members; no typedefs, no member functions, et cetera.
20142              So it does not need a prefix.  */
20143           return "";
20144       case DW_TAG_compile_unit:
20145       case DW_TAG_partial_unit:
20146         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20147         if (cu->language == language_cplus
20148             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20149             && die->child != NULL
20150             && (die->tag == DW_TAG_class_type
20151                 || die->tag == DW_TAG_structure_type
20152                 || die->tag == DW_TAG_union_type))
20153           {
20154             char *name = guess_full_die_structure_name (die, cu);
20155             if (name != NULL)
20156               return name;
20157           }
20158         return "";
20159       case DW_TAG_enumeration_type:
20160         parent_type = read_type_die (parent, cu);
20161         if (TYPE_DECLARED_CLASS (parent_type))
20162           {
20163             if (TYPE_TAG_NAME (parent_type) != NULL)
20164               return TYPE_TAG_NAME (parent_type);
20165             return "";
20166           }
20167         /* Fall through.  */
20168       default:
20169         return determine_prefix (parent, cu);
20170       }
20171 }
20172
20173 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20174    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20175    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20176    an obconcat, otherwise allocate storage for the result.  The CU argument is
20177    used to determine the language and hence, the appropriate separator.  */
20178
20179 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20180
20181 static char *
20182 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20183                  int physname, struct dwarf2_cu *cu)
20184 {
20185   const char *lead = "";
20186   const char *sep;
20187
20188   if (suffix == NULL || suffix[0] == '\0'
20189       || prefix == NULL || prefix[0] == '\0')
20190     sep = "";
20191   else if (cu->language == language_d)
20192     {
20193       /* For D, the 'main' function could be defined in any module, but it
20194          should never be prefixed.  */
20195       if (strcmp (suffix, "D main") == 0)
20196         {
20197           prefix = "";
20198           sep = "";
20199         }
20200       else
20201         sep = ".";
20202     }
20203   else if (cu->language == language_fortran && physname)
20204     {
20205       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20206          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20207
20208       lead = "__";
20209       sep = "_MOD_";
20210     }
20211   else
20212     sep = "::";
20213
20214   if (prefix == NULL)
20215     prefix = "";
20216   if (suffix == NULL)
20217     suffix = "";
20218
20219   if (obs == NULL)
20220     {
20221       char *retval
20222         = ((char *)
20223            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20224
20225       strcpy (retval, lead);
20226       strcat (retval, prefix);
20227       strcat (retval, sep);
20228       strcat (retval, suffix);
20229       return retval;
20230     }
20231   else
20232     {
20233       /* We have an obstack.  */
20234       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20235     }
20236 }
20237
20238 /* Return sibling of die, NULL if no sibling.  */
20239
20240 static struct die_info *
20241 sibling_die (struct die_info *die)
20242 {
20243   return die->sibling;
20244 }
20245
20246 /* Get name of a die, return NULL if not found.  */
20247
20248 static const char *
20249 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20250                           struct obstack *obstack)
20251 {
20252   if (name && cu->language == language_cplus)
20253     {
20254       std::string canon_name = cp_canonicalize_string (name);
20255
20256       if (!canon_name.empty ())
20257         {
20258           if (canon_name != name)
20259             name = (const char *) obstack_copy0 (obstack,
20260                                                  canon_name.c_str (),
20261                                                  canon_name.length ());
20262         }
20263     }
20264
20265   return name;
20266 }
20267
20268 /* Get name of a die, return NULL if not found.
20269    Anonymous namespaces are converted to their magic string.  */
20270
20271 static const char *
20272 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20273 {
20274   struct attribute *attr;
20275
20276   attr = dwarf2_attr (die, DW_AT_name, cu);
20277   if ((!attr || !DW_STRING (attr))
20278       && die->tag != DW_TAG_namespace
20279       && die->tag != DW_TAG_class_type
20280       && die->tag != DW_TAG_interface_type
20281       && die->tag != DW_TAG_structure_type
20282       && die->tag != DW_TAG_union_type)
20283     return NULL;
20284
20285   switch (die->tag)
20286     {
20287     case DW_TAG_compile_unit:
20288     case DW_TAG_partial_unit:
20289       /* Compilation units have a DW_AT_name that is a filename, not
20290          a source language identifier.  */
20291     case DW_TAG_enumeration_type:
20292     case DW_TAG_enumerator:
20293       /* These tags always have simple identifiers already; no need
20294          to canonicalize them.  */
20295       return DW_STRING (attr);
20296
20297     case DW_TAG_namespace:
20298       if (attr != NULL && DW_STRING (attr) != NULL)
20299         return DW_STRING (attr);
20300       return CP_ANONYMOUS_NAMESPACE_STR;
20301
20302     case DW_TAG_class_type:
20303     case DW_TAG_interface_type:
20304     case DW_TAG_structure_type:
20305     case DW_TAG_union_type:
20306       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20307          structures or unions.  These were of the form "._%d" in GCC 4.1,
20308          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20309          and GCC 4.4.  We work around this problem by ignoring these.  */
20310       if (attr && DW_STRING (attr)
20311           && (startswith (DW_STRING (attr), "._")
20312               || startswith (DW_STRING (attr), "<anonymous")))
20313         return NULL;
20314
20315       /* GCC might emit a nameless typedef that has a linkage name.  See
20316          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20317       if (!attr || DW_STRING (attr) == NULL)
20318         {
20319           char *demangled = NULL;
20320
20321           attr = dw2_linkage_name_attr (die, cu);
20322           if (attr == NULL || DW_STRING (attr) == NULL)
20323             return NULL;
20324
20325           /* Avoid demangling DW_STRING (attr) the second time on a second
20326              call for the same DIE.  */
20327           if (!DW_STRING_IS_CANONICAL (attr))
20328             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20329
20330           if (demangled)
20331             {
20332               const char *base;
20333
20334               /* FIXME: we already did this for the partial symbol... */
20335               DW_STRING (attr)
20336                 = ((const char *)
20337                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20338                                   demangled, strlen (demangled)));
20339               DW_STRING_IS_CANONICAL (attr) = 1;
20340               xfree (demangled);
20341
20342               /* Strip any leading namespaces/classes, keep only the base name.
20343                  DW_AT_name for named DIEs does not contain the prefixes.  */
20344               base = strrchr (DW_STRING (attr), ':');
20345               if (base && base > DW_STRING (attr) && base[-1] == ':')
20346                 return &base[1];
20347               else
20348                 return DW_STRING (attr);
20349             }
20350         }
20351       break;
20352
20353     default:
20354       break;
20355     }
20356
20357   if (!DW_STRING_IS_CANONICAL (attr))
20358     {
20359       DW_STRING (attr)
20360         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20361                                     &cu->objfile->per_bfd->storage_obstack);
20362       DW_STRING_IS_CANONICAL (attr) = 1;
20363     }
20364   return DW_STRING (attr);
20365 }
20366
20367 /* Return the die that this die in an extension of, or NULL if there
20368    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20369    containing the return value on output.  */
20370
20371 static struct die_info *
20372 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20373 {
20374   struct attribute *attr;
20375
20376   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20377   if (attr == NULL)
20378     return NULL;
20379
20380   return follow_die_ref (die, attr, ext_cu);
20381 }
20382
20383 /* Convert a DIE tag into its string name.  */
20384
20385 static const char *
20386 dwarf_tag_name (unsigned tag)
20387 {
20388   const char *name = get_DW_TAG_name (tag);
20389
20390   if (name == NULL)
20391     return "DW_TAG_<unknown>";
20392
20393   return name;
20394 }
20395
20396 /* Convert a DWARF attribute code into its string name.  */
20397
20398 static const char *
20399 dwarf_attr_name (unsigned attr)
20400 {
20401   const char *name;
20402
20403 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20404   if (attr == DW_AT_MIPS_fde)
20405     return "DW_AT_MIPS_fde";
20406 #else
20407   if (attr == DW_AT_HP_block_index)
20408     return "DW_AT_HP_block_index";
20409 #endif
20410
20411   name = get_DW_AT_name (attr);
20412
20413   if (name == NULL)
20414     return "DW_AT_<unknown>";
20415
20416   return name;
20417 }
20418
20419 /* Convert a DWARF value form code into its string name.  */
20420
20421 static const char *
20422 dwarf_form_name (unsigned form)
20423 {
20424   const char *name = get_DW_FORM_name (form);
20425
20426   if (name == NULL)
20427     return "DW_FORM_<unknown>";
20428
20429   return name;
20430 }
20431
20432 static const char *
20433 dwarf_bool_name (unsigned mybool)
20434 {
20435   if (mybool)
20436     return "TRUE";
20437   else
20438     return "FALSE";
20439 }
20440
20441 /* Convert a DWARF type code into its string name.  */
20442
20443 static const char *
20444 dwarf_type_encoding_name (unsigned enc)
20445 {
20446   const char *name = get_DW_ATE_name (enc);
20447
20448   if (name == NULL)
20449     return "DW_ATE_<unknown>";
20450
20451   return name;
20452 }
20453
20454 static void
20455 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20456 {
20457   unsigned int i;
20458
20459   print_spaces (indent, f);
20460   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20461                       dwarf_tag_name (die->tag), die->abbrev,
20462                       to_underlying (die->sect_off));
20463
20464   if (die->parent != NULL)
20465     {
20466       print_spaces (indent, f);
20467       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20468                           to_underlying (die->parent->sect_off));
20469     }
20470
20471   print_spaces (indent, f);
20472   fprintf_unfiltered (f, "  has children: %s\n",
20473            dwarf_bool_name (die->child != NULL));
20474
20475   print_spaces (indent, f);
20476   fprintf_unfiltered (f, "  attributes:\n");
20477
20478   for (i = 0; i < die->num_attrs; ++i)
20479     {
20480       print_spaces (indent, f);
20481       fprintf_unfiltered (f, "    %s (%s) ",
20482                dwarf_attr_name (die->attrs[i].name),
20483                dwarf_form_name (die->attrs[i].form));
20484
20485       switch (die->attrs[i].form)
20486         {
20487         case DW_FORM_addr:
20488         case DW_FORM_GNU_addr_index:
20489           fprintf_unfiltered (f, "address: ");
20490           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20491           break;
20492         case DW_FORM_block2:
20493         case DW_FORM_block4:
20494         case DW_FORM_block:
20495         case DW_FORM_block1:
20496           fprintf_unfiltered (f, "block: size %s",
20497                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20498           break;
20499         case DW_FORM_exprloc:
20500           fprintf_unfiltered (f, "expression: size %s",
20501                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20502           break;
20503         case DW_FORM_data16:
20504           fprintf_unfiltered (f, "constant of 16 bytes");
20505           break;
20506         case DW_FORM_ref_addr:
20507           fprintf_unfiltered (f, "ref address: ");
20508           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20509           break;
20510         case DW_FORM_GNU_ref_alt:
20511           fprintf_unfiltered (f, "alt ref address: ");
20512           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20513           break;
20514         case DW_FORM_ref1:
20515         case DW_FORM_ref2:
20516         case DW_FORM_ref4:
20517         case DW_FORM_ref8:
20518         case DW_FORM_ref_udata:
20519           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20520                               (long) (DW_UNSND (&die->attrs[i])));
20521           break;
20522         case DW_FORM_data1:
20523         case DW_FORM_data2:
20524         case DW_FORM_data4:
20525         case DW_FORM_data8:
20526         case DW_FORM_udata:
20527         case DW_FORM_sdata:
20528           fprintf_unfiltered (f, "constant: %s",
20529                               pulongest (DW_UNSND (&die->attrs[i])));
20530           break;
20531         case DW_FORM_sec_offset:
20532           fprintf_unfiltered (f, "section offset: %s",
20533                               pulongest (DW_UNSND (&die->attrs[i])));
20534           break;
20535         case DW_FORM_ref_sig8:
20536           fprintf_unfiltered (f, "signature: %s",
20537                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20538           break;
20539         case DW_FORM_string:
20540         case DW_FORM_strp:
20541         case DW_FORM_line_strp:
20542         case DW_FORM_GNU_str_index:
20543         case DW_FORM_GNU_strp_alt:
20544           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20545                    DW_STRING (&die->attrs[i])
20546                    ? DW_STRING (&die->attrs[i]) : "",
20547                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20548           break;
20549         case DW_FORM_flag:
20550           if (DW_UNSND (&die->attrs[i]))
20551             fprintf_unfiltered (f, "flag: TRUE");
20552           else
20553             fprintf_unfiltered (f, "flag: FALSE");
20554           break;
20555         case DW_FORM_flag_present:
20556           fprintf_unfiltered (f, "flag: TRUE");
20557           break;
20558         case DW_FORM_indirect:
20559           /* The reader will have reduced the indirect form to
20560              the "base form" so this form should not occur.  */
20561           fprintf_unfiltered (f, 
20562                               "unexpected attribute form: DW_FORM_indirect");
20563           break;
20564         case DW_FORM_implicit_const:
20565           fprintf_unfiltered (f, "constant: %s",
20566                               plongest (DW_SND (&die->attrs[i])));
20567           break;
20568         default:
20569           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20570                    die->attrs[i].form);
20571           break;
20572         }
20573       fprintf_unfiltered (f, "\n");
20574     }
20575 }
20576
20577 static void
20578 dump_die_for_error (struct die_info *die)
20579 {
20580   dump_die_shallow (gdb_stderr, 0, die);
20581 }
20582
20583 static void
20584 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20585 {
20586   int indent = level * 4;
20587
20588   gdb_assert (die != NULL);
20589
20590   if (level >= max_level)
20591     return;
20592
20593   dump_die_shallow (f, indent, die);
20594
20595   if (die->child != NULL)
20596     {
20597       print_spaces (indent, f);
20598       fprintf_unfiltered (f, "  Children:");
20599       if (level + 1 < max_level)
20600         {
20601           fprintf_unfiltered (f, "\n");
20602           dump_die_1 (f, level + 1, max_level, die->child);
20603         }
20604       else
20605         {
20606           fprintf_unfiltered (f,
20607                               " [not printed, max nesting level reached]\n");
20608         }
20609     }
20610
20611   if (die->sibling != NULL && level > 0)
20612     {
20613       dump_die_1 (f, level, max_level, die->sibling);
20614     }
20615 }
20616
20617 /* This is called from the pdie macro in gdbinit.in.
20618    It's not static so gcc will keep a copy callable from gdb.  */
20619
20620 void
20621 dump_die (struct die_info *die, int max_level)
20622 {
20623   dump_die_1 (gdb_stdlog, 0, max_level, die);
20624 }
20625
20626 static void
20627 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20628 {
20629   void **slot;
20630
20631   slot = htab_find_slot_with_hash (cu->die_hash, die,
20632                                    to_underlying (die->sect_off),
20633                                    INSERT);
20634
20635   *slot = die;
20636 }
20637
20638 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20639    required kind.  */
20640
20641 static sect_offset
20642 dwarf2_get_ref_die_offset (const struct attribute *attr)
20643 {
20644   if (attr_form_is_ref (attr))
20645     return (sect_offset) DW_UNSND (attr);
20646
20647   complaint (&symfile_complaints,
20648              _("unsupported die ref attribute form: '%s'"),
20649              dwarf_form_name (attr->form));
20650   return {};
20651 }
20652
20653 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20654  * the value held by the attribute is not constant.  */
20655
20656 static LONGEST
20657 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20658 {
20659   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20660     return DW_SND (attr);
20661   else if (attr->form == DW_FORM_udata
20662            || attr->form == DW_FORM_data1
20663            || attr->form == DW_FORM_data2
20664            || attr->form == DW_FORM_data4
20665            || attr->form == DW_FORM_data8)
20666     return DW_UNSND (attr);
20667   else
20668     {
20669       /* For DW_FORM_data16 see attr_form_is_constant.  */
20670       complaint (&symfile_complaints,
20671                  _("Attribute value is not a constant (%s)"),
20672                  dwarf_form_name (attr->form));
20673       return default_value;
20674     }
20675 }
20676
20677 /* Follow reference or signature attribute ATTR of SRC_DIE.
20678    On entry *REF_CU is the CU of SRC_DIE.
20679    On exit *REF_CU is the CU of the result.  */
20680
20681 static struct die_info *
20682 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20683                        struct dwarf2_cu **ref_cu)
20684 {
20685   struct die_info *die;
20686
20687   if (attr_form_is_ref (attr))
20688     die = follow_die_ref (src_die, attr, ref_cu);
20689   else if (attr->form == DW_FORM_ref_sig8)
20690     die = follow_die_sig (src_die, attr, ref_cu);
20691   else
20692     {
20693       dump_die_for_error (src_die);
20694       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20695              objfile_name ((*ref_cu)->objfile));
20696     }
20697
20698   return die;
20699 }
20700
20701 /* Follow reference OFFSET.
20702    On entry *REF_CU is the CU of the source die referencing OFFSET.
20703    On exit *REF_CU is the CU of the result.
20704    Returns NULL if OFFSET is invalid.  */
20705
20706 static struct die_info *
20707 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20708                    struct dwarf2_cu **ref_cu)
20709 {
20710   struct die_info temp_die;
20711   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20712
20713   gdb_assert (cu->per_cu != NULL);
20714
20715   target_cu = cu;
20716
20717   if (cu->per_cu->is_debug_types)
20718     {
20719       /* .debug_types CUs cannot reference anything outside their CU.
20720          If they need to, they have to reference a signatured type via
20721          DW_FORM_ref_sig8.  */
20722       if (!offset_in_cu_p (&cu->header, sect_off))
20723         return NULL;
20724     }
20725   else if (offset_in_dwz != cu->per_cu->is_dwz
20726            || !offset_in_cu_p (&cu->header, sect_off))
20727     {
20728       struct dwarf2_per_cu_data *per_cu;
20729
20730       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20731                                                  cu->objfile);
20732
20733       /* If necessary, add it to the queue and load its DIEs.  */
20734       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20735         load_full_comp_unit (per_cu, cu->language);
20736
20737       target_cu = per_cu->cu;
20738     }
20739   else if (cu->dies == NULL)
20740     {
20741       /* We're loading full DIEs during partial symbol reading.  */
20742       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20743       load_full_comp_unit (cu->per_cu, language_minimal);
20744     }
20745
20746   *ref_cu = target_cu;
20747   temp_die.sect_off = sect_off;
20748   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20749                                                   &temp_die,
20750                                                   to_underlying (sect_off));
20751 }
20752
20753 /* Follow reference attribute ATTR of SRC_DIE.
20754    On entry *REF_CU is the CU of SRC_DIE.
20755    On exit *REF_CU is the CU of the result.  */
20756
20757 static struct die_info *
20758 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20759                 struct dwarf2_cu **ref_cu)
20760 {
20761   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20762   struct dwarf2_cu *cu = *ref_cu;
20763   struct die_info *die;
20764
20765   die = follow_die_offset (sect_off,
20766                            (attr->form == DW_FORM_GNU_ref_alt
20767                             || cu->per_cu->is_dwz),
20768                            ref_cu);
20769   if (!die)
20770     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20771            "at 0x%x [in module %s]"),
20772            to_underlying (sect_off), to_underlying (src_die->sect_off),
20773            objfile_name (cu->objfile));
20774
20775   return die;
20776 }
20777
20778 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20779    Returned value is intended for DW_OP_call*.  Returned
20780    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20781
20782 struct dwarf2_locexpr_baton
20783 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20784                                struct dwarf2_per_cu_data *per_cu,
20785                                CORE_ADDR (*get_frame_pc) (void *baton),
20786                                void *baton)
20787 {
20788   struct dwarf2_cu *cu;
20789   struct die_info *die;
20790   struct attribute *attr;
20791   struct dwarf2_locexpr_baton retval;
20792
20793   dw2_setup (per_cu->objfile);
20794
20795   if (per_cu->cu == NULL)
20796     load_cu (per_cu);
20797   cu = per_cu->cu;
20798   if (cu == NULL)
20799     {
20800       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20801          Instead just throw an error, not much else we can do.  */
20802       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20803              to_underlying (sect_off), objfile_name (per_cu->objfile));
20804     }
20805
20806   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20807   if (!die)
20808     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20809            to_underlying (sect_off), objfile_name (per_cu->objfile));
20810
20811   attr = dwarf2_attr (die, DW_AT_location, cu);
20812   if (!attr)
20813     {
20814       /* DWARF: "If there is no such attribute, then there is no effect.".
20815          DATA is ignored if SIZE is 0.  */
20816
20817       retval.data = NULL;
20818       retval.size = 0;
20819     }
20820   else if (attr_form_is_section_offset (attr))
20821     {
20822       struct dwarf2_loclist_baton loclist_baton;
20823       CORE_ADDR pc = (*get_frame_pc) (baton);
20824       size_t size;
20825
20826       fill_in_loclist_baton (cu, &loclist_baton, attr);
20827
20828       retval.data = dwarf2_find_location_expression (&loclist_baton,
20829                                                      &size, pc);
20830       retval.size = size;
20831     }
20832   else
20833     {
20834       if (!attr_form_is_block (attr))
20835         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20836                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20837                to_underlying (sect_off), objfile_name (per_cu->objfile));
20838
20839       retval.data = DW_BLOCK (attr)->data;
20840       retval.size = DW_BLOCK (attr)->size;
20841     }
20842   retval.per_cu = cu->per_cu;
20843
20844   age_cached_comp_units ();
20845
20846   return retval;
20847 }
20848
20849 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20850    offset.  */
20851
20852 struct dwarf2_locexpr_baton
20853 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20854                              struct dwarf2_per_cu_data *per_cu,
20855                              CORE_ADDR (*get_frame_pc) (void *baton),
20856                              void *baton)
20857 {
20858   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20859
20860   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20861 }
20862
20863 /* Write a constant of a given type as target-ordered bytes into
20864    OBSTACK.  */
20865
20866 static const gdb_byte *
20867 write_constant_as_bytes (struct obstack *obstack,
20868                          enum bfd_endian byte_order,
20869                          struct type *type,
20870                          ULONGEST value,
20871                          LONGEST *len)
20872 {
20873   gdb_byte *result;
20874
20875   *len = TYPE_LENGTH (type);
20876   result = (gdb_byte *) obstack_alloc (obstack, *len);
20877   store_unsigned_integer (result, *len, byte_order, value);
20878
20879   return result;
20880 }
20881
20882 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20883    pointer to the constant bytes and set LEN to the length of the
20884    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20885    does not have a DW_AT_const_value, return NULL.  */
20886
20887 const gdb_byte *
20888 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20889                              struct dwarf2_per_cu_data *per_cu,
20890                              struct obstack *obstack,
20891                              LONGEST *len)
20892 {
20893   struct dwarf2_cu *cu;
20894   struct die_info *die;
20895   struct attribute *attr;
20896   const gdb_byte *result = NULL;
20897   struct type *type;
20898   LONGEST value;
20899   enum bfd_endian byte_order;
20900
20901   dw2_setup (per_cu->objfile);
20902
20903   if (per_cu->cu == NULL)
20904     load_cu (per_cu);
20905   cu = per_cu->cu;
20906   if (cu == NULL)
20907     {
20908       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20909          Instead just throw an error, not much else we can do.  */
20910       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20911              to_underlying (sect_off), objfile_name (per_cu->objfile));
20912     }
20913
20914   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20915   if (!die)
20916     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20917            to_underlying (sect_off), objfile_name (per_cu->objfile));
20918
20919
20920   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20921   if (attr == NULL)
20922     return NULL;
20923
20924   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20925                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20926
20927   switch (attr->form)
20928     {
20929     case DW_FORM_addr:
20930     case DW_FORM_GNU_addr_index:
20931       {
20932         gdb_byte *tem;
20933
20934         *len = cu->header.addr_size;
20935         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20936         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20937         result = tem;
20938       }
20939       break;
20940     case DW_FORM_string:
20941     case DW_FORM_strp:
20942     case DW_FORM_GNU_str_index:
20943     case DW_FORM_GNU_strp_alt:
20944       /* DW_STRING is already allocated on the objfile obstack, point
20945          directly to it.  */
20946       result = (const gdb_byte *) DW_STRING (attr);
20947       *len = strlen (DW_STRING (attr));
20948       break;
20949     case DW_FORM_block1:
20950     case DW_FORM_block2:
20951     case DW_FORM_block4:
20952     case DW_FORM_block:
20953     case DW_FORM_exprloc:
20954     case DW_FORM_data16:
20955       result = DW_BLOCK (attr)->data;
20956       *len = DW_BLOCK (attr)->size;
20957       break;
20958
20959       /* The DW_AT_const_value attributes are supposed to carry the
20960          symbol's value "represented as it would be on the target
20961          architecture."  By the time we get here, it's already been
20962          converted to host endianness, so we just need to sign- or
20963          zero-extend it as appropriate.  */
20964     case DW_FORM_data1:
20965       type = die_type (die, cu);
20966       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20967       if (result == NULL)
20968         result = write_constant_as_bytes (obstack, byte_order,
20969                                           type, value, len);
20970       break;
20971     case DW_FORM_data2:
20972       type = die_type (die, cu);
20973       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20974       if (result == NULL)
20975         result = write_constant_as_bytes (obstack, byte_order,
20976                                           type, value, len);
20977       break;
20978     case DW_FORM_data4:
20979       type = die_type (die, cu);
20980       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20981       if (result == NULL)
20982         result = write_constant_as_bytes (obstack, byte_order,
20983                                           type, value, len);
20984       break;
20985     case DW_FORM_data8:
20986       type = die_type (die, cu);
20987       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20988       if (result == NULL)
20989         result = write_constant_as_bytes (obstack, byte_order,
20990                                           type, value, len);
20991       break;
20992
20993     case DW_FORM_sdata:
20994     case DW_FORM_implicit_const:
20995       type = die_type (die, cu);
20996       result = write_constant_as_bytes (obstack, byte_order,
20997                                         type, DW_SND (attr), len);
20998       break;
20999
21000     case DW_FORM_udata:
21001       type = die_type (die, cu);
21002       result = write_constant_as_bytes (obstack, byte_order,
21003                                         type, DW_UNSND (attr), len);
21004       break;
21005
21006     default:
21007       complaint (&symfile_complaints,
21008                  _("unsupported const value attribute form: '%s'"),
21009                  dwarf_form_name (attr->form));
21010       break;
21011     }
21012
21013   return result;
21014 }
21015
21016 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21017    valid type for this die is found.  */
21018
21019 struct type *
21020 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21021                                 struct dwarf2_per_cu_data *per_cu)
21022 {
21023   struct dwarf2_cu *cu;
21024   struct die_info *die;
21025
21026   dw2_setup (per_cu->objfile);
21027
21028   if (per_cu->cu == NULL)
21029     load_cu (per_cu);
21030   cu = per_cu->cu;
21031   if (!cu)
21032     return NULL;
21033
21034   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21035   if (!die)
21036     return NULL;
21037
21038   return die_type (die, cu);
21039 }
21040
21041 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21042    PER_CU.  */
21043
21044 struct type *
21045 dwarf2_get_die_type (cu_offset die_offset,
21046                      struct dwarf2_per_cu_data *per_cu)
21047 {
21048   dw2_setup (per_cu->objfile);
21049
21050   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21051   return get_die_type_at_offset (die_offset_sect, per_cu);
21052 }
21053
21054 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21055    On entry *REF_CU is the CU of SRC_DIE.
21056    On exit *REF_CU is the CU of the result.
21057    Returns NULL if the referenced DIE isn't found.  */
21058
21059 static struct die_info *
21060 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21061                   struct dwarf2_cu **ref_cu)
21062 {
21063   struct die_info temp_die;
21064   struct dwarf2_cu *sig_cu;
21065   struct die_info *die;
21066
21067   /* While it might be nice to assert sig_type->type == NULL here,
21068      we can get here for DW_AT_imported_declaration where we need
21069      the DIE not the type.  */
21070
21071   /* If necessary, add it to the queue and load its DIEs.  */
21072
21073   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21074     read_signatured_type (sig_type);
21075
21076   sig_cu = sig_type->per_cu.cu;
21077   gdb_assert (sig_cu != NULL);
21078   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21079   temp_die.sect_off = sig_type->type_offset_in_section;
21080   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21081                                                  to_underlying (temp_die.sect_off));
21082   if (die)
21083     {
21084       /* For .gdb_index version 7 keep track of included TUs.
21085          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21086       if (dwarf2_per_objfile->index_table != NULL
21087           && dwarf2_per_objfile->index_table->version <= 7)
21088         {
21089           VEC_safe_push (dwarf2_per_cu_ptr,
21090                          (*ref_cu)->per_cu->imported_symtabs,
21091                          sig_cu->per_cu);
21092         }
21093
21094       *ref_cu = sig_cu;
21095       return die;
21096     }
21097
21098   return NULL;
21099 }
21100
21101 /* Follow signatured type referenced by ATTR in SRC_DIE.
21102    On entry *REF_CU is the CU of SRC_DIE.
21103    On exit *REF_CU is the CU of the result.
21104    The result is the DIE of the type.
21105    If the referenced type cannot be found an error is thrown.  */
21106
21107 static struct die_info *
21108 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21109                 struct dwarf2_cu **ref_cu)
21110 {
21111   ULONGEST signature = DW_SIGNATURE (attr);
21112   struct signatured_type *sig_type;
21113   struct die_info *die;
21114
21115   gdb_assert (attr->form == DW_FORM_ref_sig8);
21116
21117   sig_type = lookup_signatured_type (*ref_cu, signature);
21118   /* sig_type will be NULL if the signatured type is missing from
21119      the debug info.  */
21120   if (sig_type == NULL)
21121     {
21122       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21123                " from DIE at 0x%x [in module %s]"),
21124              hex_string (signature), to_underlying (src_die->sect_off),
21125              objfile_name ((*ref_cu)->objfile));
21126     }
21127
21128   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21129   if (die == NULL)
21130     {
21131       dump_die_for_error (src_die);
21132       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21133                " from DIE at 0x%x [in module %s]"),
21134              hex_string (signature), to_underlying (src_die->sect_off),
21135              objfile_name ((*ref_cu)->objfile));
21136     }
21137
21138   return die;
21139 }
21140
21141 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21142    reading in and processing the type unit if necessary.  */
21143
21144 static struct type *
21145 get_signatured_type (struct die_info *die, ULONGEST signature,
21146                      struct dwarf2_cu *cu)
21147 {
21148   struct signatured_type *sig_type;
21149   struct dwarf2_cu *type_cu;
21150   struct die_info *type_die;
21151   struct type *type;
21152
21153   sig_type = lookup_signatured_type (cu, signature);
21154   /* sig_type will be NULL if the signatured type is missing from
21155      the debug info.  */
21156   if (sig_type == NULL)
21157     {
21158       complaint (&symfile_complaints,
21159                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21160                    " from DIE at 0x%x [in module %s]"),
21161                  hex_string (signature), to_underlying (die->sect_off),
21162                  objfile_name (dwarf2_per_objfile->objfile));
21163       return build_error_marker_type (cu, die);
21164     }
21165
21166   /* If we already know the type we're done.  */
21167   if (sig_type->type != NULL)
21168     return sig_type->type;
21169
21170   type_cu = cu;
21171   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21172   if (type_die != NULL)
21173     {
21174       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21175          is created.  This is important, for example, because for c++ classes
21176          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21177       type = read_type_die (type_die, type_cu);
21178       if (type == NULL)
21179         {
21180           complaint (&symfile_complaints,
21181                      _("Dwarf Error: Cannot build signatured type %s"
21182                        " referenced from DIE at 0x%x [in module %s]"),
21183                      hex_string (signature), to_underlying (die->sect_off),
21184                      objfile_name (dwarf2_per_objfile->objfile));
21185           type = build_error_marker_type (cu, die);
21186         }
21187     }
21188   else
21189     {
21190       complaint (&symfile_complaints,
21191                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21192                    " from DIE at 0x%x [in module %s]"),
21193                  hex_string (signature), to_underlying (die->sect_off),
21194                  objfile_name (dwarf2_per_objfile->objfile));
21195       type = build_error_marker_type (cu, die);
21196     }
21197   sig_type->type = type;
21198
21199   return type;
21200 }
21201
21202 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21203    reading in and processing the type unit if necessary.  */
21204
21205 static struct type *
21206 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21207                           struct dwarf2_cu *cu) /* ARI: editCase function */
21208 {
21209   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21210   if (attr_form_is_ref (attr))
21211     {
21212       struct dwarf2_cu *type_cu = cu;
21213       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21214
21215       return read_type_die (type_die, type_cu);
21216     }
21217   else if (attr->form == DW_FORM_ref_sig8)
21218     {
21219       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21220     }
21221   else
21222     {
21223       complaint (&symfile_complaints,
21224                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21225                    " at 0x%x [in module %s]"),
21226                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21227                  objfile_name (dwarf2_per_objfile->objfile));
21228       return build_error_marker_type (cu, die);
21229     }
21230 }
21231
21232 /* Load the DIEs associated with type unit PER_CU into memory.  */
21233
21234 static void
21235 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21236 {
21237   struct signatured_type *sig_type;
21238
21239   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21240   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21241
21242   /* We have the per_cu, but we need the signatured_type.
21243      Fortunately this is an easy translation.  */
21244   gdb_assert (per_cu->is_debug_types);
21245   sig_type = (struct signatured_type *) per_cu;
21246
21247   gdb_assert (per_cu->cu == NULL);
21248
21249   read_signatured_type (sig_type);
21250
21251   gdb_assert (per_cu->cu != NULL);
21252 }
21253
21254 /* die_reader_func for read_signatured_type.
21255    This is identical to load_full_comp_unit_reader,
21256    but is kept separate for now.  */
21257
21258 static void
21259 read_signatured_type_reader (const struct die_reader_specs *reader,
21260                              const gdb_byte *info_ptr,
21261                              struct die_info *comp_unit_die,
21262                              int has_children,
21263                              void *data)
21264 {
21265   struct dwarf2_cu *cu = reader->cu;
21266
21267   gdb_assert (cu->die_hash == NULL);
21268   cu->die_hash =
21269     htab_create_alloc_ex (cu->header.length / 12,
21270                           die_hash,
21271                           die_eq,
21272                           NULL,
21273                           &cu->comp_unit_obstack,
21274                           hashtab_obstack_allocate,
21275                           dummy_obstack_deallocate);
21276
21277   if (has_children)
21278     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21279                                                   &info_ptr, comp_unit_die);
21280   cu->dies = comp_unit_die;
21281   /* comp_unit_die is not stored in die_hash, no need.  */
21282
21283   /* We try not to read any attributes in this function, because not
21284      all CUs needed for references have been loaded yet, and symbol
21285      table processing isn't initialized.  But we have to set the CU language,
21286      or we won't be able to build types correctly.
21287      Similarly, if we do not read the producer, we can not apply
21288      producer-specific interpretation.  */
21289   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21290 }
21291
21292 /* Read in a signatured type and build its CU and DIEs.
21293    If the type is a stub for the real type in a DWO file,
21294    read in the real type from the DWO file as well.  */
21295
21296 static void
21297 read_signatured_type (struct signatured_type *sig_type)
21298 {
21299   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21300
21301   gdb_assert (per_cu->is_debug_types);
21302   gdb_assert (per_cu->cu == NULL);
21303
21304   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21305                            read_signatured_type_reader, NULL);
21306   sig_type->per_cu.tu_read = 1;
21307 }
21308
21309 /* Decode simple location descriptions.
21310    Given a pointer to a dwarf block that defines a location, compute
21311    the location and return the value.
21312
21313    NOTE drow/2003-11-18: This function is called in two situations
21314    now: for the address of static or global variables (partial symbols
21315    only) and for offsets into structures which are expected to be
21316    (more or less) constant.  The partial symbol case should go away,
21317    and only the constant case should remain.  That will let this
21318    function complain more accurately.  A few special modes are allowed
21319    without complaint for global variables (for instance, global
21320    register values and thread-local values).
21321
21322    A location description containing no operations indicates that the
21323    object is optimized out.  The return value is 0 for that case.
21324    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21325    callers will only want a very basic result and this can become a
21326    complaint.
21327
21328    Note that stack[0] is unused except as a default error return.  */
21329
21330 static CORE_ADDR
21331 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21332 {
21333   struct objfile *objfile = cu->objfile;
21334   size_t i;
21335   size_t size = blk->size;
21336   const gdb_byte *data = blk->data;
21337   CORE_ADDR stack[64];
21338   int stacki;
21339   unsigned int bytes_read, unsnd;
21340   gdb_byte op;
21341
21342   i = 0;
21343   stacki = 0;
21344   stack[stacki] = 0;
21345   stack[++stacki] = 0;
21346
21347   while (i < size)
21348     {
21349       op = data[i++];
21350       switch (op)
21351         {
21352         case DW_OP_lit0:
21353         case DW_OP_lit1:
21354         case DW_OP_lit2:
21355         case DW_OP_lit3:
21356         case DW_OP_lit4:
21357         case DW_OP_lit5:
21358         case DW_OP_lit6:
21359         case DW_OP_lit7:
21360         case DW_OP_lit8:
21361         case DW_OP_lit9:
21362         case DW_OP_lit10:
21363         case DW_OP_lit11:
21364         case DW_OP_lit12:
21365         case DW_OP_lit13:
21366         case DW_OP_lit14:
21367         case DW_OP_lit15:
21368         case DW_OP_lit16:
21369         case DW_OP_lit17:
21370         case DW_OP_lit18:
21371         case DW_OP_lit19:
21372         case DW_OP_lit20:
21373         case DW_OP_lit21:
21374         case DW_OP_lit22:
21375         case DW_OP_lit23:
21376         case DW_OP_lit24:
21377         case DW_OP_lit25:
21378         case DW_OP_lit26:
21379         case DW_OP_lit27:
21380         case DW_OP_lit28:
21381         case DW_OP_lit29:
21382         case DW_OP_lit30:
21383         case DW_OP_lit31:
21384           stack[++stacki] = op - DW_OP_lit0;
21385           break;
21386
21387         case DW_OP_reg0:
21388         case DW_OP_reg1:
21389         case DW_OP_reg2:
21390         case DW_OP_reg3:
21391         case DW_OP_reg4:
21392         case DW_OP_reg5:
21393         case DW_OP_reg6:
21394         case DW_OP_reg7:
21395         case DW_OP_reg8:
21396         case DW_OP_reg9:
21397         case DW_OP_reg10:
21398         case DW_OP_reg11:
21399         case DW_OP_reg12:
21400         case DW_OP_reg13:
21401         case DW_OP_reg14:
21402         case DW_OP_reg15:
21403         case DW_OP_reg16:
21404         case DW_OP_reg17:
21405         case DW_OP_reg18:
21406         case DW_OP_reg19:
21407         case DW_OP_reg20:
21408         case DW_OP_reg21:
21409         case DW_OP_reg22:
21410         case DW_OP_reg23:
21411         case DW_OP_reg24:
21412         case DW_OP_reg25:
21413         case DW_OP_reg26:
21414         case DW_OP_reg27:
21415         case DW_OP_reg28:
21416         case DW_OP_reg29:
21417         case DW_OP_reg30:
21418         case DW_OP_reg31:
21419           stack[++stacki] = op - DW_OP_reg0;
21420           if (i < size)
21421             dwarf2_complex_location_expr_complaint ();
21422           break;
21423
21424         case DW_OP_regx:
21425           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21426           i += bytes_read;
21427           stack[++stacki] = unsnd;
21428           if (i < size)
21429             dwarf2_complex_location_expr_complaint ();
21430           break;
21431
21432         case DW_OP_addr:
21433           stack[++stacki] = read_address (objfile->obfd, &data[i],
21434                                           cu, &bytes_read);
21435           i += bytes_read;
21436           break;
21437
21438         case DW_OP_const1u:
21439           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21440           i += 1;
21441           break;
21442
21443         case DW_OP_const1s:
21444           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21445           i += 1;
21446           break;
21447
21448         case DW_OP_const2u:
21449           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21450           i += 2;
21451           break;
21452
21453         case DW_OP_const2s:
21454           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21455           i += 2;
21456           break;
21457
21458         case DW_OP_const4u:
21459           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21460           i += 4;
21461           break;
21462
21463         case DW_OP_const4s:
21464           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21465           i += 4;
21466           break;
21467
21468         case DW_OP_const8u:
21469           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21470           i += 8;
21471           break;
21472
21473         case DW_OP_constu:
21474           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21475                                                   &bytes_read);
21476           i += bytes_read;
21477           break;
21478
21479         case DW_OP_consts:
21480           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21481           i += bytes_read;
21482           break;
21483
21484         case DW_OP_dup:
21485           stack[stacki + 1] = stack[stacki];
21486           stacki++;
21487           break;
21488
21489         case DW_OP_plus:
21490           stack[stacki - 1] += stack[stacki];
21491           stacki--;
21492           break;
21493
21494         case DW_OP_plus_uconst:
21495           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21496                                                  &bytes_read);
21497           i += bytes_read;
21498           break;
21499
21500         case DW_OP_minus:
21501           stack[stacki - 1] -= stack[stacki];
21502           stacki--;
21503           break;
21504
21505         case DW_OP_deref:
21506           /* If we're not the last op, then we definitely can't encode
21507              this using GDB's address_class enum.  This is valid for partial
21508              global symbols, although the variable's address will be bogus
21509              in the psymtab.  */
21510           if (i < size)
21511             dwarf2_complex_location_expr_complaint ();
21512           break;
21513
21514         case DW_OP_GNU_push_tls_address:
21515         case DW_OP_form_tls_address:
21516           /* The top of the stack has the offset from the beginning
21517              of the thread control block at which the variable is located.  */
21518           /* Nothing should follow this operator, so the top of stack would
21519              be returned.  */
21520           /* This is valid for partial global symbols, but the variable's
21521              address will be bogus in the psymtab.  Make it always at least
21522              non-zero to not look as a variable garbage collected by linker
21523              which have DW_OP_addr 0.  */
21524           if (i < size)
21525             dwarf2_complex_location_expr_complaint ();
21526           stack[stacki]++;
21527           break;
21528
21529         case DW_OP_GNU_uninit:
21530           break;
21531
21532         case DW_OP_GNU_addr_index:
21533         case DW_OP_GNU_const_index:
21534           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21535                                                          &bytes_read);
21536           i += bytes_read;
21537           break;
21538
21539         default:
21540           {
21541             const char *name = get_DW_OP_name (op);
21542
21543             if (name)
21544               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21545                          name);
21546             else
21547               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21548                          op);
21549           }
21550
21551           return (stack[stacki]);
21552         }
21553
21554       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21555          outside of the allocated space.  Also enforce minimum>0.  */
21556       if (stacki >= ARRAY_SIZE (stack) - 1)
21557         {
21558           complaint (&symfile_complaints,
21559                      _("location description stack overflow"));
21560           return 0;
21561         }
21562
21563       if (stacki <= 0)
21564         {
21565           complaint (&symfile_complaints,
21566                      _("location description stack underflow"));
21567           return 0;
21568         }
21569     }
21570   return (stack[stacki]);
21571 }
21572
21573 /* memory allocation interface */
21574
21575 static struct dwarf_block *
21576 dwarf_alloc_block (struct dwarf2_cu *cu)
21577 {
21578   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21579 }
21580
21581 static struct die_info *
21582 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21583 {
21584   struct die_info *die;
21585   size_t size = sizeof (struct die_info);
21586
21587   if (num_attrs > 1)
21588     size += (num_attrs - 1) * sizeof (struct attribute);
21589
21590   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21591   memset (die, 0, sizeof (struct die_info));
21592   return (die);
21593 }
21594
21595 \f
21596 /* Macro support.  */
21597
21598 /* Return file name relative to the compilation directory of file number I in
21599    *LH's file name table.  The result is allocated using xmalloc; the caller is
21600    responsible for freeing it.  */
21601
21602 static char *
21603 file_file_name (int file, struct line_header *lh)
21604 {
21605   /* Is the file number a valid index into the line header's file name
21606      table?  Remember that file numbers start with one, not zero.  */
21607   if (1 <= file && file <= lh->file_names.size ())
21608     {
21609       const file_entry &fe = lh->file_names[file - 1];
21610
21611       if (!IS_ABSOLUTE_PATH (fe.name))
21612         {
21613           const char *dir = fe.include_dir (lh);
21614           if (dir != NULL)
21615             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21616         }
21617       return xstrdup (fe.name);
21618     }
21619   else
21620     {
21621       /* The compiler produced a bogus file number.  We can at least
21622          record the macro definitions made in the file, even if we
21623          won't be able to find the file by name.  */
21624       char fake_name[80];
21625
21626       xsnprintf (fake_name, sizeof (fake_name),
21627                  "<bad macro file number %d>", file);
21628
21629       complaint (&symfile_complaints,
21630                  _("bad file number in macro information (%d)"),
21631                  file);
21632
21633       return xstrdup (fake_name);
21634     }
21635 }
21636
21637 /* Return the full name of file number I in *LH's file name table.
21638    Use COMP_DIR as the name of the current directory of the
21639    compilation.  The result is allocated using xmalloc; the caller is
21640    responsible for freeing it.  */
21641 static char *
21642 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21643 {
21644   /* Is the file number a valid index into the line header's file name
21645      table?  Remember that file numbers start with one, not zero.  */
21646   if (1 <= file && file <= lh->file_names.size ())
21647     {
21648       char *relative = file_file_name (file, lh);
21649
21650       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21651         return relative;
21652       return reconcat (relative, comp_dir, SLASH_STRING,
21653                        relative, (char *) NULL);
21654     }
21655   else
21656     return file_file_name (file, lh);
21657 }
21658
21659
21660 static struct macro_source_file *
21661 macro_start_file (int file, int line,
21662                   struct macro_source_file *current_file,
21663                   struct line_header *lh)
21664 {
21665   /* File name relative to the compilation directory of this source file.  */
21666   char *file_name = file_file_name (file, lh);
21667
21668   if (! current_file)
21669     {
21670       /* Note: We don't create a macro table for this compilation unit
21671          at all until we actually get a filename.  */
21672       struct macro_table *macro_table = get_macro_table ();
21673
21674       /* If we have no current file, then this must be the start_file
21675          directive for the compilation unit's main source file.  */
21676       current_file = macro_set_main (macro_table, file_name);
21677       macro_define_special (macro_table);
21678     }
21679   else
21680     current_file = macro_include (current_file, line, file_name);
21681
21682   xfree (file_name);
21683
21684   return current_file;
21685 }
21686
21687 static const char *
21688 consume_improper_spaces (const char *p, const char *body)
21689 {
21690   if (*p == ' ')
21691     {
21692       complaint (&symfile_complaints,
21693                  _("macro definition contains spaces "
21694                    "in formal argument list:\n`%s'"),
21695                  body);
21696
21697       while (*p == ' ')
21698         p++;
21699     }
21700
21701   return p;
21702 }
21703
21704
21705 static void
21706 parse_macro_definition (struct macro_source_file *file, int line,
21707                         const char *body)
21708 {
21709   const char *p;
21710
21711   /* The body string takes one of two forms.  For object-like macro
21712      definitions, it should be:
21713
21714         <macro name> " " <definition>
21715
21716      For function-like macro definitions, it should be:
21717
21718         <macro name> "() " <definition>
21719      or
21720         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21721
21722      Spaces may appear only where explicitly indicated, and in the
21723      <definition>.
21724
21725      The Dwarf 2 spec says that an object-like macro's name is always
21726      followed by a space, but versions of GCC around March 2002 omit
21727      the space when the macro's definition is the empty string.
21728
21729      The Dwarf 2 spec says that there should be no spaces between the
21730      formal arguments in a function-like macro's formal argument list,
21731      but versions of GCC around March 2002 include spaces after the
21732      commas.  */
21733
21734
21735   /* Find the extent of the macro name.  The macro name is terminated
21736      by either a space or null character (for an object-like macro) or
21737      an opening paren (for a function-like macro).  */
21738   for (p = body; *p; p++)
21739     if (*p == ' ' || *p == '(')
21740       break;
21741
21742   if (*p == ' ' || *p == '\0')
21743     {
21744       /* It's an object-like macro.  */
21745       int name_len = p - body;
21746       char *name = savestring (body, name_len);
21747       const char *replacement;
21748
21749       if (*p == ' ')
21750         replacement = body + name_len + 1;
21751       else
21752         {
21753           dwarf2_macro_malformed_definition_complaint (body);
21754           replacement = body + name_len;
21755         }
21756
21757       macro_define_object (file, line, name, replacement);
21758
21759       xfree (name);
21760     }
21761   else if (*p == '(')
21762     {
21763       /* It's a function-like macro.  */
21764       char *name = savestring (body, p - body);
21765       int argc = 0;
21766       int argv_size = 1;
21767       char **argv = XNEWVEC (char *, argv_size);
21768
21769       p++;
21770
21771       p = consume_improper_spaces (p, body);
21772
21773       /* Parse the formal argument list.  */
21774       while (*p && *p != ')')
21775         {
21776           /* Find the extent of the current argument name.  */
21777           const char *arg_start = p;
21778
21779           while (*p && *p != ',' && *p != ')' && *p != ' ')
21780             p++;
21781
21782           if (! *p || p == arg_start)
21783             dwarf2_macro_malformed_definition_complaint (body);
21784           else
21785             {
21786               /* Make sure argv has room for the new argument.  */
21787               if (argc >= argv_size)
21788                 {
21789                   argv_size *= 2;
21790                   argv = XRESIZEVEC (char *, argv, argv_size);
21791                 }
21792
21793               argv[argc++] = savestring (arg_start, p - arg_start);
21794             }
21795
21796           p = consume_improper_spaces (p, body);
21797
21798           /* Consume the comma, if present.  */
21799           if (*p == ',')
21800             {
21801               p++;
21802
21803               p = consume_improper_spaces (p, body);
21804             }
21805         }
21806
21807       if (*p == ')')
21808         {
21809           p++;
21810
21811           if (*p == ' ')
21812             /* Perfectly formed definition, no complaints.  */
21813             macro_define_function (file, line, name,
21814                                    argc, (const char **) argv,
21815                                    p + 1);
21816           else if (*p == '\0')
21817             {
21818               /* Complain, but do define it.  */
21819               dwarf2_macro_malformed_definition_complaint (body);
21820               macro_define_function (file, line, name,
21821                                      argc, (const char **) argv,
21822                                      p);
21823             }
21824           else
21825             /* Just complain.  */
21826             dwarf2_macro_malformed_definition_complaint (body);
21827         }
21828       else
21829         /* Just complain.  */
21830         dwarf2_macro_malformed_definition_complaint (body);
21831
21832       xfree (name);
21833       {
21834         int i;
21835
21836         for (i = 0; i < argc; i++)
21837           xfree (argv[i]);
21838       }
21839       xfree (argv);
21840     }
21841   else
21842     dwarf2_macro_malformed_definition_complaint (body);
21843 }
21844
21845 /* Skip some bytes from BYTES according to the form given in FORM.
21846    Returns the new pointer.  */
21847
21848 static const gdb_byte *
21849 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21850                  enum dwarf_form form,
21851                  unsigned int offset_size,
21852                  struct dwarf2_section_info *section)
21853 {
21854   unsigned int bytes_read;
21855
21856   switch (form)
21857     {
21858     case DW_FORM_data1:
21859     case DW_FORM_flag:
21860       ++bytes;
21861       break;
21862
21863     case DW_FORM_data2:
21864       bytes += 2;
21865       break;
21866
21867     case DW_FORM_data4:
21868       bytes += 4;
21869       break;
21870
21871     case DW_FORM_data8:
21872       bytes += 8;
21873       break;
21874
21875     case DW_FORM_data16:
21876       bytes += 16;
21877       break;
21878
21879     case DW_FORM_string:
21880       read_direct_string (abfd, bytes, &bytes_read);
21881       bytes += bytes_read;
21882       break;
21883
21884     case DW_FORM_sec_offset:
21885     case DW_FORM_strp:
21886     case DW_FORM_GNU_strp_alt:
21887       bytes += offset_size;
21888       break;
21889
21890     case DW_FORM_block:
21891       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21892       bytes += bytes_read;
21893       break;
21894
21895     case DW_FORM_block1:
21896       bytes += 1 + read_1_byte (abfd, bytes);
21897       break;
21898     case DW_FORM_block2:
21899       bytes += 2 + read_2_bytes (abfd, bytes);
21900       break;
21901     case DW_FORM_block4:
21902       bytes += 4 + read_4_bytes (abfd, bytes);
21903       break;
21904
21905     case DW_FORM_sdata:
21906     case DW_FORM_udata:
21907     case DW_FORM_GNU_addr_index:
21908     case DW_FORM_GNU_str_index:
21909       bytes = gdb_skip_leb128 (bytes, buffer_end);
21910       if (bytes == NULL)
21911         {
21912           dwarf2_section_buffer_overflow_complaint (section);
21913           return NULL;
21914         }
21915       break;
21916
21917     case DW_FORM_implicit_const:
21918       break;
21919
21920     default:
21921       {
21922       complain:
21923         complaint (&symfile_complaints,
21924                    _("invalid form 0x%x in `%s'"),
21925                    form, get_section_name (section));
21926         return NULL;
21927       }
21928     }
21929
21930   return bytes;
21931 }
21932
21933 /* A helper for dwarf_decode_macros that handles skipping an unknown
21934    opcode.  Returns an updated pointer to the macro data buffer; or,
21935    on error, issues a complaint and returns NULL.  */
21936
21937 static const gdb_byte *
21938 skip_unknown_opcode (unsigned int opcode,
21939                      const gdb_byte **opcode_definitions,
21940                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21941                      bfd *abfd,
21942                      unsigned int offset_size,
21943                      struct dwarf2_section_info *section)
21944 {
21945   unsigned int bytes_read, i;
21946   unsigned long arg;
21947   const gdb_byte *defn;
21948
21949   if (opcode_definitions[opcode] == NULL)
21950     {
21951       complaint (&symfile_complaints,
21952                  _("unrecognized DW_MACFINO opcode 0x%x"),
21953                  opcode);
21954       return NULL;
21955     }
21956
21957   defn = opcode_definitions[opcode];
21958   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21959   defn += bytes_read;
21960
21961   for (i = 0; i < arg; ++i)
21962     {
21963       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21964                                  (enum dwarf_form) defn[i], offset_size,
21965                                  section);
21966       if (mac_ptr == NULL)
21967         {
21968           /* skip_form_bytes already issued the complaint.  */
21969           return NULL;
21970         }
21971     }
21972
21973   return mac_ptr;
21974 }
21975
21976 /* A helper function which parses the header of a macro section.
21977    If the macro section is the extended (for now called "GNU") type,
21978    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21979    the header, or issues a complaint and returns NULL on error.  */
21980
21981 static const gdb_byte *
21982 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21983                           bfd *abfd,
21984                           const gdb_byte *mac_ptr,
21985                           unsigned int *offset_size,
21986                           int section_is_gnu)
21987 {
21988   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21989
21990   if (section_is_gnu)
21991     {
21992       unsigned int version, flags;
21993
21994       version = read_2_bytes (abfd, mac_ptr);
21995       if (version != 4 && version != 5)
21996         {
21997           complaint (&symfile_complaints,
21998                      _("unrecognized version `%d' in .debug_macro section"),
21999                      version);
22000           return NULL;
22001         }
22002       mac_ptr += 2;
22003
22004       flags = read_1_byte (abfd, mac_ptr);
22005       ++mac_ptr;
22006       *offset_size = (flags & 1) ? 8 : 4;
22007
22008       if ((flags & 2) != 0)
22009         /* We don't need the line table offset.  */
22010         mac_ptr += *offset_size;
22011
22012       /* Vendor opcode descriptions.  */
22013       if ((flags & 4) != 0)
22014         {
22015           unsigned int i, count;
22016
22017           count = read_1_byte (abfd, mac_ptr);
22018           ++mac_ptr;
22019           for (i = 0; i < count; ++i)
22020             {
22021               unsigned int opcode, bytes_read;
22022               unsigned long arg;
22023
22024               opcode = read_1_byte (abfd, mac_ptr);
22025               ++mac_ptr;
22026               opcode_definitions[opcode] = mac_ptr;
22027               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22028               mac_ptr += bytes_read;
22029               mac_ptr += arg;
22030             }
22031         }
22032     }
22033
22034   return mac_ptr;
22035 }
22036
22037 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22038    including DW_MACRO_import.  */
22039
22040 static void
22041 dwarf_decode_macro_bytes (bfd *abfd,
22042                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22043                           struct macro_source_file *current_file,
22044                           struct line_header *lh,
22045                           struct dwarf2_section_info *section,
22046                           int section_is_gnu, int section_is_dwz,
22047                           unsigned int offset_size,
22048                           htab_t include_hash)
22049 {
22050   struct objfile *objfile = dwarf2_per_objfile->objfile;
22051   enum dwarf_macro_record_type macinfo_type;
22052   int at_commandline;
22053   const gdb_byte *opcode_definitions[256];
22054
22055   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22056                                       &offset_size, section_is_gnu);
22057   if (mac_ptr == NULL)
22058     {
22059       /* We already issued a complaint.  */
22060       return;
22061     }
22062
22063   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22064      GDB is still reading the definitions from command line.  First
22065      DW_MACINFO_start_file will need to be ignored as it was already executed
22066      to create CURRENT_FILE for the main source holding also the command line
22067      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22068      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22069
22070   at_commandline = 1;
22071
22072   do
22073     {
22074       /* Do we at least have room for a macinfo type byte?  */
22075       if (mac_ptr >= mac_end)
22076         {
22077           dwarf2_section_buffer_overflow_complaint (section);
22078           break;
22079         }
22080
22081       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22082       mac_ptr++;
22083
22084       /* Note that we rely on the fact that the corresponding GNU and
22085          DWARF constants are the same.  */
22086       switch (macinfo_type)
22087         {
22088           /* A zero macinfo type indicates the end of the macro
22089              information.  */
22090         case 0:
22091           break;
22092
22093         case DW_MACRO_define:
22094         case DW_MACRO_undef:
22095         case DW_MACRO_define_strp:
22096         case DW_MACRO_undef_strp:
22097         case DW_MACRO_define_sup:
22098         case DW_MACRO_undef_sup:
22099           {
22100             unsigned int bytes_read;
22101             int line;
22102             const char *body;
22103             int is_define;
22104
22105             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22106             mac_ptr += bytes_read;
22107
22108             if (macinfo_type == DW_MACRO_define
22109                 || macinfo_type == DW_MACRO_undef)
22110               {
22111                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22112                 mac_ptr += bytes_read;
22113               }
22114             else
22115               {
22116                 LONGEST str_offset;
22117
22118                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22119                 mac_ptr += offset_size;
22120
22121                 if (macinfo_type == DW_MACRO_define_sup
22122                     || macinfo_type == DW_MACRO_undef_sup
22123                     || section_is_dwz)
22124                   {
22125                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22126
22127                     body = read_indirect_string_from_dwz (dwz, str_offset);
22128                   }
22129                 else
22130                   body = read_indirect_string_at_offset (abfd, str_offset);
22131               }
22132
22133             is_define = (macinfo_type == DW_MACRO_define
22134                          || macinfo_type == DW_MACRO_define_strp
22135                          || macinfo_type == DW_MACRO_define_sup);
22136             if (! current_file)
22137               {
22138                 /* DWARF violation as no main source is present.  */
22139                 complaint (&symfile_complaints,
22140                            _("debug info with no main source gives macro %s "
22141                              "on line %d: %s"),
22142                            is_define ? _("definition") : _("undefinition"),
22143                            line, body);
22144                 break;
22145               }
22146             if ((line == 0 && !at_commandline)
22147                 || (line != 0 && at_commandline))
22148               complaint (&symfile_complaints,
22149                          _("debug info gives %s macro %s with %s line %d: %s"),
22150                          at_commandline ? _("command-line") : _("in-file"),
22151                          is_define ? _("definition") : _("undefinition"),
22152                          line == 0 ? _("zero") : _("non-zero"), line, body);
22153
22154             if (is_define)
22155               parse_macro_definition (current_file, line, body);
22156             else
22157               {
22158                 gdb_assert (macinfo_type == DW_MACRO_undef
22159                             || macinfo_type == DW_MACRO_undef_strp
22160                             || macinfo_type == DW_MACRO_undef_sup);
22161                 macro_undef (current_file, line, body);
22162               }
22163           }
22164           break;
22165
22166         case DW_MACRO_start_file:
22167           {
22168             unsigned int bytes_read;
22169             int line, file;
22170
22171             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22172             mac_ptr += bytes_read;
22173             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22174             mac_ptr += bytes_read;
22175
22176             if ((line == 0 && !at_commandline)
22177                 || (line != 0 && at_commandline))
22178               complaint (&symfile_complaints,
22179                          _("debug info gives source %d included "
22180                            "from %s at %s line %d"),
22181                          file, at_commandline ? _("command-line") : _("file"),
22182                          line == 0 ? _("zero") : _("non-zero"), line);
22183
22184             if (at_commandline)
22185               {
22186                 /* This DW_MACRO_start_file was executed in the
22187                    pass one.  */
22188                 at_commandline = 0;
22189               }
22190             else
22191               current_file = macro_start_file (file, line, current_file, lh);
22192           }
22193           break;
22194
22195         case DW_MACRO_end_file:
22196           if (! current_file)
22197             complaint (&symfile_complaints,
22198                        _("macro debug info has an unmatched "
22199                          "`close_file' directive"));
22200           else
22201             {
22202               current_file = current_file->included_by;
22203               if (! current_file)
22204                 {
22205                   enum dwarf_macro_record_type next_type;
22206
22207                   /* GCC circa March 2002 doesn't produce the zero
22208                      type byte marking the end of the compilation
22209                      unit.  Complain if it's not there, but exit no
22210                      matter what.  */
22211
22212                   /* Do we at least have room for a macinfo type byte?  */
22213                   if (mac_ptr >= mac_end)
22214                     {
22215                       dwarf2_section_buffer_overflow_complaint (section);
22216                       return;
22217                     }
22218
22219                   /* We don't increment mac_ptr here, so this is just
22220                      a look-ahead.  */
22221                   next_type
22222                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22223                                                                   mac_ptr);
22224                   if (next_type != 0)
22225                     complaint (&symfile_complaints,
22226                                _("no terminating 0-type entry for "
22227                                  "macros in `.debug_macinfo' section"));
22228
22229                   return;
22230                 }
22231             }
22232           break;
22233
22234         case DW_MACRO_import:
22235         case DW_MACRO_import_sup:
22236           {
22237             LONGEST offset;
22238             void **slot;
22239             bfd *include_bfd = abfd;
22240             struct dwarf2_section_info *include_section = section;
22241             const gdb_byte *include_mac_end = mac_end;
22242             int is_dwz = section_is_dwz;
22243             const gdb_byte *new_mac_ptr;
22244
22245             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22246             mac_ptr += offset_size;
22247
22248             if (macinfo_type == DW_MACRO_import_sup)
22249               {
22250                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22251
22252                 dwarf2_read_section (objfile, &dwz->macro);
22253
22254                 include_section = &dwz->macro;
22255                 include_bfd = get_section_bfd_owner (include_section);
22256                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22257                 is_dwz = 1;
22258               }
22259
22260             new_mac_ptr = include_section->buffer + offset;
22261             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22262
22263             if (*slot != NULL)
22264               {
22265                 /* This has actually happened; see
22266                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22267                 complaint (&symfile_complaints,
22268                            _("recursive DW_MACRO_import in "
22269                              ".debug_macro section"));
22270               }
22271             else
22272               {
22273                 *slot = (void *) new_mac_ptr;
22274
22275                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22276                                           include_mac_end, current_file, lh,
22277                                           section, section_is_gnu, is_dwz,
22278                                           offset_size, include_hash);
22279
22280                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22281               }
22282           }
22283           break;
22284
22285         case DW_MACINFO_vendor_ext:
22286           if (!section_is_gnu)
22287             {
22288               unsigned int bytes_read;
22289
22290               /* This reads the constant, but since we don't recognize
22291                  any vendor extensions, we ignore it.  */
22292               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22293               mac_ptr += bytes_read;
22294               read_direct_string (abfd, mac_ptr, &bytes_read);
22295               mac_ptr += bytes_read;
22296
22297               /* We don't recognize any vendor extensions.  */
22298               break;
22299             }
22300           /* FALLTHROUGH */
22301
22302         default:
22303           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22304                                          mac_ptr, mac_end, abfd, offset_size,
22305                                          section);
22306           if (mac_ptr == NULL)
22307             return;
22308           break;
22309         }
22310     } while (macinfo_type != 0);
22311 }
22312
22313 static void
22314 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22315                      int section_is_gnu)
22316 {
22317   struct objfile *objfile = dwarf2_per_objfile->objfile;
22318   struct line_header *lh = cu->line_header;
22319   bfd *abfd;
22320   const gdb_byte *mac_ptr, *mac_end;
22321   struct macro_source_file *current_file = 0;
22322   enum dwarf_macro_record_type macinfo_type;
22323   unsigned int offset_size = cu->header.offset_size;
22324   const gdb_byte *opcode_definitions[256];
22325   struct cleanup *cleanup;
22326   void **slot;
22327   struct dwarf2_section_info *section;
22328   const char *section_name;
22329
22330   if (cu->dwo_unit != NULL)
22331     {
22332       if (section_is_gnu)
22333         {
22334           section = &cu->dwo_unit->dwo_file->sections.macro;
22335           section_name = ".debug_macro.dwo";
22336         }
22337       else
22338         {
22339           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22340           section_name = ".debug_macinfo.dwo";
22341         }
22342     }
22343   else
22344     {
22345       if (section_is_gnu)
22346         {
22347           section = &dwarf2_per_objfile->macro;
22348           section_name = ".debug_macro";
22349         }
22350       else
22351         {
22352           section = &dwarf2_per_objfile->macinfo;
22353           section_name = ".debug_macinfo";
22354         }
22355     }
22356
22357   dwarf2_read_section (objfile, section);
22358   if (section->buffer == NULL)
22359     {
22360       complaint (&symfile_complaints, _("missing %s section"), section_name);
22361       return;
22362     }
22363   abfd = get_section_bfd_owner (section);
22364
22365   /* First pass: Find the name of the base filename.
22366      This filename is needed in order to process all macros whose definition
22367      (or undefinition) comes from the command line.  These macros are defined
22368      before the first DW_MACINFO_start_file entry, and yet still need to be
22369      associated to the base file.
22370
22371      To determine the base file name, we scan the macro definitions until we
22372      reach the first DW_MACINFO_start_file entry.  We then initialize
22373      CURRENT_FILE accordingly so that any macro definition found before the
22374      first DW_MACINFO_start_file can still be associated to the base file.  */
22375
22376   mac_ptr = section->buffer + offset;
22377   mac_end = section->buffer + section->size;
22378
22379   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22380                                       &offset_size, section_is_gnu);
22381   if (mac_ptr == NULL)
22382     {
22383       /* We already issued a complaint.  */
22384       return;
22385     }
22386
22387   do
22388     {
22389       /* Do we at least have room for a macinfo type byte?  */
22390       if (mac_ptr >= mac_end)
22391         {
22392           /* Complaint is printed during the second pass as GDB will probably
22393              stop the first pass earlier upon finding
22394              DW_MACINFO_start_file.  */
22395           break;
22396         }
22397
22398       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22399       mac_ptr++;
22400
22401       /* Note that we rely on the fact that the corresponding GNU and
22402          DWARF constants are the same.  */
22403       switch (macinfo_type)
22404         {
22405           /* A zero macinfo type indicates the end of the macro
22406              information.  */
22407         case 0:
22408           break;
22409
22410         case DW_MACRO_define:
22411         case DW_MACRO_undef:
22412           /* Only skip the data by MAC_PTR.  */
22413           {
22414             unsigned int bytes_read;
22415
22416             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22417             mac_ptr += bytes_read;
22418             read_direct_string (abfd, mac_ptr, &bytes_read);
22419             mac_ptr += bytes_read;
22420           }
22421           break;
22422
22423         case DW_MACRO_start_file:
22424           {
22425             unsigned int bytes_read;
22426             int line, file;
22427
22428             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22429             mac_ptr += bytes_read;
22430             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22431             mac_ptr += bytes_read;
22432
22433             current_file = macro_start_file (file, line, current_file, lh);
22434           }
22435           break;
22436
22437         case DW_MACRO_end_file:
22438           /* No data to skip by MAC_PTR.  */
22439           break;
22440
22441         case DW_MACRO_define_strp:
22442         case DW_MACRO_undef_strp:
22443         case DW_MACRO_define_sup:
22444         case DW_MACRO_undef_sup:
22445           {
22446             unsigned int bytes_read;
22447
22448             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22449             mac_ptr += bytes_read;
22450             mac_ptr += offset_size;
22451           }
22452           break;
22453
22454         case DW_MACRO_import:
22455         case DW_MACRO_import_sup:
22456           /* Note that, according to the spec, a transparent include
22457              chain cannot call DW_MACRO_start_file.  So, we can just
22458              skip this opcode.  */
22459           mac_ptr += offset_size;
22460           break;
22461
22462         case DW_MACINFO_vendor_ext:
22463           /* Only skip the data by MAC_PTR.  */
22464           if (!section_is_gnu)
22465             {
22466               unsigned int bytes_read;
22467
22468               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22469               mac_ptr += bytes_read;
22470               read_direct_string (abfd, mac_ptr, &bytes_read);
22471               mac_ptr += bytes_read;
22472             }
22473           /* FALLTHROUGH */
22474
22475         default:
22476           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22477                                          mac_ptr, mac_end, abfd, offset_size,
22478                                          section);
22479           if (mac_ptr == NULL)
22480             return;
22481           break;
22482         }
22483     } while (macinfo_type != 0 && current_file == NULL);
22484
22485   /* Second pass: Process all entries.
22486
22487      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22488      command-line macro definitions/undefinitions.  This flag is unset when we
22489      reach the first DW_MACINFO_start_file entry.  */
22490
22491   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22492                                            htab_eq_pointer,
22493                                            NULL, xcalloc, xfree));
22494   mac_ptr = section->buffer + offset;
22495   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22496   *slot = (void *) mac_ptr;
22497   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22498                             current_file, lh, section,
22499                             section_is_gnu, 0, offset_size,
22500                             include_hash.get ());
22501 }
22502
22503 /* Check if the attribute's form is a DW_FORM_block*
22504    if so return true else false.  */
22505
22506 static int
22507 attr_form_is_block (const struct attribute *attr)
22508 {
22509   return (attr == NULL ? 0 :
22510       attr->form == DW_FORM_block1
22511       || attr->form == DW_FORM_block2
22512       || attr->form == DW_FORM_block4
22513       || attr->form == DW_FORM_block
22514       || attr->form == DW_FORM_exprloc);
22515 }
22516
22517 /* Return non-zero if ATTR's value is a section offset --- classes
22518    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22519    You may use DW_UNSND (attr) to retrieve such offsets.
22520
22521    Section 7.5.4, "Attribute Encodings", explains that no attribute
22522    may have a value that belongs to more than one of these classes; it
22523    would be ambiguous if we did, because we use the same forms for all
22524    of them.  */
22525
22526 static int
22527 attr_form_is_section_offset (const struct attribute *attr)
22528 {
22529   return (attr->form == DW_FORM_data4
22530           || attr->form == DW_FORM_data8
22531           || attr->form == DW_FORM_sec_offset);
22532 }
22533
22534 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22535    zero otherwise.  When this function returns true, you can apply
22536    dwarf2_get_attr_constant_value to it.
22537
22538    However, note that for some attributes you must check
22539    attr_form_is_section_offset before using this test.  DW_FORM_data4
22540    and DW_FORM_data8 are members of both the constant class, and of
22541    the classes that contain offsets into other debug sections
22542    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22543    that, if an attribute's can be either a constant or one of the
22544    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22545    taken as section offsets, not constants.
22546
22547    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22548    cannot handle that.  */
22549
22550 static int
22551 attr_form_is_constant (const struct attribute *attr)
22552 {
22553   switch (attr->form)
22554     {
22555     case DW_FORM_sdata:
22556     case DW_FORM_udata:
22557     case DW_FORM_data1:
22558     case DW_FORM_data2:
22559     case DW_FORM_data4:
22560     case DW_FORM_data8:
22561     case DW_FORM_implicit_const:
22562       return 1;
22563     default:
22564       return 0;
22565     }
22566 }
22567
22568
22569 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22570    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22571
22572 static int
22573 attr_form_is_ref (const struct attribute *attr)
22574 {
22575   switch (attr->form)
22576     {
22577     case DW_FORM_ref_addr:
22578     case DW_FORM_ref1:
22579     case DW_FORM_ref2:
22580     case DW_FORM_ref4:
22581     case DW_FORM_ref8:
22582     case DW_FORM_ref_udata:
22583     case DW_FORM_GNU_ref_alt:
22584       return 1;
22585     default:
22586       return 0;
22587     }
22588 }
22589
22590 /* Return the .debug_loc section to use for CU.
22591    For DWO files use .debug_loc.dwo.  */
22592
22593 static struct dwarf2_section_info *
22594 cu_debug_loc_section (struct dwarf2_cu *cu)
22595 {
22596   if (cu->dwo_unit)
22597     {
22598       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22599       
22600       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22601     }
22602   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22603                                   : &dwarf2_per_objfile->loc);
22604 }
22605
22606 /* A helper function that fills in a dwarf2_loclist_baton.  */
22607
22608 static void
22609 fill_in_loclist_baton (struct dwarf2_cu *cu,
22610                        struct dwarf2_loclist_baton *baton,
22611                        const struct attribute *attr)
22612 {
22613   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22614
22615   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22616
22617   baton->per_cu = cu->per_cu;
22618   gdb_assert (baton->per_cu);
22619   /* We don't know how long the location list is, but make sure we
22620      don't run off the edge of the section.  */
22621   baton->size = section->size - DW_UNSND (attr);
22622   baton->data = section->buffer + DW_UNSND (attr);
22623   baton->base_address = cu->base_address;
22624   baton->from_dwo = cu->dwo_unit != NULL;
22625 }
22626
22627 static void
22628 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22629                              struct dwarf2_cu *cu, int is_block)
22630 {
22631   struct objfile *objfile = dwarf2_per_objfile->objfile;
22632   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22633
22634   if (attr_form_is_section_offset (attr)
22635       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22636          the section.  If so, fall through to the complaint in the
22637          other branch.  */
22638       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22639     {
22640       struct dwarf2_loclist_baton *baton;
22641
22642       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22643
22644       fill_in_loclist_baton (cu, baton, attr);
22645
22646       if (cu->base_known == 0)
22647         complaint (&symfile_complaints,
22648                    _("Location list used without "
22649                      "specifying the CU base address."));
22650
22651       SYMBOL_ACLASS_INDEX (sym) = (is_block
22652                                    ? dwarf2_loclist_block_index
22653                                    : dwarf2_loclist_index);
22654       SYMBOL_LOCATION_BATON (sym) = baton;
22655     }
22656   else
22657     {
22658       struct dwarf2_locexpr_baton *baton;
22659
22660       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22661       baton->per_cu = cu->per_cu;
22662       gdb_assert (baton->per_cu);
22663
22664       if (attr_form_is_block (attr))
22665         {
22666           /* Note that we're just copying the block's data pointer
22667              here, not the actual data.  We're still pointing into the
22668              info_buffer for SYM's objfile; right now we never release
22669              that buffer, but when we do clean up properly this may
22670              need to change.  */
22671           baton->size = DW_BLOCK (attr)->size;
22672           baton->data = DW_BLOCK (attr)->data;
22673         }
22674       else
22675         {
22676           dwarf2_invalid_attrib_class_complaint ("location description",
22677                                                  SYMBOL_NATURAL_NAME (sym));
22678           baton->size = 0;
22679         }
22680
22681       SYMBOL_ACLASS_INDEX (sym) = (is_block
22682                                    ? dwarf2_locexpr_block_index
22683                                    : dwarf2_locexpr_index);
22684       SYMBOL_LOCATION_BATON (sym) = baton;
22685     }
22686 }
22687
22688 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22689    came from a separate debuginfo file, then the master objfile is
22690    returned.  */
22691
22692 struct objfile *
22693 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22694 {
22695   struct objfile *objfile = per_cu->objfile;
22696
22697   /* Return the master objfile, so that we can report and look up the
22698      correct file containing this variable.  */
22699   if (objfile->separate_debug_objfile_backlink)
22700     objfile = objfile->separate_debug_objfile_backlink;
22701
22702   return objfile;
22703 }
22704
22705 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22706    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22707    CU_HEADERP first.  */
22708
22709 static const struct comp_unit_head *
22710 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22711                        struct dwarf2_per_cu_data *per_cu)
22712 {
22713   const gdb_byte *info_ptr;
22714
22715   if (per_cu->cu)
22716     return &per_cu->cu->header;
22717
22718   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22719
22720   memset (cu_headerp, 0, sizeof (*cu_headerp));
22721   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22722                        rcuh_kind::COMPILE);
22723
22724   return cu_headerp;
22725 }
22726
22727 /* Return the address size given in the compilation unit header for CU.  */
22728
22729 int
22730 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22731 {
22732   struct comp_unit_head cu_header_local;
22733   const struct comp_unit_head *cu_headerp;
22734
22735   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22736
22737   return cu_headerp->addr_size;
22738 }
22739
22740 /* Return the offset size given in the compilation unit header for CU.  */
22741
22742 int
22743 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22744 {
22745   struct comp_unit_head cu_header_local;
22746   const struct comp_unit_head *cu_headerp;
22747
22748   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22749
22750   return cu_headerp->offset_size;
22751 }
22752
22753 /* See its dwarf2loc.h declaration.  */
22754
22755 int
22756 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22757 {
22758   struct comp_unit_head cu_header_local;
22759   const struct comp_unit_head *cu_headerp;
22760
22761   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22762
22763   if (cu_headerp->version == 2)
22764     return cu_headerp->addr_size;
22765   else
22766     return cu_headerp->offset_size;
22767 }
22768
22769 /* Return the text offset of the CU.  The returned offset comes from
22770    this CU's objfile.  If this objfile came from a separate debuginfo
22771    file, then the offset may be different from the corresponding
22772    offset in the parent objfile.  */
22773
22774 CORE_ADDR
22775 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22776 {
22777   struct objfile *objfile = per_cu->objfile;
22778
22779   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22780 }
22781
22782 /* Return DWARF version number of PER_CU.  */
22783
22784 short
22785 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22786 {
22787   return per_cu->dwarf_version;
22788 }
22789
22790 /* Locate the .debug_info compilation unit from CU's objfile which contains
22791    the DIE at OFFSET.  Raises an error on failure.  */
22792
22793 static struct dwarf2_per_cu_data *
22794 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22795                                   unsigned int offset_in_dwz,
22796                                   struct objfile *objfile)
22797 {
22798   struct dwarf2_per_cu_data *this_cu;
22799   int low, high;
22800   const sect_offset *cu_off;
22801
22802   low = 0;
22803   high = dwarf2_per_objfile->n_comp_units - 1;
22804   while (high > low)
22805     {
22806       struct dwarf2_per_cu_data *mid_cu;
22807       int mid = low + (high - low) / 2;
22808
22809       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22810       cu_off = &mid_cu->sect_off;
22811       if (mid_cu->is_dwz > offset_in_dwz
22812           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22813         high = mid;
22814       else
22815         low = mid + 1;
22816     }
22817   gdb_assert (low == high);
22818   this_cu = dwarf2_per_objfile->all_comp_units[low];
22819   cu_off = &this_cu->sect_off;
22820   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22821     {
22822       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22823         error (_("Dwarf Error: could not find partial DIE containing "
22824                "offset 0x%x [in module %s]"),
22825                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22826
22827       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22828                   <= sect_off);
22829       return dwarf2_per_objfile->all_comp_units[low-1];
22830     }
22831   else
22832     {
22833       this_cu = dwarf2_per_objfile->all_comp_units[low];
22834       if (low == dwarf2_per_objfile->n_comp_units - 1
22835           && sect_off >= this_cu->sect_off + this_cu->length)
22836         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22837       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22838       return this_cu;
22839     }
22840 }
22841
22842 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22843
22844 static void
22845 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22846 {
22847   memset (cu, 0, sizeof (*cu));
22848   per_cu->cu = cu;
22849   cu->per_cu = per_cu;
22850   cu->objfile = per_cu->objfile;
22851   obstack_init (&cu->comp_unit_obstack);
22852 }
22853
22854 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22855
22856 static void
22857 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22858                        enum language pretend_language)
22859 {
22860   struct attribute *attr;
22861
22862   /* Set the language we're debugging.  */
22863   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22864   if (attr)
22865     set_cu_language (DW_UNSND (attr), cu);
22866   else
22867     {
22868       cu->language = pretend_language;
22869       cu->language_defn = language_def (cu->language);
22870     }
22871
22872   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22873 }
22874
22875 /* Release one cached compilation unit, CU.  We unlink it from the tree
22876    of compilation units, but we don't remove it from the read_in_chain;
22877    the caller is responsible for that.
22878    NOTE: DATA is a void * because this function is also used as a
22879    cleanup routine.  */
22880
22881 static void
22882 free_heap_comp_unit (void *data)
22883 {
22884   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22885
22886   gdb_assert (cu->per_cu != NULL);
22887   cu->per_cu->cu = NULL;
22888   cu->per_cu = NULL;
22889
22890   obstack_free (&cu->comp_unit_obstack, NULL);
22891
22892   xfree (cu);
22893 }
22894
22895 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22896    when we're finished with it.  We can't free the pointer itself, but be
22897    sure to unlink it from the cache.  Also release any associated storage.  */
22898
22899 static void
22900 free_stack_comp_unit (void *data)
22901 {
22902   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22903
22904   gdb_assert (cu->per_cu != NULL);
22905   cu->per_cu->cu = NULL;
22906   cu->per_cu = NULL;
22907
22908   obstack_free (&cu->comp_unit_obstack, NULL);
22909   cu->partial_dies = NULL;
22910 }
22911
22912 /* Free all cached compilation units.  */
22913
22914 static void
22915 free_cached_comp_units (void *data)
22916 {
22917   dwarf2_per_objfile->free_cached_comp_units ();
22918 }
22919
22920 /* Increase the age counter on each cached compilation unit, and free
22921    any that are too old.  */
22922
22923 static void
22924 age_cached_comp_units (void)
22925 {
22926   struct dwarf2_per_cu_data *per_cu, **last_chain;
22927
22928   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22929   per_cu = dwarf2_per_objfile->read_in_chain;
22930   while (per_cu != NULL)
22931     {
22932       per_cu->cu->last_used ++;
22933       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22934         dwarf2_mark (per_cu->cu);
22935       per_cu = per_cu->cu->read_in_chain;
22936     }
22937
22938   per_cu = dwarf2_per_objfile->read_in_chain;
22939   last_chain = &dwarf2_per_objfile->read_in_chain;
22940   while (per_cu != NULL)
22941     {
22942       struct dwarf2_per_cu_data *next_cu;
22943
22944       next_cu = per_cu->cu->read_in_chain;
22945
22946       if (!per_cu->cu->mark)
22947         {
22948           free_heap_comp_unit (per_cu->cu);
22949           *last_chain = next_cu;
22950         }
22951       else
22952         last_chain = &per_cu->cu->read_in_chain;
22953
22954       per_cu = next_cu;
22955     }
22956 }
22957
22958 /* Remove a single compilation unit from the cache.  */
22959
22960 static void
22961 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22962 {
22963   struct dwarf2_per_cu_data *per_cu, **last_chain;
22964
22965   per_cu = dwarf2_per_objfile->read_in_chain;
22966   last_chain = &dwarf2_per_objfile->read_in_chain;
22967   while (per_cu != NULL)
22968     {
22969       struct dwarf2_per_cu_data *next_cu;
22970
22971       next_cu = per_cu->cu->read_in_chain;
22972
22973       if (per_cu == target_per_cu)
22974         {
22975           free_heap_comp_unit (per_cu->cu);
22976           per_cu->cu = NULL;
22977           *last_chain = next_cu;
22978           break;
22979         }
22980       else
22981         last_chain = &per_cu->cu->read_in_chain;
22982
22983       per_cu = next_cu;
22984     }
22985 }
22986
22987 /* Release all extra memory associated with OBJFILE.  */
22988
22989 void
22990 dwarf2_free_objfile (struct objfile *objfile)
22991 {
22992   dwarf2_per_objfile
22993     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22994                                                   dwarf2_objfile_data_key);
22995
22996   if (dwarf2_per_objfile == NULL)
22997     return;
22998
22999   dwarf2_per_objfile->~dwarf2_per_objfile ();
23000 }
23001
23002 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23003    We store these in a hash table separate from the DIEs, and preserve them
23004    when the DIEs are flushed out of cache.
23005
23006    The CU "per_cu" pointer is needed because offset alone is not enough to
23007    uniquely identify the type.  A file may have multiple .debug_types sections,
23008    or the type may come from a DWO file.  Furthermore, while it's more logical
23009    to use per_cu->section+offset, with Fission the section with the data is in
23010    the DWO file but we don't know that section at the point we need it.
23011    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23012    because we can enter the lookup routine, get_die_type_at_offset, from
23013    outside this file, and thus won't necessarily have PER_CU->cu.
23014    Fortunately, PER_CU is stable for the life of the objfile.  */
23015
23016 struct dwarf2_per_cu_offset_and_type
23017 {
23018   const struct dwarf2_per_cu_data *per_cu;
23019   sect_offset sect_off;
23020   struct type *type;
23021 };
23022
23023 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23024
23025 static hashval_t
23026 per_cu_offset_and_type_hash (const void *item)
23027 {
23028   const struct dwarf2_per_cu_offset_and_type *ofs
23029     = (const struct dwarf2_per_cu_offset_and_type *) item;
23030
23031   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23032 }
23033
23034 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23035
23036 static int
23037 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23038 {
23039   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23040     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23041   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23042     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23043
23044   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23045           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23046 }
23047
23048 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23049    table if necessary.  For convenience, return TYPE.
23050
23051    The DIEs reading must have careful ordering to:
23052     * Not cause infite loops trying to read in DIEs as a prerequisite for
23053       reading current DIE.
23054     * Not trying to dereference contents of still incompletely read in types
23055       while reading in other DIEs.
23056     * Enable referencing still incompletely read in types just by a pointer to
23057       the type without accessing its fields.
23058
23059    Therefore caller should follow these rules:
23060      * Try to fetch any prerequisite types we may need to build this DIE type
23061        before building the type and calling set_die_type.
23062      * After building type call set_die_type for current DIE as soon as
23063        possible before fetching more types to complete the current type.
23064      * Make the type as complete as possible before fetching more types.  */
23065
23066 static struct type *
23067 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23068 {
23069   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23070   struct objfile *objfile = cu->objfile;
23071   struct attribute *attr;
23072   struct dynamic_prop prop;
23073
23074   /* For Ada types, make sure that the gnat-specific data is always
23075      initialized (if not already set).  There are a few types where
23076      we should not be doing so, because the type-specific area is
23077      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23078      where the type-specific area is used to store the floatformat).
23079      But this is not a problem, because the gnat-specific information
23080      is actually not needed for these types.  */
23081   if (need_gnat_info (cu)
23082       && TYPE_CODE (type) != TYPE_CODE_FUNC
23083       && TYPE_CODE (type) != TYPE_CODE_FLT
23084       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23085       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23086       && TYPE_CODE (type) != TYPE_CODE_METHOD
23087       && !HAVE_GNAT_AUX_INFO (type))
23088     INIT_GNAT_SPECIFIC (type);
23089
23090   /* Read DW_AT_allocated and set in type.  */
23091   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23092   if (attr_form_is_block (attr))
23093     {
23094       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23095         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23096     }
23097   else if (attr != NULL)
23098     {
23099       complaint (&symfile_complaints,
23100                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23101                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23102                  to_underlying (die->sect_off));
23103     }
23104
23105   /* Read DW_AT_associated and set in type.  */
23106   attr = dwarf2_attr (die, DW_AT_associated, cu);
23107   if (attr_form_is_block (attr))
23108     {
23109       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23110         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23111     }
23112   else if (attr != NULL)
23113     {
23114       complaint (&symfile_complaints,
23115                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23116                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23117                  to_underlying (die->sect_off));
23118     }
23119
23120   /* Read DW_AT_data_location and set in type.  */
23121   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23122   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23123     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23124
23125   if (dwarf2_per_objfile->die_type_hash == NULL)
23126     {
23127       dwarf2_per_objfile->die_type_hash =
23128         htab_create_alloc_ex (127,
23129                               per_cu_offset_and_type_hash,
23130                               per_cu_offset_and_type_eq,
23131                               NULL,
23132                               &objfile->objfile_obstack,
23133                               hashtab_obstack_allocate,
23134                               dummy_obstack_deallocate);
23135     }
23136
23137   ofs.per_cu = cu->per_cu;
23138   ofs.sect_off = die->sect_off;
23139   ofs.type = type;
23140   slot = (struct dwarf2_per_cu_offset_and_type **)
23141     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23142   if (*slot)
23143     complaint (&symfile_complaints,
23144                _("A problem internal to GDB: DIE 0x%x has type already set"),
23145                to_underlying (die->sect_off));
23146   *slot = XOBNEW (&objfile->objfile_obstack,
23147                   struct dwarf2_per_cu_offset_and_type);
23148   **slot = ofs;
23149   return type;
23150 }
23151
23152 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23153    or return NULL if the die does not have a saved type.  */
23154
23155 static struct type *
23156 get_die_type_at_offset (sect_offset sect_off,
23157                         struct dwarf2_per_cu_data *per_cu)
23158 {
23159   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23160
23161   if (dwarf2_per_objfile->die_type_hash == NULL)
23162     return NULL;
23163
23164   ofs.per_cu = per_cu;
23165   ofs.sect_off = sect_off;
23166   slot = ((struct dwarf2_per_cu_offset_and_type *)
23167           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23168   if (slot)
23169     return slot->type;
23170   else
23171     return NULL;
23172 }
23173
23174 /* Look up the type for DIE in CU in die_type_hash,
23175    or return NULL if DIE does not have a saved type.  */
23176
23177 static struct type *
23178 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23179 {
23180   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23181 }
23182
23183 /* Add a dependence relationship from CU to REF_PER_CU.  */
23184
23185 static void
23186 dwarf2_add_dependence (struct dwarf2_cu *cu,
23187                        struct dwarf2_per_cu_data *ref_per_cu)
23188 {
23189   void **slot;
23190
23191   if (cu->dependencies == NULL)
23192     cu->dependencies
23193       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23194                               NULL, &cu->comp_unit_obstack,
23195                               hashtab_obstack_allocate,
23196                               dummy_obstack_deallocate);
23197
23198   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23199   if (*slot == NULL)
23200     *slot = ref_per_cu;
23201 }
23202
23203 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23204    Set the mark field in every compilation unit in the
23205    cache that we must keep because we are keeping CU.  */
23206
23207 static int
23208 dwarf2_mark_helper (void **slot, void *data)
23209 {
23210   struct dwarf2_per_cu_data *per_cu;
23211
23212   per_cu = (struct dwarf2_per_cu_data *) *slot;
23213
23214   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23215      reading of the chain.  As such dependencies remain valid it is not much
23216      useful to track and undo them during QUIT cleanups.  */
23217   if (per_cu->cu == NULL)
23218     return 1;
23219
23220   if (per_cu->cu->mark)
23221     return 1;
23222   per_cu->cu->mark = 1;
23223
23224   if (per_cu->cu->dependencies != NULL)
23225     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23226
23227   return 1;
23228 }
23229
23230 /* Set the mark field in CU and in every other compilation unit in the
23231    cache that we must keep because we are keeping CU.  */
23232
23233 static void
23234 dwarf2_mark (struct dwarf2_cu *cu)
23235 {
23236   if (cu->mark)
23237     return;
23238   cu->mark = 1;
23239   if (cu->dependencies != NULL)
23240     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23241 }
23242
23243 static void
23244 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23245 {
23246   while (per_cu)
23247     {
23248       per_cu->cu->mark = 0;
23249       per_cu = per_cu->cu->read_in_chain;
23250     }
23251 }
23252
23253 /* Trivial hash function for partial_die_info: the hash value of a DIE
23254    is its offset in .debug_info for this objfile.  */
23255
23256 static hashval_t
23257 partial_die_hash (const void *item)
23258 {
23259   const struct partial_die_info *part_die
23260     = (const struct partial_die_info *) item;
23261
23262   return to_underlying (part_die->sect_off);
23263 }
23264
23265 /* Trivial comparison function for partial_die_info structures: two DIEs
23266    are equal if they have the same offset.  */
23267
23268 static int
23269 partial_die_eq (const void *item_lhs, const void *item_rhs)
23270 {
23271   const struct partial_die_info *part_die_lhs
23272     = (const struct partial_die_info *) item_lhs;
23273   const struct partial_die_info *part_die_rhs
23274     = (const struct partial_die_info *) item_rhs;
23275
23276   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23277 }
23278
23279 static struct cmd_list_element *set_dwarf_cmdlist;
23280 static struct cmd_list_element *show_dwarf_cmdlist;
23281
23282 static void
23283 set_dwarf_cmd (char *args, int from_tty)
23284 {
23285   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23286              gdb_stdout);
23287 }
23288
23289 static void
23290 show_dwarf_cmd (char *args, int from_tty)
23291 {
23292   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23293 }
23294
23295 /* Free data associated with OBJFILE, if necessary.  */
23296
23297 static void
23298 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23299 {
23300   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23301   int ix;
23302
23303   /* Make sure we don't accidentally use dwarf2_per_objfile while
23304      cleaning up.  */
23305   dwarf2_per_objfile = NULL;
23306
23307   for (ix = 0; ix < data->n_comp_units; ++ix)
23308    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23309
23310   for (ix = 0; ix < data->n_type_units; ++ix)
23311     VEC_free (dwarf2_per_cu_ptr,
23312               data->all_type_units[ix]->per_cu.imported_symtabs);
23313   xfree (data->all_type_units);
23314
23315   VEC_free (dwarf2_section_info_def, data->types);
23316
23317   if (data->dwo_files)
23318     free_dwo_files (data->dwo_files, objfile);
23319   if (data->dwp_file)
23320     gdb_bfd_unref (data->dwp_file->dbfd);
23321
23322   if (data->dwz_file && data->dwz_file->dwz_bfd)
23323     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23324 }
23325
23326 \f
23327 /* The "save gdb-index" command.  */
23328
23329 /* In-memory buffer to prepare data to be written later to a file.  */
23330 class data_buf
23331 {
23332 public:
23333   /* Copy DATA to the end of the buffer.  */
23334   template<typename T>
23335   void append_data (const T &data)
23336   {
23337     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23338                reinterpret_cast<const gdb_byte *> (&data + 1),
23339                grow (sizeof (data)));
23340   }
23341
23342   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23343      terminating zero is appended too.  */
23344   void append_cstr0 (const char *cstr)
23345   {
23346     const size_t size = strlen (cstr) + 1;
23347     std::copy (cstr, cstr + size, grow (size));
23348   }
23349
23350   /* Accept a host-format integer in VAL and append it to the buffer
23351      as a target-format integer which is LEN bytes long.  */
23352   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23353   {
23354     ::store_unsigned_integer (grow (len), len, byte_order, val);
23355   }
23356
23357   /* Return the size of the buffer.  */
23358   size_t size () const
23359   {
23360     return m_vec.size ();
23361   }
23362
23363   /* Write the buffer to FILE.  */
23364   void file_write (FILE *file) const
23365   {
23366     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23367       error (_("couldn't write data to file"));
23368   }
23369
23370 private:
23371   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23372      the start of the new block.  */
23373   gdb_byte *grow (size_t size)
23374   {
23375     m_vec.resize (m_vec.size () + size);
23376     return &*m_vec.end () - size;
23377   }
23378
23379   gdb::byte_vector m_vec;
23380 };
23381
23382 /* An entry in the symbol table.  */
23383 struct symtab_index_entry
23384 {
23385   /* The name of the symbol.  */
23386   const char *name;
23387   /* The offset of the name in the constant pool.  */
23388   offset_type index_offset;
23389   /* A sorted vector of the indices of all the CUs that hold an object
23390      of this name.  */
23391   std::vector<offset_type> cu_indices;
23392 };
23393
23394 /* The symbol table.  This is a power-of-2-sized hash table.  */
23395 struct mapped_symtab
23396 {
23397   mapped_symtab ()
23398   {
23399     data.resize (1024);
23400   }
23401
23402   offset_type n_elements = 0;
23403   std::vector<symtab_index_entry> data;
23404 };
23405
23406 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23407    the slot.
23408    
23409    Function is used only during write_hash_table so no index format backward
23410    compatibility is needed.  */
23411
23412 static symtab_index_entry &
23413 find_slot (struct mapped_symtab *symtab, const char *name)
23414 {
23415   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23416
23417   index = hash & (symtab->data.size () - 1);
23418   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23419
23420   for (;;)
23421     {
23422       if (symtab->data[index].name == NULL
23423           || strcmp (name, symtab->data[index].name) == 0)
23424         return symtab->data[index];
23425       index = (index + step) & (symtab->data.size () - 1);
23426     }
23427 }
23428
23429 /* Expand SYMTAB's hash table.  */
23430
23431 static void
23432 hash_expand (struct mapped_symtab *symtab)
23433 {
23434   auto old_entries = std::move (symtab->data);
23435
23436   symtab->data.clear ();
23437   symtab->data.resize (old_entries.size () * 2);
23438
23439   for (auto &it : old_entries)
23440     if (it.name != NULL)
23441       {
23442         auto &ref = find_slot (symtab, it.name);
23443         ref = std::move (it);
23444       }
23445 }
23446
23447 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23448    CU_INDEX is the index of the CU in which the symbol appears.
23449    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23450
23451 static void
23452 add_index_entry (struct mapped_symtab *symtab, const char *name,
23453                  int is_static, gdb_index_symbol_kind kind,
23454                  offset_type cu_index)
23455 {
23456   offset_type cu_index_and_attrs;
23457
23458   ++symtab->n_elements;
23459   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23460     hash_expand (symtab);
23461
23462   symtab_index_entry &slot = find_slot (symtab, name);
23463   if (slot.name == NULL)
23464     {
23465       slot.name = name;
23466       /* index_offset is set later.  */
23467     }
23468
23469   cu_index_and_attrs = 0;
23470   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23471   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23472   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23473
23474   /* We don't want to record an index value twice as we want to avoid the
23475      duplication.
23476      We process all global symbols and then all static symbols
23477      (which would allow us to avoid the duplication by only having to check
23478      the last entry pushed), but a symbol could have multiple kinds in one CU.
23479      To keep things simple we don't worry about the duplication here and
23480      sort and uniqufy the list after we've processed all symbols.  */
23481   slot.cu_indices.push_back (cu_index_and_attrs);
23482 }
23483
23484 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23485
23486 static void
23487 uniquify_cu_indices (struct mapped_symtab *symtab)
23488 {
23489   for (auto &entry : symtab->data)
23490     {
23491       if (entry.name != NULL && !entry.cu_indices.empty ())
23492         {
23493           auto &cu_indices = entry.cu_indices;
23494           std::sort (cu_indices.begin (), cu_indices.end ());
23495           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23496           cu_indices.erase (from, cu_indices.end ());
23497         }
23498     }
23499 }
23500
23501 /* A form of 'const char *' suitable for container keys.  Only the
23502    pointer is stored.  The strings themselves are compared, not the
23503    pointers.  */
23504 class c_str_view
23505 {
23506 public:
23507   c_str_view (const char *cstr)
23508     : m_cstr (cstr)
23509   {}
23510
23511   bool operator== (const c_str_view &other) const
23512   {
23513     return strcmp (m_cstr, other.m_cstr) == 0;
23514   }
23515
23516 private:
23517   friend class c_str_view_hasher;
23518   const char *const m_cstr;
23519 };
23520
23521 /* A std::unordered_map::hasher for c_str_view that uses the right
23522    hash function for strings in a mapped index.  */
23523 class c_str_view_hasher
23524 {
23525 public:
23526   size_t operator () (const c_str_view &x) const
23527   {
23528     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23529   }
23530 };
23531
23532 /* A std::unordered_map::hasher for std::vector<>.  */
23533 template<typename T>
23534 class vector_hasher
23535 {
23536 public:
23537   size_t operator () (const std::vector<T> &key) const
23538   {
23539     return iterative_hash (key.data (),
23540                            sizeof (key.front ()) * key.size (), 0);
23541   }
23542 };
23543
23544 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23545    constant pool entries going into the data buffer CPOOL.  */
23546
23547 static void
23548 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23549 {
23550   {
23551     /* Elements are sorted vectors of the indices of all the CUs that
23552        hold an object of this name.  */
23553     std::unordered_map<std::vector<offset_type>, offset_type,
23554                        vector_hasher<offset_type>>
23555       symbol_hash_table;
23556
23557     /* We add all the index vectors to the constant pool first, to
23558        ensure alignment is ok.  */
23559     for (symtab_index_entry &entry : symtab->data)
23560       {
23561         if (entry.name == NULL)
23562           continue;
23563         gdb_assert (entry.index_offset == 0);
23564
23565         /* Finding before inserting is faster than always trying to
23566            insert, because inserting always allocates a node, does the
23567            lookup, and then destroys the new node if another node
23568            already had the same key.  C++17 try_emplace will avoid
23569            this.  */
23570         const auto found
23571           = symbol_hash_table.find (entry.cu_indices);
23572         if (found != symbol_hash_table.end ())
23573           {
23574             entry.index_offset = found->second;
23575             continue;
23576           }
23577
23578         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23579         entry.index_offset = cpool.size ();
23580         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23581         for (const auto index : entry.cu_indices)
23582           cpool.append_data (MAYBE_SWAP (index));
23583       }
23584   }
23585
23586   /* Now write out the hash table.  */
23587   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23588   for (const auto &entry : symtab->data)
23589     {
23590       offset_type str_off, vec_off;
23591
23592       if (entry.name != NULL)
23593         {
23594           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23595           if (insertpair.second)
23596             cpool.append_cstr0 (entry.name);
23597           str_off = insertpair.first->second;
23598           vec_off = entry.index_offset;
23599         }
23600       else
23601         {
23602           /* While 0 is a valid constant pool index, it is not valid
23603              to have 0 for both offsets.  */
23604           str_off = 0;
23605           vec_off = 0;
23606         }
23607
23608       output.append_data (MAYBE_SWAP (str_off));
23609       output.append_data (MAYBE_SWAP (vec_off));
23610     }
23611 }
23612
23613 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23614
23615 /* Helper struct for building the address table.  */
23616 struct addrmap_index_data
23617 {
23618   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23619     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23620   {}
23621
23622   struct objfile *objfile;
23623   data_buf &addr_vec;
23624   psym_index_map &cu_index_htab;
23625
23626   /* Non-zero if the previous_* fields are valid.
23627      We can't write an entry until we see the next entry (since it is only then
23628      that we know the end of the entry).  */
23629   int previous_valid;
23630   /* Index of the CU in the table of all CUs in the index file.  */
23631   unsigned int previous_cu_index;
23632   /* Start address of the CU.  */
23633   CORE_ADDR previous_cu_start;
23634 };
23635
23636 /* Write an address entry to ADDR_VEC.  */
23637
23638 static void
23639 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23640                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23641 {
23642   CORE_ADDR baseaddr;
23643
23644   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23645
23646   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23647   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23648   addr_vec.append_data (MAYBE_SWAP (cu_index));
23649 }
23650
23651 /* Worker function for traversing an addrmap to build the address table.  */
23652
23653 static int
23654 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23655 {
23656   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23657   struct partial_symtab *pst = (struct partial_symtab *) obj;
23658
23659   if (data->previous_valid)
23660     add_address_entry (data->objfile, data->addr_vec,
23661                        data->previous_cu_start, start_addr,
23662                        data->previous_cu_index);
23663
23664   data->previous_cu_start = start_addr;
23665   if (pst != NULL)
23666     {
23667       const auto it = data->cu_index_htab.find (pst);
23668       gdb_assert (it != data->cu_index_htab.cend ());
23669       data->previous_cu_index = it->second;
23670       data->previous_valid = 1;
23671     }
23672   else
23673     data->previous_valid = 0;
23674
23675   return 0;
23676 }
23677
23678 /* Write OBJFILE's address map to ADDR_VEC.
23679    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23680    in the index file.  */
23681
23682 static void
23683 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23684                    psym_index_map &cu_index_htab)
23685 {
23686   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23687
23688   /* When writing the address table, we have to cope with the fact that
23689      the addrmap iterator only provides the start of a region; we have to
23690      wait until the next invocation to get the start of the next region.  */
23691
23692   addrmap_index_data.objfile = objfile;
23693   addrmap_index_data.previous_valid = 0;
23694
23695   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23696                    &addrmap_index_data);
23697
23698   /* It's highly unlikely the last entry (end address = 0xff...ff)
23699      is valid, but we should still handle it.
23700      The end address is recorded as the start of the next region, but that
23701      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23702      anyway.  */
23703   if (addrmap_index_data.previous_valid)
23704     add_address_entry (objfile, addr_vec,
23705                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23706                        addrmap_index_data.previous_cu_index);
23707 }
23708
23709 /* Return the symbol kind of PSYM.  */
23710
23711 static gdb_index_symbol_kind
23712 symbol_kind (struct partial_symbol *psym)
23713 {
23714   domain_enum domain = PSYMBOL_DOMAIN (psym);
23715   enum address_class aclass = PSYMBOL_CLASS (psym);
23716
23717   switch (domain)
23718     {
23719     case VAR_DOMAIN:
23720       switch (aclass)
23721         {
23722         case LOC_BLOCK:
23723           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23724         case LOC_TYPEDEF:
23725           return GDB_INDEX_SYMBOL_KIND_TYPE;
23726         case LOC_COMPUTED:
23727         case LOC_CONST_BYTES:
23728         case LOC_OPTIMIZED_OUT:
23729         case LOC_STATIC:
23730           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23731         case LOC_CONST:
23732           /* Note: It's currently impossible to recognize psyms as enum values
23733              short of reading the type info.  For now punt.  */
23734           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23735         default:
23736           /* There are other LOC_FOO values that one might want to classify
23737              as variables, but dwarf2read.c doesn't currently use them.  */
23738           return GDB_INDEX_SYMBOL_KIND_OTHER;
23739         }
23740     case STRUCT_DOMAIN:
23741       return GDB_INDEX_SYMBOL_KIND_TYPE;
23742     default:
23743       return GDB_INDEX_SYMBOL_KIND_OTHER;
23744     }
23745 }
23746
23747 /* Add a list of partial symbols to SYMTAB.  */
23748
23749 static void
23750 write_psymbols (struct mapped_symtab *symtab,
23751                 std::unordered_set<partial_symbol *> &psyms_seen,
23752                 struct partial_symbol **psymp,
23753                 int count,
23754                 offset_type cu_index,
23755                 int is_static)
23756 {
23757   for (; count-- > 0; ++psymp)
23758     {
23759       struct partial_symbol *psym = *psymp;
23760
23761       if (SYMBOL_LANGUAGE (psym) == language_ada)
23762         error (_("Ada is not currently supported by the index"));
23763
23764       /* Only add a given psymbol once.  */
23765       if (psyms_seen.insert (psym).second)
23766         {
23767           gdb_index_symbol_kind kind = symbol_kind (psym);
23768
23769           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23770                            is_static, kind, cu_index);
23771         }
23772     }
23773 }
23774
23775 /* A helper struct used when iterating over debug_types.  */
23776 struct signatured_type_index_data
23777 {
23778   signatured_type_index_data (data_buf &types_list_,
23779                               std::unordered_set<partial_symbol *> &psyms_seen_)
23780     : types_list (types_list_), psyms_seen (psyms_seen_)
23781   {}
23782
23783   struct objfile *objfile;
23784   struct mapped_symtab *symtab;
23785   data_buf &types_list;
23786   std::unordered_set<partial_symbol *> &psyms_seen;
23787   int cu_index;
23788 };
23789
23790 /* A helper function that writes a single signatured_type to an
23791    obstack.  */
23792
23793 static int
23794 write_one_signatured_type (void **slot, void *d)
23795 {
23796   struct signatured_type_index_data *info
23797     = (struct signatured_type_index_data *) d;
23798   struct signatured_type *entry = (struct signatured_type *) *slot;
23799   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23800
23801   write_psymbols (info->symtab,
23802                   info->psyms_seen,
23803                   info->objfile->global_psymbols.list
23804                   + psymtab->globals_offset,
23805                   psymtab->n_global_syms, info->cu_index,
23806                   0);
23807   write_psymbols (info->symtab,
23808                   info->psyms_seen,
23809                   info->objfile->static_psymbols.list
23810                   + psymtab->statics_offset,
23811                   psymtab->n_static_syms, info->cu_index,
23812                   1);
23813
23814   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23815                                 to_underlying (entry->per_cu.sect_off));
23816   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23817                                 to_underlying (entry->type_offset_in_tu));
23818   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23819
23820   ++info->cu_index;
23821
23822   return 1;
23823 }
23824
23825 /* Recurse into all "included" dependencies and count their symbols as
23826    if they appeared in this psymtab.  */
23827
23828 static void
23829 recursively_count_psymbols (struct partial_symtab *psymtab,
23830                             size_t &psyms_seen)
23831 {
23832   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23833     if (psymtab->dependencies[i]->user != NULL)
23834       recursively_count_psymbols (psymtab->dependencies[i],
23835                                   psyms_seen);
23836
23837   psyms_seen += psymtab->n_global_syms;
23838   psyms_seen += psymtab->n_static_syms;
23839 }
23840
23841 /* Recurse into all "included" dependencies and write their symbols as
23842    if they appeared in this psymtab.  */
23843
23844 static void
23845 recursively_write_psymbols (struct objfile *objfile,
23846                             struct partial_symtab *psymtab,
23847                             struct mapped_symtab *symtab,
23848                             std::unordered_set<partial_symbol *> &psyms_seen,
23849                             offset_type cu_index)
23850 {
23851   int i;
23852
23853   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23854     if (psymtab->dependencies[i]->user != NULL)
23855       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23856                                   symtab, psyms_seen, cu_index);
23857
23858   write_psymbols (symtab,
23859                   psyms_seen,
23860                   objfile->global_psymbols.list + psymtab->globals_offset,
23861                   psymtab->n_global_syms, cu_index,
23862                   0);
23863   write_psymbols (symtab,
23864                   psyms_seen,
23865                   objfile->static_psymbols.list + psymtab->statics_offset,
23866                   psymtab->n_static_syms, cu_index,
23867                   1);
23868 }
23869
23870 /* Create an index file for OBJFILE in the directory DIR.  */
23871
23872 static void
23873 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23874 {
23875   if (dwarf2_per_objfile->using_index)
23876     error (_("Cannot use an index to create the index"));
23877
23878   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23879     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23880
23881   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23882     return;
23883
23884   struct stat st;
23885   if (stat (objfile_name (objfile), &st) < 0)
23886     perror_with_name (objfile_name (objfile));
23887
23888   std::string filename (std::string (dir) + SLASH_STRING
23889                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23890
23891   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23892   if (!out_file)
23893     error (_("Can't open `%s' for writing"), filename.c_str ());
23894
23895   /* Order matters here; we want FILE to be closed before FILENAME is
23896      unlinked, because on MS-Windows one cannot delete a file that is
23897      still open.  (Don't call anything here that might throw until
23898      file_closer is created.)  */
23899   gdb::unlinker unlink_file (filename.c_str ());
23900   gdb_file_up close_out_file (out_file);
23901
23902   mapped_symtab symtab;
23903   data_buf cu_list;
23904
23905   /* While we're scanning CU's create a table that maps a psymtab pointer
23906      (which is what addrmap records) to its index (which is what is recorded
23907      in the index file).  This will later be needed to write the address
23908      table.  */
23909   psym_index_map cu_index_htab;
23910   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23911
23912   /* The CU list is already sorted, so we don't need to do additional
23913      work here.  Also, the debug_types entries do not appear in
23914      all_comp_units, but only in their own hash table.  */
23915
23916   /* The psyms_seen set is potentially going to be largish (~40k
23917      elements when indexing a -g3 build of GDB itself).  Estimate the
23918      number of elements in order to avoid too many rehashes, which
23919      require rebuilding buckets and thus many trips to
23920      malloc/free.  */
23921   size_t psyms_count = 0;
23922   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23923     {
23924       struct dwarf2_per_cu_data *per_cu
23925         = dwarf2_per_objfile->all_comp_units[i];
23926       struct partial_symtab *psymtab = per_cu->v.psymtab;
23927
23928       if (psymtab != NULL && psymtab->user == NULL)
23929         recursively_count_psymbols (psymtab, psyms_count);
23930     }
23931   /* Generating an index for gdb itself shows a ratio of
23932      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23933   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23934   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23935     {
23936       struct dwarf2_per_cu_data *per_cu
23937         = dwarf2_per_objfile->all_comp_units[i];
23938       struct partial_symtab *psymtab = per_cu->v.psymtab;
23939
23940       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23941          It may be referenced from a local scope but in such case it does not
23942          need to be present in .gdb_index.  */
23943       if (psymtab == NULL)
23944         continue;
23945
23946       if (psymtab->user == NULL)
23947         recursively_write_psymbols (objfile, psymtab, &symtab,
23948                                     psyms_seen, i);
23949
23950       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23951       gdb_assert (insertpair.second);
23952
23953       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23954                            to_underlying (per_cu->sect_off));
23955       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23956     }
23957
23958   /* Dump the address map.  */
23959   data_buf addr_vec;
23960   write_address_map (objfile, addr_vec, cu_index_htab);
23961
23962   /* Write out the .debug_type entries, if any.  */
23963   data_buf types_cu_list;
23964   if (dwarf2_per_objfile->signatured_types)
23965     {
23966       signatured_type_index_data sig_data (types_cu_list,
23967                                            psyms_seen);
23968
23969       sig_data.objfile = objfile;
23970       sig_data.symtab = &symtab;
23971       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23972       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23973                               write_one_signatured_type, &sig_data);
23974     }
23975
23976   /* Now that we've processed all symbols we can shrink their cu_indices
23977      lists.  */
23978   uniquify_cu_indices (&symtab);
23979
23980   data_buf symtab_vec, constant_pool;
23981   write_hash_table (&symtab, symtab_vec, constant_pool);
23982
23983   data_buf contents;
23984   const offset_type size_of_contents = 6 * sizeof (offset_type);
23985   offset_type total_len = size_of_contents;
23986
23987   /* The version number.  */
23988   contents.append_data (MAYBE_SWAP (8));
23989
23990   /* The offset of the CU list from the start of the file.  */
23991   contents.append_data (MAYBE_SWAP (total_len));
23992   total_len += cu_list.size ();
23993
23994   /* The offset of the types CU list from the start of the file.  */
23995   contents.append_data (MAYBE_SWAP (total_len));
23996   total_len += types_cu_list.size ();
23997
23998   /* The offset of the address table from the start of the file.  */
23999   contents.append_data (MAYBE_SWAP (total_len));
24000   total_len += addr_vec.size ();
24001
24002   /* The offset of the symbol table from the start of the file.  */
24003   contents.append_data (MAYBE_SWAP (total_len));
24004   total_len += symtab_vec.size ();
24005
24006   /* The offset of the constant pool from the start of the file.  */
24007   contents.append_data (MAYBE_SWAP (total_len));
24008   total_len += constant_pool.size ();
24009
24010   gdb_assert (contents.size () == size_of_contents);
24011
24012   contents.file_write (out_file);
24013   cu_list.file_write (out_file);
24014   types_cu_list.file_write (out_file);
24015   addr_vec.file_write (out_file);
24016   symtab_vec.file_write (out_file);
24017   constant_pool.file_write (out_file);
24018
24019   /* We want to keep the file.  */
24020   unlink_file.keep ();
24021 }
24022
24023 /* Implementation of the `save gdb-index' command.
24024    
24025    Note that the file format used by this command is documented in the
24026    GDB manual.  Any changes here must be documented there.  */
24027
24028 static void
24029 save_gdb_index_command (char *arg, int from_tty)
24030 {
24031   struct objfile *objfile;
24032
24033   if (!arg || !*arg)
24034     error (_("usage: save gdb-index DIRECTORY"));
24035
24036   ALL_OBJFILES (objfile)
24037   {
24038     struct stat st;
24039
24040     /* If the objfile does not correspond to an actual file, skip it.  */
24041     if (stat (objfile_name (objfile), &st) < 0)
24042       continue;
24043
24044     dwarf2_per_objfile
24045       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24046                                                     dwarf2_objfile_data_key);
24047     if (dwarf2_per_objfile)
24048       {
24049
24050         TRY
24051           {
24052             write_psymtabs_to_index (objfile, arg);
24053           }
24054         CATCH (except, RETURN_MASK_ERROR)
24055           {
24056             exception_fprintf (gdb_stderr, except,
24057                                _("Error while writing index for `%s': "),
24058                                objfile_name (objfile));
24059           }
24060         END_CATCH
24061       }
24062   }
24063 }
24064
24065 \f
24066
24067 int dwarf_always_disassemble;
24068
24069 static void
24070 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24071                                struct cmd_list_element *c, const char *value)
24072 {
24073   fprintf_filtered (file,
24074                     _("Whether to always disassemble "
24075                       "DWARF expressions is %s.\n"),
24076                     value);
24077 }
24078
24079 static void
24080 show_check_physname (struct ui_file *file, int from_tty,
24081                      struct cmd_list_element *c, const char *value)
24082 {
24083   fprintf_filtered (file,
24084                     _("Whether to check \"physname\" is %s.\n"),
24085                     value);
24086 }
24087
24088 void
24089 _initialize_dwarf2_read (void)
24090 {
24091   struct cmd_list_element *c;
24092
24093   dwarf2_objfile_data_key
24094     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24095
24096   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24097 Set DWARF specific variables.\n\
24098 Configure DWARF variables such as the cache size"),
24099                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24100                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24101
24102   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24103 Show DWARF specific variables\n\
24104 Show DWARF variables such as the cache size"),
24105                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24106                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24107
24108   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24109                             &dwarf_max_cache_age, _("\
24110 Set the upper bound on the age of cached DWARF compilation units."), _("\
24111 Show the upper bound on the age of cached DWARF compilation units."), _("\
24112 A higher limit means that cached compilation units will be stored\n\
24113 in memory longer, and more total memory will be used.  Zero disables\n\
24114 caching, which can slow down startup."),
24115                             NULL,
24116                             show_dwarf_max_cache_age,
24117                             &set_dwarf_cmdlist,
24118                             &show_dwarf_cmdlist);
24119
24120   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24121                            &dwarf_always_disassemble, _("\
24122 Set whether `info address' always disassembles DWARF expressions."), _("\
24123 Show whether `info address' always disassembles DWARF expressions."), _("\
24124 When enabled, DWARF expressions are always printed in an assembly-like\n\
24125 syntax.  When disabled, expressions will be printed in a more\n\
24126 conversational style, when possible."),
24127                            NULL,
24128                            show_dwarf_always_disassemble,
24129                            &set_dwarf_cmdlist,
24130                            &show_dwarf_cmdlist);
24131
24132   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24133 Set debugging of the DWARF reader."), _("\
24134 Show debugging of the DWARF reader."), _("\
24135 When enabled (non-zero), debugging messages are printed during DWARF\n\
24136 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24137 information.  A value greater than 1 provides more verbose information."),
24138                             NULL,
24139                             NULL,
24140                             &setdebuglist, &showdebuglist);
24141
24142   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24143 Set debugging of the DWARF DIE reader."), _("\
24144 Show debugging of the DWARF DIE reader."), _("\
24145 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24146 The value is the maximum depth to print."),
24147                              NULL,
24148                              NULL,
24149                              &setdebuglist, &showdebuglist);
24150
24151   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24152 Set debugging of the dwarf line reader."), _("\
24153 Show debugging of the dwarf line reader."), _("\
24154 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24155 A value of 1 (one) provides basic information.\n\
24156 A value greater than 1 provides more verbose information."),
24157                              NULL,
24158                              NULL,
24159                              &setdebuglist, &showdebuglist);
24160
24161   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24162 Set cross-checking of \"physname\" code against demangler."), _("\
24163 Show cross-checking of \"physname\" code against demangler."), _("\
24164 When enabled, GDB's internal \"physname\" code is checked against\n\
24165 the demangler."),
24166                            NULL, show_check_physname,
24167                            &setdebuglist, &showdebuglist);
24168
24169   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24170                            no_class, &use_deprecated_index_sections, _("\
24171 Set whether to use deprecated gdb_index sections."), _("\
24172 Show whether to use deprecated gdb_index sections."), _("\
24173 When enabled, deprecated .gdb_index sections are used anyway.\n\
24174 Normally they are ignored either because of a missing feature or\n\
24175 performance issue.\n\
24176 Warning: This option must be enabled before gdb reads the file."),
24177                            NULL,
24178                            NULL,
24179                            &setlist, &showlist);
24180
24181   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24182                _("\
24183 Save a gdb-index file.\n\
24184 Usage: save gdb-index DIRECTORY"),
24185                &save_cmdlist);
24186   set_cmd_completer (c, filename_completer);
24187
24188   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24189                                                         &dwarf2_locexpr_funcs);
24190   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24191                                                         &dwarf2_loclist_funcs);
24192
24193   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24194                                         &dwarf2_block_frame_base_locexpr_funcs);
24195   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24196                                         &dwarf2_block_frame_base_loclist_funcs);
24197 }