Record and output access specifiers for nested typedefs
[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_lt_14 : 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   const char *filename;
2690   struct dwz_file *result;
2691   bfd_size_type buildid_len_arg;
2692   size_t buildid_len;
2693   bfd_byte *buildid;
2694
2695   if (dwarf2_per_objfile->dwz_file != NULL)
2696     return dwarf2_per_objfile->dwz_file;
2697
2698   bfd_set_error (bfd_error_no_error);
2699   gdb::unique_xmalloc_ptr<char> data
2700     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2701                                   &buildid_len_arg, &buildid));
2702   if (data == NULL)
2703     {
2704       if (bfd_get_error () == bfd_error_no_error)
2705         return NULL;
2706       error (_("could not read '.gnu_debugaltlink' section: %s"),
2707              bfd_errmsg (bfd_get_error ()));
2708     }
2709
2710   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2711
2712   buildid_len = (size_t) buildid_len_arg;
2713
2714   filename = data.get ();
2715
2716   std::string abs_storage;
2717   if (!IS_ABSOLUTE_PATH (filename))
2718     {
2719       gdb::unique_xmalloc_ptr<char> abs
2720         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2721
2722       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2723       filename = abs_storage.c_str ();
2724     }
2725
2726   /* First try the file name given in the section.  If that doesn't
2727      work, try to use the build-id instead.  */
2728   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2729   if (dwz_bfd != NULL)
2730     {
2731       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2732         dwz_bfd.release ();
2733     }
2734
2735   if (dwz_bfd == NULL)
2736     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2737
2738   if (dwz_bfd == NULL)
2739     error (_("could not find '.gnu_debugaltlink' file for %s"),
2740            objfile_name (dwarf2_per_objfile->objfile));
2741
2742   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2743                            struct dwz_file);
2744   result->dwz_bfd = dwz_bfd.release ();
2745
2746   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2747
2748   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2749   dwarf2_per_objfile->dwz_file = result;
2750   return result;
2751 }
2752 \f
2753 /* DWARF quick_symbols_functions support.  */
2754
2755 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2756    unique line tables, so we maintain a separate table of all .debug_line
2757    derived entries to support the sharing.
2758    All the quick functions need is the list of file names.  We discard the
2759    line_header when we're done and don't need to record it here.  */
2760 struct quick_file_names
2761 {
2762   /* The data used to construct the hash key.  */
2763   struct stmt_list_hash hash;
2764
2765   /* The number of entries in file_names, real_names.  */
2766   unsigned int num_file_names;
2767
2768   /* The file names from the line table, after being run through
2769      file_full_name.  */
2770   const char **file_names;
2771
2772   /* The file names from the line table after being run through
2773      gdb_realpath.  These are computed lazily.  */
2774   const char **real_names;
2775 };
2776
2777 /* When using the index (and thus not using psymtabs), each CU has an
2778    object of this type.  This is used to hold information needed by
2779    the various "quick" methods.  */
2780 struct dwarf2_per_cu_quick_data
2781 {
2782   /* The file table.  This can be NULL if there was no file table
2783      or it's currently not read in.
2784      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2785   struct quick_file_names *file_names;
2786
2787   /* The corresponding symbol table.  This is NULL if symbols for this
2788      CU have not yet been read.  */
2789   struct compunit_symtab *compunit_symtab;
2790
2791   /* A temporary mark bit used when iterating over all CUs in
2792      expand_symtabs_matching.  */
2793   unsigned int mark : 1;
2794
2795   /* True if we've tried to read the file table and found there isn't one.
2796      There will be no point in trying to read it again next time.  */
2797   unsigned int no_file_data : 1;
2798 };
2799
2800 /* Utility hash function for a stmt_list_hash.  */
2801
2802 static hashval_t
2803 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2804 {
2805   hashval_t v = 0;
2806
2807   if (stmt_list_hash->dwo_unit != NULL)
2808     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2809   v += to_underlying (stmt_list_hash->line_sect_off);
2810   return v;
2811 }
2812
2813 /* Utility equality function for a stmt_list_hash.  */
2814
2815 static int
2816 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2817                     const struct stmt_list_hash *rhs)
2818 {
2819   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2820     return 0;
2821   if (lhs->dwo_unit != NULL
2822       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2823     return 0;
2824
2825   return lhs->line_sect_off == rhs->line_sect_off;
2826 }
2827
2828 /* Hash function for a quick_file_names.  */
2829
2830 static hashval_t
2831 hash_file_name_entry (const void *e)
2832 {
2833   const struct quick_file_names *file_data
2834     = (const struct quick_file_names *) e;
2835
2836   return hash_stmt_list_entry (&file_data->hash);
2837 }
2838
2839 /* Equality function for a quick_file_names.  */
2840
2841 static int
2842 eq_file_name_entry (const void *a, const void *b)
2843 {
2844   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2845   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2846
2847   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2848 }
2849
2850 /* Delete function for a quick_file_names.  */
2851
2852 static void
2853 delete_file_name_entry (void *e)
2854 {
2855   struct quick_file_names *file_data = (struct quick_file_names *) e;
2856   int i;
2857
2858   for (i = 0; i < file_data->num_file_names; ++i)
2859     {
2860       xfree ((void*) file_data->file_names[i]);
2861       if (file_data->real_names)
2862         xfree ((void*) file_data->real_names[i]);
2863     }
2864
2865   /* The space for the struct itself lives on objfile_obstack,
2866      so we don't free it here.  */
2867 }
2868
2869 /* Create a quick_file_names hash table.  */
2870
2871 static htab_t
2872 create_quick_file_names_table (unsigned int nr_initial_entries)
2873 {
2874   return htab_create_alloc (nr_initial_entries,
2875                             hash_file_name_entry, eq_file_name_entry,
2876                             delete_file_name_entry, xcalloc, xfree);
2877 }
2878
2879 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2880    have to be created afterwards.  You should call age_cached_comp_units after
2881    processing PER_CU->CU.  dw2_setup must have been already called.  */
2882
2883 static void
2884 load_cu (struct dwarf2_per_cu_data *per_cu)
2885 {
2886   if (per_cu->is_debug_types)
2887     load_full_type_unit (per_cu);
2888   else
2889     load_full_comp_unit (per_cu, language_minimal);
2890
2891   if (per_cu->cu == NULL)
2892     return;  /* Dummy CU.  */
2893
2894   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2895 }
2896
2897 /* Read in the symbols for PER_CU.  */
2898
2899 static void
2900 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2901 {
2902   struct cleanup *back_to;
2903
2904   /* Skip type_unit_groups, reading the type units they contain
2905      is handled elsewhere.  */
2906   if (IS_TYPE_UNIT_GROUP (per_cu))
2907     return;
2908
2909   back_to = make_cleanup (dwarf2_release_queue, NULL);
2910
2911   if (dwarf2_per_objfile->using_index
2912       ? per_cu->v.quick->compunit_symtab == NULL
2913       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2914     {
2915       queue_comp_unit (per_cu, language_minimal);
2916       load_cu (per_cu);
2917
2918       /* If we just loaded a CU from a DWO, and we're working with an index
2919          that may badly handle TUs, load all the TUs in that DWO as well.
2920          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2921       if (!per_cu->is_debug_types
2922           && per_cu->cu != NULL
2923           && per_cu->cu->dwo_unit != NULL
2924           && dwarf2_per_objfile->index_table != NULL
2925           && dwarf2_per_objfile->index_table->version <= 7
2926           /* DWP files aren't supported yet.  */
2927           && get_dwp_file () == NULL)
2928         queue_and_load_all_dwo_tus (per_cu);
2929     }
2930
2931   process_queue ();
2932
2933   /* Age the cache, releasing compilation units that have not
2934      been used recently.  */
2935   age_cached_comp_units ();
2936
2937   do_cleanups (back_to);
2938 }
2939
2940 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2941    the objfile from which this CU came.  Returns the resulting symbol
2942    table.  */
2943
2944 static struct compunit_symtab *
2945 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2946 {
2947   gdb_assert (dwarf2_per_objfile->using_index);
2948   if (!per_cu->v.quick->compunit_symtab)
2949     {
2950       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2951       scoped_restore decrementer = increment_reading_symtab ();
2952       dw2_do_instantiate_symtab (per_cu);
2953       process_cu_includes ();
2954       do_cleanups (back_to);
2955     }
2956
2957   return per_cu->v.quick->compunit_symtab;
2958 }
2959
2960 /* Return the CU/TU given its index.
2961
2962    This is intended for loops like:
2963
2964    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
2965                     + dwarf2_per_objfile->n_type_units); ++i)
2966      {
2967        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
2968
2969        ...;
2970      }
2971 */
2972
2973 static struct dwarf2_per_cu_data *
2974 dw2_get_cutu (int index)
2975 {
2976   if (index >= dwarf2_per_objfile->n_comp_units)
2977     {
2978       index -= dwarf2_per_objfile->n_comp_units;
2979       gdb_assert (index < dwarf2_per_objfile->n_type_units);
2980       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
2981     }
2982
2983   return dwarf2_per_objfile->all_comp_units[index];
2984 }
2985
2986 /* Return the CU given its index.
2987    This differs from dw2_get_cutu in that it's for when you know INDEX
2988    refers to a CU.  */
2989
2990 static struct dwarf2_per_cu_data *
2991 dw2_get_cu (int index)
2992 {
2993   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
2994
2995   return dwarf2_per_objfile->all_comp_units[index];
2996 }
2997
2998 /* A helper for create_cus_from_index that handles a given list of
2999    CUs.  */
3000
3001 static void
3002 create_cus_from_index_list (struct objfile *objfile,
3003                             const gdb_byte *cu_list, offset_type n_elements,
3004                             struct dwarf2_section_info *section,
3005                             int is_dwz,
3006                             int base_offset)
3007 {
3008   offset_type i;
3009
3010   for (i = 0; i < n_elements; i += 2)
3011     {
3012       gdb_static_assert (sizeof (ULONGEST) >= 8);
3013
3014       sect_offset sect_off
3015         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3016       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3017       cu_list += 2 * 8;
3018
3019       dwarf2_per_cu_data *the_cu
3020         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3021                           struct dwarf2_per_cu_data);
3022       the_cu->sect_off = sect_off;
3023       the_cu->length = length;
3024       the_cu->objfile = objfile;
3025       the_cu->section = section;
3026       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3027                                         struct dwarf2_per_cu_quick_data);
3028       the_cu->is_dwz = is_dwz;
3029       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3030     }
3031 }
3032
3033 /* Read the CU list from the mapped index, and use it to create all
3034    the CU objects for this objfile.  */
3035
3036 static void
3037 create_cus_from_index (struct objfile *objfile,
3038                        const gdb_byte *cu_list, offset_type cu_list_elements,
3039                        const gdb_byte *dwz_list, offset_type dwz_elements)
3040 {
3041   struct dwz_file *dwz;
3042
3043   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3044   dwarf2_per_objfile->all_comp_units =
3045     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3046                dwarf2_per_objfile->n_comp_units);
3047
3048   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3049                               &dwarf2_per_objfile->info, 0, 0);
3050
3051   if (dwz_elements == 0)
3052     return;
3053
3054   dwz = dwarf2_get_dwz_file ();
3055   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3056                               cu_list_elements / 2);
3057 }
3058
3059 /* Create the signatured type hash table from the index.  */
3060
3061 static void
3062 create_signatured_type_table_from_index (struct objfile *objfile,
3063                                          struct dwarf2_section_info *section,
3064                                          const gdb_byte *bytes,
3065                                          offset_type elements)
3066 {
3067   offset_type i;
3068   htab_t sig_types_hash;
3069
3070   dwarf2_per_objfile->n_type_units
3071     = dwarf2_per_objfile->n_allocated_type_units
3072     = elements / 3;
3073   dwarf2_per_objfile->all_type_units =
3074     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3075
3076   sig_types_hash = allocate_signatured_type_table (objfile);
3077
3078   for (i = 0; i < elements; i += 3)
3079     {
3080       struct signatured_type *sig_type;
3081       ULONGEST signature;
3082       void **slot;
3083       cu_offset type_offset_in_tu;
3084
3085       gdb_static_assert (sizeof (ULONGEST) >= 8);
3086       sect_offset sect_off
3087         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3088       type_offset_in_tu
3089         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3090                                                 BFD_ENDIAN_LITTLE);
3091       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3092       bytes += 3 * 8;
3093
3094       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3095                                  struct signatured_type);
3096       sig_type->signature = signature;
3097       sig_type->type_offset_in_tu = type_offset_in_tu;
3098       sig_type->per_cu.is_debug_types = 1;
3099       sig_type->per_cu.section = section;
3100       sig_type->per_cu.sect_off = sect_off;
3101       sig_type->per_cu.objfile = objfile;
3102       sig_type->per_cu.v.quick
3103         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3104                           struct dwarf2_per_cu_quick_data);
3105
3106       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3107       *slot = sig_type;
3108
3109       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3110     }
3111
3112   dwarf2_per_objfile->signatured_types = sig_types_hash;
3113 }
3114
3115 /* Read the address map data from the mapped index, and use it to
3116    populate the objfile's psymtabs_addrmap.  */
3117
3118 static void
3119 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3120 {
3121   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3122   const gdb_byte *iter, *end;
3123   struct addrmap *mutable_map;
3124   CORE_ADDR baseaddr;
3125
3126   auto_obstack temp_obstack;
3127
3128   mutable_map = addrmap_create_mutable (&temp_obstack);
3129
3130   iter = index->address_table;
3131   end = iter + index->address_table_size;
3132
3133   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3134
3135   while (iter < end)
3136     {
3137       ULONGEST hi, lo, cu_index;
3138       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3139       iter += 8;
3140       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3141       iter += 8;
3142       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3143       iter += 4;
3144
3145       if (lo > hi)
3146         {
3147           complaint (&symfile_complaints,
3148                      _(".gdb_index address table has invalid range (%s - %s)"),
3149                      hex_string (lo), hex_string (hi));
3150           continue;
3151         }
3152
3153       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3154         {
3155           complaint (&symfile_complaints,
3156                      _(".gdb_index address table has invalid CU number %u"),
3157                      (unsigned) cu_index);
3158           continue;
3159         }
3160
3161       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3162       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3163       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3164     }
3165
3166   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3167                                                     &objfile->objfile_obstack);
3168 }
3169
3170 /* The hash function for strings in the mapped index.  This is the same as
3171    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3172    implementation.  This is necessary because the hash function is tied to the
3173    format of the mapped index file.  The hash values do not have to match with
3174    SYMBOL_HASH_NEXT.
3175    
3176    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3177
3178 static hashval_t
3179 mapped_index_string_hash (int index_version, const void *p)
3180 {
3181   const unsigned char *str = (const unsigned char *) p;
3182   hashval_t r = 0;
3183   unsigned char c;
3184
3185   while ((c = *str++) != 0)
3186     {
3187       if (index_version >= 5)
3188         c = tolower (c);
3189       r = r * 67 + c - 113;
3190     }
3191
3192   return r;
3193 }
3194
3195 /* Find a slot in the mapped index INDEX for the object named NAME.
3196    If NAME is found, set *VEC_OUT to point to the CU vector in the
3197    constant pool and return true.  If NAME cannot be found, return
3198    false.  */
3199
3200 static bool
3201 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3202                           offset_type **vec_out)
3203 {
3204   offset_type hash;
3205   offset_type slot, step;
3206   int (*cmp) (const char *, const char *);
3207
3208   gdb::unique_xmalloc_ptr<char> without_params;
3209   if (current_language->la_language == language_cplus
3210       || current_language->la_language == language_fortran
3211       || current_language->la_language == language_d)
3212     {
3213       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3214          not contain any.  */
3215
3216       if (strchr (name, '(') != NULL)
3217         {
3218           without_params = cp_remove_params (name);
3219
3220           if (without_params != NULL)
3221             name = without_params.get ();
3222         }
3223     }
3224
3225   /* Index version 4 did not support case insensitive searches.  But the
3226      indices for case insensitive languages are built in lowercase, therefore
3227      simulate our NAME being searched is also lowercased.  */
3228   hash = mapped_index_string_hash ((index->version == 4
3229                                     && case_sensitivity == case_sensitive_off
3230                                     ? 5 : index->version),
3231                                    name);
3232
3233   slot = hash & (index->symbol_table_slots - 1);
3234   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3235   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3236
3237   for (;;)
3238     {
3239       /* Convert a slot number to an offset into the table.  */
3240       offset_type i = 2 * slot;
3241       const char *str;
3242       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3243         return false;
3244
3245       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3246       if (!cmp (name, str))
3247         {
3248           *vec_out = (offset_type *) (index->constant_pool
3249                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3250           return true;
3251         }
3252
3253       slot = (slot + step) & (index->symbol_table_slots - 1);
3254     }
3255 }
3256
3257 /* A helper function that reads the .gdb_index from SECTION and fills
3258    in MAP.  FILENAME is the name of the file containing the section;
3259    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3260    ok to use deprecated sections.
3261
3262    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3263    out parameters that are filled in with information about the CU and
3264    TU lists in the section.
3265
3266    Returns 1 if all went well, 0 otherwise.  */
3267
3268 static int
3269 read_index_from_section (struct objfile *objfile,
3270                          const char *filename,
3271                          int deprecated_ok,
3272                          struct dwarf2_section_info *section,
3273                          struct mapped_index *map,
3274                          const gdb_byte **cu_list,
3275                          offset_type *cu_list_elements,
3276                          const gdb_byte **types_list,
3277                          offset_type *types_list_elements)
3278 {
3279   const gdb_byte *addr;
3280   offset_type version;
3281   offset_type *metadata;
3282   int i;
3283
3284   if (dwarf2_section_empty_p (section))
3285     return 0;
3286
3287   /* Older elfutils strip versions could keep the section in the main
3288      executable while splitting it for the separate debug info file.  */
3289   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3290     return 0;
3291
3292   dwarf2_read_section (objfile, section);
3293
3294   addr = section->buffer;
3295   /* Version check.  */
3296   version = MAYBE_SWAP (*(offset_type *) addr);
3297   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3298      causes the index to behave very poorly for certain requests.  Version 3
3299      contained incomplete addrmap.  So, it seems better to just ignore such
3300      indices.  */
3301   if (version < 4)
3302     {
3303       static int warning_printed = 0;
3304       if (!warning_printed)
3305         {
3306           warning (_("Skipping obsolete .gdb_index section in %s."),
3307                    filename);
3308           warning_printed = 1;
3309         }
3310       return 0;
3311     }
3312   /* Index version 4 uses a different hash function than index version
3313      5 and later.
3314
3315      Versions earlier than 6 did not emit psymbols for inlined
3316      functions.  Using these files will cause GDB not to be able to
3317      set breakpoints on inlined functions by name, so we ignore these
3318      indices unless the user has done
3319      "set use-deprecated-index-sections on".  */
3320   if (version < 6 && !deprecated_ok)
3321     {
3322       static int warning_printed = 0;
3323       if (!warning_printed)
3324         {
3325           warning (_("\
3326 Skipping deprecated .gdb_index section in %s.\n\
3327 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3328 to use the section anyway."),
3329                    filename);
3330           warning_printed = 1;
3331         }
3332       return 0;
3333     }
3334   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3335      of the TU (for symbols coming from TUs),
3336      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3337      Plus gold-generated indices can have duplicate entries for global symbols,
3338      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3339      These are just performance bugs, and we can't distinguish gdb-generated
3340      indices from gold-generated ones, so issue no warning here.  */
3341
3342   /* Indexes with higher version than the one supported by GDB may be no
3343      longer backward compatible.  */
3344   if (version > 8)
3345     return 0;
3346
3347   map->version = version;
3348   map->total_size = section->size;
3349
3350   metadata = (offset_type *) (addr + sizeof (offset_type));
3351
3352   i = 0;
3353   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3354   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3355                        / 8);
3356   ++i;
3357
3358   *types_list = addr + MAYBE_SWAP (metadata[i]);
3359   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3360                            - MAYBE_SWAP (metadata[i]))
3361                           / 8);
3362   ++i;
3363
3364   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3365   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3366                              - MAYBE_SWAP (metadata[i]));
3367   ++i;
3368
3369   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3370   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3371                               - MAYBE_SWAP (metadata[i]))
3372                              / (2 * sizeof (offset_type)));
3373   ++i;
3374
3375   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3376
3377   return 1;
3378 }
3379
3380
3381 /* Read the index file.  If everything went ok, initialize the "quick"
3382    elements of all the CUs and return 1.  Otherwise, return 0.  */
3383
3384 static int
3385 dwarf2_read_index (struct objfile *objfile)
3386 {
3387   struct mapped_index local_map, *map;
3388   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3389   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3390   struct dwz_file *dwz;
3391
3392   if (!read_index_from_section (objfile, objfile_name (objfile),
3393                                 use_deprecated_index_sections,
3394                                 &dwarf2_per_objfile->gdb_index, &local_map,
3395                                 &cu_list, &cu_list_elements,
3396                                 &types_list, &types_list_elements))
3397     return 0;
3398
3399   /* Don't use the index if it's empty.  */
3400   if (local_map.symbol_table_slots == 0)
3401     return 0;
3402
3403   /* If there is a .dwz file, read it so we can get its CU list as
3404      well.  */
3405   dwz = dwarf2_get_dwz_file ();
3406   if (dwz != NULL)
3407     {
3408       struct mapped_index dwz_map;
3409       const gdb_byte *dwz_types_ignore;
3410       offset_type dwz_types_elements_ignore;
3411
3412       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3413                                     1,
3414                                     &dwz->gdb_index, &dwz_map,
3415                                     &dwz_list, &dwz_list_elements,
3416                                     &dwz_types_ignore,
3417                                     &dwz_types_elements_ignore))
3418         {
3419           warning (_("could not read '.gdb_index' section from %s; skipping"),
3420                    bfd_get_filename (dwz->dwz_bfd));
3421           return 0;
3422         }
3423     }
3424
3425   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3426                          dwz_list_elements);
3427
3428   if (types_list_elements)
3429     {
3430       struct dwarf2_section_info *section;
3431
3432       /* We can only handle a single .debug_types when we have an
3433          index.  */
3434       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3435         return 0;
3436
3437       section = VEC_index (dwarf2_section_info_def,
3438                            dwarf2_per_objfile->types, 0);
3439
3440       create_signatured_type_table_from_index (objfile, section, types_list,
3441                                                types_list_elements);
3442     }
3443
3444   create_addrmap_from_index (objfile, &local_map);
3445
3446   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3447   *map = local_map;
3448
3449   dwarf2_per_objfile->index_table = map;
3450   dwarf2_per_objfile->using_index = 1;
3451   dwarf2_per_objfile->quick_file_names_table =
3452     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3453
3454   return 1;
3455 }
3456
3457 /* A helper for the "quick" functions which sets the global
3458    dwarf2_per_objfile according to OBJFILE.  */
3459
3460 static void
3461 dw2_setup (struct objfile *objfile)
3462 {
3463   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3464                         objfile_data (objfile, dwarf2_objfile_data_key));
3465   gdb_assert (dwarf2_per_objfile);
3466 }
3467
3468 /* die_reader_func for dw2_get_file_names.  */
3469
3470 static void
3471 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3472                            const gdb_byte *info_ptr,
3473                            struct die_info *comp_unit_die,
3474                            int has_children,
3475                            void *data)
3476 {
3477   struct dwarf2_cu *cu = reader->cu;
3478   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3479   struct objfile *objfile = dwarf2_per_objfile->objfile;
3480   struct dwarf2_per_cu_data *lh_cu;
3481   struct attribute *attr;
3482   int i;
3483   void **slot;
3484   struct quick_file_names *qfn;
3485
3486   gdb_assert (! this_cu->is_debug_types);
3487
3488   /* Our callers never want to match partial units -- instead they
3489      will match the enclosing full CU.  */
3490   if (comp_unit_die->tag == DW_TAG_partial_unit)
3491     {
3492       this_cu->v.quick->no_file_data = 1;
3493       return;
3494     }
3495
3496   lh_cu = this_cu;
3497   slot = NULL;
3498
3499   line_header_up lh;
3500   sect_offset line_offset {};
3501
3502   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3503   if (attr)
3504     {
3505       struct quick_file_names find_entry;
3506
3507       line_offset = (sect_offset) DW_UNSND (attr);
3508
3509       /* We may have already read in this line header (TU line header sharing).
3510          If we have we're done.  */
3511       find_entry.hash.dwo_unit = cu->dwo_unit;
3512       find_entry.hash.line_sect_off = line_offset;
3513       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3514                              &find_entry, INSERT);
3515       if (*slot != NULL)
3516         {
3517           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3518           return;
3519         }
3520
3521       lh = dwarf_decode_line_header (line_offset, cu);
3522     }
3523   if (lh == NULL)
3524     {
3525       lh_cu->v.quick->no_file_data = 1;
3526       return;
3527     }
3528
3529   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3530   qfn->hash.dwo_unit = cu->dwo_unit;
3531   qfn->hash.line_sect_off = line_offset;
3532   gdb_assert (slot != NULL);
3533   *slot = qfn;
3534
3535   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3536
3537   qfn->num_file_names = lh->file_names.size ();
3538   qfn->file_names =
3539     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3540   for (i = 0; i < lh->file_names.size (); ++i)
3541     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3542   qfn->real_names = NULL;
3543
3544   lh_cu->v.quick->file_names = qfn;
3545 }
3546
3547 /* A helper for the "quick" functions which attempts to read the line
3548    table for THIS_CU.  */
3549
3550 static struct quick_file_names *
3551 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3552 {
3553   /* This should never be called for TUs.  */
3554   gdb_assert (! this_cu->is_debug_types);
3555   /* Nor type unit groups.  */
3556   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3557
3558   if (this_cu->v.quick->file_names != NULL)
3559     return this_cu->v.quick->file_names;
3560   /* If we know there is no line data, no point in looking again.  */
3561   if (this_cu->v.quick->no_file_data)
3562     return NULL;
3563
3564   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3565
3566   if (this_cu->v.quick->no_file_data)
3567     return NULL;
3568   return this_cu->v.quick->file_names;
3569 }
3570
3571 /* A helper for the "quick" functions which computes and caches the
3572    real path for a given file name from the line table.  */
3573
3574 static const char *
3575 dw2_get_real_path (struct objfile *objfile,
3576                    struct quick_file_names *qfn, int index)
3577 {
3578   if (qfn->real_names == NULL)
3579     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3580                                       qfn->num_file_names, const char *);
3581
3582   if (qfn->real_names[index] == NULL)
3583     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3584
3585   return qfn->real_names[index];
3586 }
3587
3588 static struct symtab *
3589 dw2_find_last_source_symtab (struct objfile *objfile)
3590 {
3591   struct compunit_symtab *cust;
3592   int index;
3593
3594   dw2_setup (objfile);
3595   index = dwarf2_per_objfile->n_comp_units - 1;
3596   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3597   if (cust == NULL)
3598     return NULL;
3599   return compunit_primary_filetab (cust);
3600 }
3601
3602 /* Traversal function for dw2_forget_cached_source_info.  */
3603
3604 static int
3605 dw2_free_cached_file_names (void **slot, void *info)
3606 {
3607   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3608
3609   if (file_data->real_names)
3610     {
3611       int i;
3612
3613       for (i = 0; i < file_data->num_file_names; ++i)
3614         {
3615           xfree ((void*) file_data->real_names[i]);
3616           file_data->real_names[i] = NULL;
3617         }
3618     }
3619
3620   return 1;
3621 }
3622
3623 static void
3624 dw2_forget_cached_source_info (struct objfile *objfile)
3625 {
3626   dw2_setup (objfile);
3627
3628   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3629                           dw2_free_cached_file_names, NULL);
3630 }
3631
3632 /* Helper function for dw2_map_symtabs_matching_filename that expands
3633    the symtabs and calls the iterator.  */
3634
3635 static int
3636 dw2_map_expand_apply (struct objfile *objfile,
3637                       struct dwarf2_per_cu_data *per_cu,
3638                       const char *name, const char *real_path,
3639                       gdb::function_view<bool (symtab *)> callback)
3640 {
3641   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3642
3643   /* Don't visit already-expanded CUs.  */
3644   if (per_cu->v.quick->compunit_symtab)
3645     return 0;
3646
3647   /* This may expand more than one symtab, and we want to iterate over
3648      all of them.  */
3649   dw2_instantiate_symtab (per_cu);
3650
3651   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3652                                     last_made, callback);
3653 }
3654
3655 /* Implementation of the map_symtabs_matching_filename method.  */
3656
3657 static bool
3658 dw2_map_symtabs_matching_filename
3659   (struct objfile *objfile, const char *name, const char *real_path,
3660    gdb::function_view<bool (symtab *)> callback)
3661 {
3662   int i;
3663   const char *name_basename = lbasename (name);
3664
3665   dw2_setup (objfile);
3666
3667   /* The rule is CUs specify all the files, including those used by
3668      any TU, so there's no need to scan TUs here.  */
3669
3670   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3671     {
3672       int j;
3673       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3674       struct quick_file_names *file_data;
3675
3676       /* We only need to look at symtabs not already expanded.  */
3677       if (per_cu->v.quick->compunit_symtab)
3678         continue;
3679
3680       file_data = dw2_get_file_names (per_cu);
3681       if (file_data == NULL)
3682         continue;
3683
3684       for (j = 0; j < file_data->num_file_names; ++j)
3685         {
3686           const char *this_name = file_data->file_names[j];
3687           const char *this_real_name;
3688
3689           if (compare_filenames_for_search (this_name, name))
3690             {
3691               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3692                                         callback))
3693                 return true;
3694               continue;
3695             }
3696
3697           /* Before we invoke realpath, which can get expensive when many
3698              files are involved, do a quick comparison of the basenames.  */
3699           if (! basenames_may_differ
3700               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3701             continue;
3702
3703           this_real_name = dw2_get_real_path (objfile, file_data, j);
3704           if (compare_filenames_for_search (this_real_name, name))
3705             {
3706               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3707                                         callback))
3708                 return true;
3709               continue;
3710             }
3711
3712           if (real_path != NULL)
3713             {
3714               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3715               gdb_assert (IS_ABSOLUTE_PATH (name));
3716               if (this_real_name != NULL
3717                   && FILENAME_CMP (real_path, this_real_name) == 0)
3718                 {
3719                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3720                                             callback))
3721                     return true;
3722                   continue;
3723                 }
3724             }
3725         }
3726     }
3727
3728   return false;
3729 }
3730
3731 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3732
3733 struct dw2_symtab_iterator
3734 {
3735   /* The internalized form of .gdb_index.  */
3736   struct mapped_index *index;
3737   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3738   int want_specific_block;
3739   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3740      Unused if !WANT_SPECIFIC_BLOCK.  */
3741   int block_index;
3742   /* The kind of symbol we're looking for.  */
3743   domain_enum domain;
3744   /* The list of CUs from the index entry of the symbol,
3745      or NULL if not found.  */
3746   offset_type *vec;
3747   /* The next element in VEC to look at.  */
3748   int next;
3749   /* The number of elements in VEC, or zero if there is no match.  */
3750   int length;
3751   /* Have we seen a global version of the symbol?
3752      If so we can ignore all further global instances.
3753      This is to work around gold/15646, inefficient gold-generated
3754      indices.  */
3755   int global_seen;
3756 };
3757
3758 /* Initialize the index symtab iterator ITER.
3759    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3760    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3761
3762 static void
3763 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3764                       struct mapped_index *index,
3765                       int want_specific_block,
3766                       int block_index,
3767                       domain_enum domain,
3768                       const char *name)
3769 {
3770   iter->index = index;
3771   iter->want_specific_block = want_specific_block;
3772   iter->block_index = block_index;
3773   iter->domain = domain;
3774   iter->next = 0;
3775   iter->global_seen = 0;
3776
3777   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3778     iter->length = MAYBE_SWAP (*iter->vec);
3779   else
3780     {
3781       iter->vec = NULL;
3782       iter->length = 0;
3783     }
3784 }
3785
3786 /* Return the next matching CU or NULL if there are no more.  */
3787
3788 static struct dwarf2_per_cu_data *
3789 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3790 {
3791   for ( ; iter->next < iter->length; ++iter->next)
3792     {
3793       offset_type cu_index_and_attrs =
3794         MAYBE_SWAP (iter->vec[iter->next + 1]);
3795       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3796       struct dwarf2_per_cu_data *per_cu;
3797       int want_static = iter->block_index != GLOBAL_BLOCK;
3798       /* This value is only valid for index versions >= 7.  */
3799       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3800       gdb_index_symbol_kind symbol_kind =
3801         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3802       /* Only check the symbol attributes if they're present.
3803          Indices prior to version 7 don't record them,
3804          and indices >= 7 may elide them for certain symbols
3805          (gold does this).  */
3806       int attrs_valid =
3807         (iter->index->version >= 7
3808          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3809
3810       /* Don't crash on bad data.  */
3811       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3812                        + dwarf2_per_objfile->n_type_units))
3813         {
3814           complaint (&symfile_complaints,
3815                      _(".gdb_index entry has bad CU index"
3816                        " [in module %s]"),
3817                      objfile_name (dwarf2_per_objfile->objfile));
3818           continue;
3819         }
3820
3821       per_cu = dw2_get_cutu (cu_index);
3822
3823       /* Skip if already read in.  */
3824       if (per_cu->v.quick->compunit_symtab)
3825         continue;
3826
3827       /* Check static vs global.  */
3828       if (attrs_valid)
3829         {
3830           if (iter->want_specific_block
3831               && want_static != is_static)
3832             continue;
3833           /* Work around gold/15646.  */
3834           if (!is_static && iter->global_seen)
3835             continue;
3836           if (!is_static)
3837             iter->global_seen = 1;
3838         }
3839
3840       /* Only check the symbol's kind if it has one.  */
3841       if (attrs_valid)
3842         {
3843           switch (iter->domain)
3844             {
3845             case VAR_DOMAIN:
3846               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3847                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3848                   /* Some types are also in VAR_DOMAIN.  */
3849                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3850                 continue;
3851               break;
3852             case STRUCT_DOMAIN:
3853               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3854                 continue;
3855               break;
3856             case LABEL_DOMAIN:
3857               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3858                 continue;
3859               break;
3860             default:
3861               break;
3862             }
3863         }
3864
3865       ++iter->next;
3866       return per_cu;
3867     }
3868
3869   return NULL;
3870 }
3871
3872 static struct compunit_symtab *
3873 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3874                    const char *name, domain_enum domain)
3875 {
3876   struct compunit_symtab *stab_best = NULL;
3877   struct mapped_index *index;
3878
3879   dw2_setup (objfile);
3880
3881   index = dwarf2_per_objfile->index_table;
3882
3883   /* index is NULL if OBJF_READNOW.  */
3884   if (index)
3885     {
3886       struct dw2_symtab_iterator iter;
3887       struct dwarf2_per_cu_data *per_cu;
3888
3889       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3890
3891       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3892         {
3893           struct symbol *sym, *with_opaque = NULL;
3894           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3895           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3896           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3897
3898           sym = block_find_symbol (block, name, domain,
3899                                    block_find_non_opaque_type_preferred,
3900                                    &with_opaque);
3901
3902           /* Some caution must be observed with overloaded functions
3903              and methods, since the index will not contain any overload
3904              information (but NAME might contain it).  */
3905
3906           if (sym != NULL
3907               && SYMBOL_MATCHES_SEARCH_NAME (sym, name))
3908             return stab;
3909           if (with_opaque != NULL
3910               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, name))
3911             stab_best = stab;
3912
3913           /* Keep looking through other CUs.  */
3914         }
3915     }
3916
3917   return stab_best;
3918 }
3919
3920 static void
3921 dw2_print_stats (struct objfile *objfile)
3922 {
3923   int i, total, count;
3924
3925   dw2_setup (objfile);
3926   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3927   count = 0;
3928   for (i = 0; i < total; ++i)
3929     {
3930       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3931
3932       if (!per_cu->v.quick->compunit_symtab)
3933         ++count;
3934     }
3935   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3936   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3937 }
3938
3939 /* This dumps minimal information about the index.
3940    It is called via "mt print objfiles".
3941    One use is to verify .gdb_index has been loaded by the
3942    gdb.dwarf2/gdb-index.exp testcase.  */
3943
3944 static void
3945 dw2_dump (struct objfile *objfile)
3946 {
3947   dw2_setup (objfile);
3948   gdb_assert (dwarf2_per_objfile->using_index);
3949   printf_filtered (".gdb_index:");
3950   if (dwarf2_per_objfile->index_table != NULL)
3951     {
3952       printf_filtered (" version %d\n",
3953                        dwarf2_per_objfile->index_table->version);
3954     }
3955   else
3956     printf_filtered (" faked for \"readnow\"\n");
3957   printf_filtered ("\n");
3958 }
3959
3960 static void
3961 dw2_relocate (struct objfile *objfile,
3962               const struct section_offsets *new_offsets,
3963               const struct section_offsets *delta)
3964 {
3965   /* There's nothing to relocate here.  */
3966 }
3967
3968 static void
3969 dw2_expand_symtabs_for_function (struct objfile *objfile,
3970                                  const char *func_name)
3971 {
3972   struct mapped_index *index;
3973
3974   dw2_setup (objfile);
3975
3976   index = dwarf2_per_objfile->index_table;
3977
3978   /* index is NULL if OBJF_READNOW.  */
3979   if (index)
3980     {
3981       struct dw2_symtab_iterator iter;
3982       struct dwarf2_per_cu_data *per_cu;
3983
3984       /* Note: It doesn't matter what we pass for block_index here.  */
3985       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
3986                             func_name);
3987
3988       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3989         dw2_instantiate_symtab (per_cu);
3990     }
3991 }
3992
3993 static void
3994 dw2_expand_all_symtabs (struct objfile *objfile)
3995 {
3996   int i;
3997
3998   dw2_setup (objfile);
3999
4000   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4001                    + dwarf2_per_objfile->n_type_units); ++i)
4002     {
4003       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4004
4005       dw2_instantiate_symtab (per_cu);
4006     }
4007 }
4008
4009 static void
4010 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4011                                   const char *fullname)
4012 {
4013   int i;
4014
4015   dw2_setup (objfile);
4016
4017   /* We don't need to consider type units here.
4018      This is only called for examining code, e.g. expand_line_sal.
4019      There can be an order of magnitude (or more) more type units
4020      than comp units, and we avoid them if we can.  */
4021
4022   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4023     {
4024       int j;
4025       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4026       struct quick_file_names *file_data;
4027
4028       /* We only need to look at symtabs not already expanded.  */
4029       if (per_cu->v.quick->compunit_symtab)
4030         continue;
4031
4032       file_data = dw2_get_file_names (per_cu);
4033       if (file_data == NULL)
4034         continue;
4035
4036       for (j = 0; j < file_data->num_file_names; ++j)
4037         {
4038           const char *this_fullname = file_data->file_names[j];
4039
4040           if (filename_cmp (this_fullname, fullname) == 0)
4041             {
4042               dw2_instantiate_symtab (per_cu);
4043               break;
4044             }
4045         }
4046     }
4047 }
4048
4049 static void
4050 dw2_map_matching_symbols (struct objfile *objfile,
4051                           const char * name, domain_enum domain,
4052                           int global,
4053                           int (*callback) (struct block *,
4054                                            struct symbol *, void *),
4055                           void *data, symbol_compare_ftype *match,
4056                           symbol_compare_ftype *ordered_compare)
4057 {
4058   /* Currently unimplemented; used for Ada.  The function can be called if the
4059      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4060      does not look for non-Ada symbols this function should just return.  */
4061 }
4062
4063 static void
4064 dw2_expand_symtabs_matching
4065   (struct objfile *objfile,
4066    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4067    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4068    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4069    enum search_domain kind)
4070 {
4071   int i;
4072   offset_type iter;
4073   struct mapped_index *index;
4074
4075   dw2_setup (objfile);
4076
4077   /* index_table is NULL if OBJF_READNOW.  */
4078   if (!dwarf2_per_objfile->index_table)
4079     return;
4080   index = dwarf2_per_objfile->index_table;
4081
4082   if (file_matcher != NULL)
4083     {
4084       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4085                                                 htab_eq_pointer,
4086                                                 NULL, xcalloc, xfree));
4087       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4088                                                     htab_eq_pointer,
4089                                                     NULL, xcalloc, xfree));
4090
4091       /* The rule is CUs specify all the files, including those used by
4092          any TU, so there's no need to scan TUs here.  */
4093
4094       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4095         {
4096           int j;
4097           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4098           struct quick_file_names *file_data;
4099           void **slot;
4100
4101           QUIT;
4102
4103           per_cu->v.quick->mark = 0;
4104
4105           /* We only need to look at symtabs not already expanded.  */
4106           if (per_cu->v.quick->compunit_symtab)
4107             continue;
4108
4109           file_data = dw2_get_file_names (per_cu);
4110           if (file_data == NULL)
4111             continue;
4112
4113           if (htab_find (visited_not_found.get (), file_data) != NULL)
4114             continue;
4115           else if (htab_find (visited_found.get (), file_data) != NULL)
4116             {
4117               per_cu->v.quick->mark = 1;
4118               continue;
4119             }
4120
4121           for (j = 0; j < file_data->num_file_names; ++j)
4122             {
4123               const char *this_real_name;
4124
4125               if (file_matcher (file_data->file_names[j], false))
4126                 {
4127                   per_cu->v.quick->mark = 1;
4128                   break;
4129                 }
4130
4131               /* Before we invoke realpath, which can get expensive when many
4132                  files are involved, do a quick comparison of the basenames.  */
4133               if (!basenames_may_differ
4134                   && !file_matcher (lbasename (file_data->file_names[j]),
4135                                     true))
4136                 continue;
4137
4138               this_real_name = dw2_get_real_path (objfile, file_data, j);
4139               if (file_matcher (this_real_name, false))
4140                 {
4141                   per_cu->v.quick->mark = 1;
4142                   break;
4143                 }
4144             }
4145
4146           slot = htab_find_slot (per_cu->v.quick->mark
4147                                  ? visited_found.get ()
4148                                  : visited_not_found.get (),
4149                                  file_data, INSERT);
4150           *slot = file_data;
4151         }
4152     }
4153
4154   for (iter = 0; iter < index->symbol_table_slots; ++iter)
4155     {
4156       offset_type idx = 2 * iter;
4157       const char *name;
4158       offset_type *vec, vec_len, vec_idx;
4159       int global_seen = 0;
4160
4161       QUIT;
4162
4163       if (index->symbol_table[idx] == 0 && index->symbol_table[idx + 1] == 0)
4164         continue;
4165
4166       name = index->constant_pool + MAYBE_SWAP (index->symbol_table[idx]);
4167
4168       if (!symbol_matcher (name))
4169         continue;
4170
4171       /* The name was matched, now expand corresponding CUs that were
4172          marked.  */
4173       vec = (offset_type *) (index->constant_pool
4174                              + MAYBE_SWAP (index->symbol_table[idx + 1]));
4175       vec_len = MAYBE_SWAP (vec[0]);
4176       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4177         {
4178           struct dwarf2_per_cu_data *per_cu;
4179           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4180           /* This value is only valid for index versions >= 7.  */
4181           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4182           gdb_index_symbol_kind symbol_kind =
4183             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4184           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4185           /* Only check the symbol attributes if they're present.
4186              Indices prior to version 7 don't record them,
4187              and indices >= 7 may elide them for certain symbols
4188              (gold does this).  */
4189           int attrs_valid =
4190             (index->version >= 7
4191              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4192
4193           /* Work around gold/15646.  */
4194           if (attrs_valid)
4195             {
4196               if (!is_static && global_seen)
4197                 continue;
4198               if (!is_static)
4199                 global_seen = 1;
4200             }
4201
4202           /* Only check the symbol's kind if it has one.  */
4203           if (attrs_valid)
4204             {
4205               switch (kind)
4206                 {
4207                 case VARIABLES_DOMAIN:
4208                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4209                     continue;
4210                   break;
4211                 case FUNCTIONS_DOMAIN:
4212                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4213                     continue;
4214                   break;
4215                 case TYPES_DOMAIN:
4216                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4217                     continue;
4218                   break;
4219                 default:
4220                   break;
4221                 }
4222             }
4223
4224           /* Don't crash on bad data.  */
4225           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4226                            + dwarf2_per_objfile->n_type_units))
4227             {
4228               complaint (&symfile_complaints,
4229                          _(".gdb_index entry has bad CU index"
4230                            " [in module %s]"), objfile_name (objfile));
4231               continue;
4232             }
4233
4234           per_cu = dw2_get_cutu (cu_index);
4235           if (file_matcher == NULL || per_cu->v.quick->mark)
4236             {
4237               int symtab_was_null =
4238                 (per_cu->v.quick->compunit_symtab == NULL);
4239
4240               dw2_instantiate_symtab (per_cu);
4241
4242               if (expansion_notify != NULL
4243                   && symtab_was_null
4244                   && per_cu->v.quick->compunit_symtab != NULL)
4245                 {
4246                   expansion_notify (per_cu->v.quick->compunit_symtab);
4247                 }
4248             }
4249         }
4250     }
4251 }
4252
4253 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4254    symtab.  */
4255
4256 static struct compunit_symtab *
4257 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4258                                           CORE_ADDR pc)
4259 {
4260   int i;
4261
4262   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4263       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4264     return cust;
4265
4266   if (cust->includes == NULL)
4267     return NULL;
4268
4269   for (i = 0; cust->includes[i]; ++i)
4270     {
4271       struct compunit_symtab *s = cust->includes[i];
4272
4273       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4274       if (s != NULL)
4275         return s;
4276     }
4277
4278   return NULL;
4279 }
4280
4281 static struct compunit_symtab *
4282 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4283                                   struct bound_minimal_symbol msymbol,
4284                                   CORE_ADDR pc,
4285                                   struct obj_section *section,
4286                                   int warn_if_readin)
4287 {
4288   struct dwarf2_per_cu_data *data;
4289   struct compunit_symtab *result;
4290
4291   dw2_setup (objfile);
4292
4293   if (!objfile->psymtabs_addrmap)
4294     return NULL;
4295
4296   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4297                                                      pc);
4298   if (!data)
4299     return NULL;
4300
4301   if (warn_if_readin && data->v.quick->compunit_symtab)
4302     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4303              paddress (get_objfile_arch (objfile), pc));
4304
4305   result
4306     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4307                                                 pc);
4308   gdb_assert (result != NULL);
4309   return result;
4310 }
4311
4312 static void
4313 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4314                           void *data, int need_fullname)
4315 {
4316   dw2_setup (objfile);
4317
4318   if (!dwarf2_per_objfile->filenames_cache)
4319     {
4320       dwarf2_per_objfile->filenames_cache.emplace ();
4321
4322       htab_up visited (htab_create_alloc (10,
4323                                           htab_hash_pointer, htab_eq_pointer,
4324                                           NULL, xcalloc, xfree));
4325
4326       /* The rule is CUs specify all the files, including those used
4327          by any TU, so there's no need to scan TUs here.  We can
4328          ignore file names coming from already-expanded CUs.  */
4329
4330       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4331         {
4332           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4333
4334           if (per_cu->v.quick->compunit_symtab)
4335             {
4336               void **slot = htab_find_slot (visited.get (),
4337                                             per_cu->v.quick->file_names,
4338                                             INSERT);
4339
4340               *slot = per_cu->v.quick->file_names;
4341             }
4342         }
4343
4344       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4345         {
4346           int j;
4347           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4348           struct quick_file_names *file_data;
4349           void **slot;
4350
4351           /* We only need to look at symtabs not already expanded.  */
4352           if (per_cu->v.quick->compunit_symtab)
4353             continue;
4354
4355           file_data = dw2_get_file_names (per_cu);
4356           if (file_data == NULL)
4357             continue;
4358
4359           slot = htab_find_slot (visited.get (), file_data, INSERT);
4360           if (*slot)
4361             {
4362               /* Already visited.  */
4363               continue;
4364             }
4365           *slot = file_data;
4366
4367           for (int j = 0; j < file_data->num_file_names; ++j)
4368             {
4369               const char *filename = file_data->file_names[j];
4370               dwarf2_per_objfile->filenames_cache->seen (filename);
4371             }
4372         }
4373     }
4374
4375   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4376     {
4377       gdb::unique_xmalloc_ptr<char> this_real_name;
4378
4379       if (need_fullname)
4380         this_real_name = gdb_realpath (filename);
4381       (*fun) (filename, this_real_name.get (), data);
4382     });
4383 }
4384
4385 static int
4386 dw2_has_symbols (struct objfile *objfile)
4387 {
4388   return 1;
4389 }
4390
4391 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4392 {
4393   dw2_has_symbols,
4394   dw2_find_last_source_symtab,
4395   dw2_forget_cached_source_info,
4396   dw2_map_symtabs_matching_filename,
4397   dw2_lookup_symbol,
4398   dw2_print_stats,
4399   dw2_dump,
4400   dw2_relocate,
4401   dw2_expand_symtabs_for_function,
4402   dw2_expand_all_symtabs,
4403   dw2_expand_symtabs_with_fullname,
4404   dw2_map_matching_symbols,
4405   dw2_expand_symtabs_matching,
4406   dw2_find_pc_sect_compunit_symtab,
4407   dw2_map_symbol_filenames
4408 };
4409
4410 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4411    file will use psymtabs, or 1 if using the GNU index.  */
4412
4413 int
4414 dwarf2_initialize_objfile (struct objfile *objfile)
4415 {
4416   /* If we're about to read full symbols, don't bother with the
4417      indices.  In this case we also don't care if some other debug
4418      format is making psymtabs, because they are all about to be
4419      expanded anyway.  */
4420   if ((objfile->flags & OBJF_READNOW))
4421     {
4422       int i;
4423
4424       dwarf2_per_objfile->using_index = 1;
4425       create_all_comp_units (objfile);
4426       create_all_type_units (objfile);
4427       dwarf2_per_objfile->quick_file_names_table =
4428         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4429
4430       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4431                        + dwarf2_per_objfile->n_type_units); ++i)
4432         {
4433           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4434
4435           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4436                                             struct dwarf2_per_cu_quick_data);
4437         }
4438
4439       /* Return 1 so that gdb sees the "quick" functions.  However,
4440          these functions will be no-ops because we will have expanded
4441          all symtabs.  */
4442       return 1;
4443     }
4444
4445   if (dwarf2_read_index (objfile))
4446     return 1;
4447
4448   return 0;
4449 }
4450
4451 \f
4452
4453 /* Build a partial symbol table.  */
4454
4455 void
4456 dwarf2_build_psymtabs (struct objfile *objfile)
4457 {
4458
4459   if (objfile->global_psymbols.capacity () == 0
4460       && objfile->static_psymbols.capacity () == 0)
4461     init_psymbol_list (objfile, 1024);
4462
4463   TRY
4464     {
4465       /* This isn't really ideal: all the data we allocate on the
4466          objfile's obstack is still uselessly kept around.  However,
4467          freeing it seems unsafe.  */
4468       psymtab_discarder psymtabs (objfile);
4469       dwarf2_build_psymtabs_hard (objfile);
4470       psymtabs.keep ();
4471     }
4472   CATCH (except, RETURN_MASK_ERROR)
4473     {
4474       exception_print (gdb_stderr, except);
4475     }
4476   END_CATCH
4477 }
4478
4479 /* Return the total length of the CU described by HEADER.  */
4480
4481 static unsigned int
4482 get_cu_length (const struct comp_unit_head *header)
4483 {
4484   return header->initial_length_size + header->length;
4485 }
4486
4487 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4488
4489 static inline bool
4490 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4491 {
4492   sect_offset bottom = cu_header->sect_off;
4493   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4494
4495   return sect_off >= bottom && sect_off < top;
4496 }
4497
4498 /* Find the base address of the compilation unit for range lists and
4499    location lists.  It will normally be specified by DW_AT_low_pc.
4500    In DWARF-3 draft 4, the base address could be overridden by
4501    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4502    compilation units with discontinuous ranges.  */
4503
4504 static void
4505 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4506 {
4507   struct attribute *attr;
4508
4509   cu->base_known = 0;
4510   cu->base_address = 0;
4511
4512   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4513   if (attr)
4514     {
4515       cu->base_address = attr_value_as_address (attr);
4516       cu->base_known = 1;
4517     }
4518   else
4519     {
4520       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4521       if (attr)
4522         {
4523           cu->base_address = attr_value_as_address (attr);
4524           cu->base_known = 1;
4525         }
4526     }
4527 }
4528
4529 /* Read in the comp unit header information from the debug_info at info_ptr.
4530    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4531    NOTE: This leaves members offset, first_die_offset to be filled in
4532    by the caller.  */
4533
4534 static const gdb_byte *
4535 read_comp_unit_head (struct comp_unit_head *cu_header,
4536                      const gdb_byte *info_ptr,
4537                      struct dwarf2_section_info *section,
4538                      rcuh_kind section_kind)
4539 {
4540   int signed_addr;
4541   unsigned int bytes_read;
4542   const char *filename = get_section_file_name (section);
4543   bfd *abfd = get_section_bfd_owner (section);
4544
4545   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4546   cu_header->initial_length_size = bytes_read;
4547   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4548   info_ptr += bytes_read;
4549   cu_header->version = read_2_bytes (abfd, info_ptr);
4550   info_ptr += 2;
4551   if (cu_header->version < 5)
4552     switch (section_kind)
4553       {
4554       case rcuh_kind::COMPILE:
4555         cu_header->unit_type = DW_UT_compile;
4556         break;
4557       case rcuh_kind::TYPE:
4558         cu_header->unit_type = DW_UT_type;
4559         break;
4560       default:
4561         internal_error (__FILE__, __LINE__,
4562                         _("read_comp_unit_head: invalid section_kind"));
4563       }
4564   else
4565     {
4566       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4567                                                  (read_1_byte (abfd, info_ptr));
4568       info_ptr += 1;
4569       switch (cu_header->unit_type)
4570         {
4571         case DW_UT_compile:
4572           if (section_kind != rcuh_kind::COMPILE)
4573             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4574                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4575                    filename);
4576           break;
4577         case DW_UT_type:
4578           section_kind = rcuh_kind::TYPE;
4579           break;
4580         default:
4581           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4582                  "(is %d, should be %d or %d) [in module %s]"),
4583                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4584         }
4585
4586       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4587       info_ptr += 1;
4588     }
4589   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4590                                                           cu_header,
4591                                                           &bytes_read);
4592   info_ptr += bytes_read;
4593   if (cu_header->version < 5)
4594     {
4595       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4596       info_ptr += 1;
4597     }
4598   signed_addr = bfd_get_sign_extend_vma (abfd);
4599   if (signed_addr < 0)
4600     internal_error (__FILE__, __LINE__,
4601                     _("read_comp_unit_head: dwarf from non elf file"));
4602   cu_header->signed_addr_p = signed_addr;
4603
4604   if (section_kind == rcuh_kind::TYPE)
4605     {
4606       LONGEST type_offset;
4607
4608       cu_header->signature = read_8_bytes (abfd, info_ptr);
4609       info_ptr += 8;
4610
4611       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4612       info_ptr += bytes_read;
4613       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4614       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4615         error (_("Dwarf Error: Too big type_offset in compilation unit "
4616                "header (is %s) [in module %s]"), plongest (type_offset),
4617                filename);
4618     }
4619
4620   return info_ptr;
4621 }
4622
4623 /* Helper function that returns the proper abbrev section for
4624    THIS_CU.  */
4625
4626 static struct dwarf2_section_info *
4627 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4628 {
4629   struct dwarf2_section_info *abbrev;
4630
4631   if (this_cu->is_dwz)
4632     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4633   else
4634     abbrev = &dwarf2_per_objfile->abbrev;
4635
4636   return abbrev;
4637 }
4638
4639 /* Subroutine of read_and_check_comp_unit_head and
4640    read_and_check_type_unit_head to simplify them.
4641    Perform various error checking on the header.  */
4642
4643 static void
4644 error_check_comp_unit_head (struct comp_unit_head *header,
4645                             struct dwarf2_section_info *section,
4646                             struct dwarf2_section_info *abbrev_section)
4647 {
4648   const char *filename = get_section_file_name (section);
4649
4650   if (header->version < 2 || header->version > 5)
4651     error (_("Dwarf Error: wrong version in compilation unit header "
4652            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4653            filename);
4654
4655   if (to_underlying (header->abbrev_sect_off)
4656       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4657     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4658            "(offset 0x%x + 6) [in module %s]"),
4659            to_underlying (header->abbrev_sect_off),
4660            to_underlying (header->sect_off),
4661            filename);
4662
4663   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4664      avoid potential 32-bit overflow.  */
4665   if (((ULONGEST) header->sect_off + get_cu_length (header))
4666       > section->size)
4667     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4668            "(offset 0x%x + 0) [in module %s]"),
4669            header->length, to_underlying (header->sect_off),
4670            filename);
4671 }
4672
4673 /* Read in a CU/TU header and perform some basic error checking.
4674    The contents of the header are stored in HEADER.
4675    The result is a pointer to the start of the first DIE.  */
4676
4677 static const gdb_byte *
4678 read_and_check_comp_unit_head (struct comp_unit_head *header,
4679                                struct dwarf2_section_info *section,
4680                                struct dwarf2_section_info *abbrev_section,
4681                                const gdb_byte *info_ptr,
4682                                rcuh_kind section_kind)
4683 {
4684   const gdb_byte *beg_of_comp_unit = info_ptr;
4685   bfd *abfd = get_section_bfd_owner (section);
4686
4687   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4688
4689   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4690
4691   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4692
4693   error_check_comp_unit_head (header, section, abbrev_section);
4694
4695   return info_ptr;
4696 }
4697
4698 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4699
4700 static sect_offset
4701 read_abbrev_offset (struct dwarf2_section_info *section,
4702                     sect_offset sect_off)
4703 {
4704   bfd *abfd = get_section_bfd_owner (section);
4705   const gdb_byte *info_ptr;
4706   unsigned int initial_length_size, offset_size;
4707   uint16_t version;
4708
4709   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4710   info_ptr = section->buffer + to_underlying (sect_off);
4711   read_initial_length (abfd, info_ptr, &initial_length_size);
4712   offset_size = initial_length_size == 4 ? 4 : 8;
4713   info_ptr += initial_length_size;
4714
4715   version = read_2_bytes (abfd, info_ptr);
4716   info_ptr += 2;
4717   if (version >= 5)
4718     {
4719       /* Skip unit type and address size.  */
4720       info_ptr += 2;
4721     }
4722
4723   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4724 }
4725
4726 /* Allocate a new partial symtab for file named NAME and mark this new
4727    partial symtab as being an include of PST.  */
4728
4729 static void
4730 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4731                                struct objfile *objfile)
4732 {
4733   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4734
4735   if (!IS_ABSOLUTE_PATH (subpst->filename))
4736     {
4737       /* It shares objfile->objfile_obstack.  */
4738       subpst->dirname = pst->dirname;
4739     }
4740
4741   subpst->textlow = 0;
4742   subpst->texthigh = 0;
4743
4744   subpst->dependencies
4745     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4746   subpst->dependencies[0] = pst;
4747   subpst->number_of_dependencies = 1;
4748
4749   subpst->globals_offset = 0;
4750   subpst->n_global_syms = 0;
4751   subpst->statics_offset = 0;
4752   subpst->n_static_syms = 0;
4753   subpst->compunit_symtab = NULL;
4754   subpst->read_symtab = pst->read_symtab;
4755   subpst->readin = 0;
4756
4757   /* No private part is necessary for include psymtabs.  This property
4758      can be used to differentiate between such include psymtabs and
4759      the regular ones.  */
4760   subpst->read_symtab_private = NULL;
4761 }
4762
4763 /* Read the Line Number Program data and extract the list of files
4764    included by the source file represented by PST.  Build an include
4765    partial symtab for each of these included files.  */
4766
4767 static void
4768 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4769                                struct die_info *die,
4770                                struct partial_symtab *pst)
4771 {
4772   line_header_up lh;
4773   struct attribute *attr;
4774
4775   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4776   if (attr)
4777     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4778   if (lh == NULL)
4779     return;  /* No linetable, so no includes.  */
4780
4781   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4782   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4783 }
4784
4785 static hashval_t
4786 hash_signatured_type (const void *item)
4787 {
4788   const struct signatured_type *sig_type
4789     = (const struct signatured_type *) item;
4790
4791   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4792   return sig_type->signature;
4793 }
4794
4795 static int
4796 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4797 {
4798   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4799   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4800
4801   return lhs->signature == rhs->signature;
4802 }
4803
4804 /* Allocate a hash table for signatured types.  */
4805
4806 static htab_t
4807 allocate_signatured_type_table (struct objfile *objfile)
4808 {
4809   return htab_create_alloc_ex (41,
4810                                hash_signatured_type,
4811                                eq_signatured_type,
4812                                NULL,
4813                                &objfile->objfile_obstack,
4814                                hashtab_obstack_allocate,
4815                                dummy_obstack_deallocate);
4816 }
4817
4818 /* A helper function to add a signatured type CU to a table.  */
4819
4820 static int
4821 add_signatured_type_cu_to_table (void **slot, void *datum)
4822 {
4823   struct signatured_type *sigt = (struct signatured_type *) *slot;
4824   struct signatured_type ***datap = (struct signatured_type ***) datum;
4825
4826   **datap = sigt;
4827   ++*datap;
4828
4829   return 1;
4830 }
4831
4832 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4833    and fill them into TYPES_HTAB.  It will process only type units,
4834    therefore DW_UT_type.  */
4835
4836 static void
4837 create_debug_type_hash_table (struct dwo_file *dwo_file,
4838                               dwarf2_section_info *section, htab_t &types_htab,
4839                               rcuh_kind section_kind)
4840 {
4841   struct objfile *objfile = dwarf2_per_objfile->objfile;
4842   struct dwarf2_section_info *abbrev_section;
4843   bfd *abfd;
4844   const gdb_byte *info_ptr, *end_ptr;
4845
4846   abbrev_section = (dwo_file != NULL
4847                     ? &dwo_file->sections.abbrev
4848                     : &dwarf2_per_objfile->abbrev);
4849
4850   if (dwarf_read_debug)
4851     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4852                         get_section_name (section),
4853                         get_section_file_name (abbrev_section));
4854
4855   dwarf2_read_section (objfile, section);
4856   info_ptr = section->buffer;
4857
4858   if (info_ptr == NULL)
4859     return;
4860
4861   /* We can't set abfd until now because the section may be empty or
4862      not present, in which case the bfd is unknown.  */
4863   abfd = get_section_bfd_owner (section);
4864
4865   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4866      because we don't need to read any dies: the signature is in the
4867      header.  */
4868
4869   end_ptr = info_ptr + section->size;
4870   while (info_ptr < end_ptr)
4871     {
4872       struct signatured_type *sig_type;
4873       struct dwo_unit *dwo_tu;
4874       void **slot;
4875       const gdb_byte *ptr = info_ptr;
4876       struct comp_unit_head header;
4877       unsigned int length;
4878
4879       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4880
4881       /* Initialize it due to a false compiler warning.  */
4882       header.signature = -1;
4883       header.type_cu_offset_in_tu = (cu_offset) -1;
4884
4885       /* We need to read the type's signature in order to build the hash
4886          table, but we don't need anything else just yet.  */
4887
4888       ptr = read_and_check_comp_unit_head (&header, section,
4889                                            abbrev_section, ptr, section_kind);
4890
4891       length = get_cu_length (&header);
4892
4893       /* Skip dummy type units.  */
4894       if (ptr >= info_ptr + length
4895           || peek_abbrev_code (abfd, ptr) == 0
4896           || header.unit_type != DW_UT_type)
4897         {
4898           info_ptr += length;
4899           continue;
4900         }
4901
4902       if (types_htab == NULL)
4903         {
4904           if (dwo_file)
4905             types_htab = allocate_dwo_unit_table (objfile);
4906           else
4907             types_htab = allocate_signatured_type_table (objfile);
4908         }
4909
4910       if (dwo_file)
4911         {
4912           sig_type = NULL;
4913           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4914                                    struct dwo_unit);
4915           dwo_tu->dwo_file = dwo_file;
4916           dwo_tu->signature = header.signature;
4917           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4918           dwo_tu->section = section;
4919           dwo_tu->sect_off = sect_off;
4920           dwo_tu->length = length;
4921         }
4922       else
4923         {
4924           /* N.B.: type_offset is not usable if this type uses a DWO file.
4925              The real type_offset is in the DWO file.  */
4926           dwo_tu = NULL;
4927           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4928                                      struct signatured_type);
4929           sig_type->signature = header.signature;
4930           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4931           sig_type->per_cu.objfile = objfile;
4932           sig_type->per_cu.is_debug_types = 1;
4933           sig_type->per_cu.section = section;
4934           sig_type->per_cu.sect_off = sect_off;
4935           sig_type->per_cu.length = length;
4936         }
4937
4938       slot = htab_find_slot (types_htab,
4939                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4940                              INSERT);
4941       gdb_assert (slot != NULL);
4942       if (*slot != NULL)
4943         {
4944           sect_offset dup_sect_off;
4945
4946           if (dwo_file)
4947             {
4948               const struct dwo_unit *dup_tu
4949                 = (const struct dwo_unit *) *slot;
4950
4951               dup_sect_off = dup_tu->sect_off;
4952             }
4953           else
4954             {
4955               const struct signatured_type *dup_tu
4956                 = (const struct signatured_type *) *slot;
4957
4958               dup_sect_off = dup_tu->per_cu.sect_off;
4959             }
4960
4961           complaint (&symfile_complaints,
4962                      _("debug type entry at offset 0x%x is duplicate to"
4963                        " the entry at offset 0x%x, signature %s"),
4964                      to_underlying (sect_off), to_underlying (dup_sect_off),
4965                      hex_string (header.signature));
4966         }
4967       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4968
4969       if (dwarf_read_debug > 1)
4970         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4971                             to_underlying (sect_off),
4972                             hex_string (header.signature));
4973
4974       info_ptr += length;
4975     }
4976 }
4977
4978 /* Create the hash table of all entries in the .debug_types
4979    (or .debug_types.dwo) section(s).
4980    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4981    otherwise it is NULL.
4982
4983    The result is a pointer to the hash table or NULL if there are no types.
4984
4985    Note: This function processes DWO files only, not DWP files.  */
4986
4987 static void
4988 create_debug_types_hash_table (struct dwo_file *dwo_file,
4989                                VEC (dwarf2_section_info_def) *types,
4990                                htab_t &types_htab)
4991 {
4992   int ix;
4993   struct dwarf2_section_info *section;
4994
4995   if (VEC_empty (dwarf2_section_info_def, types))
4996     return;
4997
4998   for (ix = 0;
4999        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5000        ++ix)
5001     create_debug_type_hash_table (dwo_file, section, types_htab,
5002                                   rcuh_kind::TYPE);
5003 }
5004
5005 /* Create the hash table of all entries in the .debug_types section,
5006    and initialize all_type_units.
5007    The result is zero if there is an error (e.g. missing .debug_types section),
5008    otherwise non-zero.  */
5009
5010 static int
5011 create_all_type_units (struct objfile *objfile)
5012 {
5013   htab_t types_htab = NULL;
5014   struct signatured_type **iter;
5015
5016   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5017                                 rcuh_kind::COMPILE);
5018   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5019   if (types_htab == NULL)
5020     {
5021       dwarf2_per_objfile->signatured_types = NULL;
5022       return 0;
5023     }
5024
5025   dwarf2_per_objfile->signatured_types = types_htab;
5026
5027   dwarf2_per_objfile->n_type_units
5028     = dwarf2_per_objfile->n_allocated_type_units
5029     = htab_elements (types_htab);
5030   dwarf2_per_objfile->all_type_units =
5031     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5032   iter = &dwarf2_per_objfile->all_type_units[0];
5033   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5034   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5035               == dwarf2_per_objfile->n_type_units);
5036
5037   return 1;
5038 }
5039
5040 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5041    If SLOT is non-NULL, it is the entry to use in the hash table.
5042    Otherwise we find one.  */
5043
5044 static struct signatured_type *
5045 add_type_unit (ULONGEST sig, void **slot)
5046 {
5047   struct objfile *objfile = dwarf2_per_objfile->objfile;
5048   int n_type_units = dwarf2_per_objfile->n_type_units;
5049   struct signatured_type *sig_type;
5050
5051   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5052   ++n_type_units;
5053   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5054     {
5055       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5056         dwarf2_per_objfile->n_allocated_type_units = 1;
5057       dwarf2_per_objfile->n_allocated_type_units *= 2;
5058       dwarf2_per_objfile->all_type_units
5059         = XRESIZEVEC (struct signatured_type *,
5060                       dwarf2_per_objfile->all_type_units,
5061                       dwarf2_per_objfile->n_allocated_type_units);
5062       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5063     }
5064   dwarf2_per_objfile->n_type_units = n_type_units;
5065
5066   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5067                              struct signatured_type);
5068   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5069   sig_type->signature = sig;
5070   sig_type->per_cu.is_debug_types = 1;
5071   if (dwarf2_per_objfile->using_index)
5072     {
5073       sig_type->per_cu.v.quick =
5074         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5075                         struct dwarf2_per_cu_quick_data);
5076     }
5077
5078   if (slot == NULL)
5079     {
5080       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5081                              sig_type, INSERT);
5082     }
5083   gdb_assert (*slot == NULL);
5084   *slot = sig_type;
5085   /* The rest of sig_type must be filled in by the caller.  */
5086   return sig_type;
5087 }
5088
5089 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5090    Fill in SIG_ENTRY with DWO_ENTRY.  */
5091
5092 static void
5093 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5094                                   struct signatured_type *sig_entry,
5095                                   struct dwo_unit *dwo_entry)
5096 {
5097   /* Make sure we're not clobbering something we don't expect to.  */
5098   gdb_assert (! sig_entry->per_cu.queued);
5099   gdb_assert (sig_entry->per_cu.cu == NULL);
5100   if (dwarf2_per_objfile->using_index)
5101     {
5102       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5103       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5104     }
5105   else
5106       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5107   gdb_assert (sig_entry->signature == dwo_entry->signature);
5108   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5109   gdb_assert (sig_entry->type_unit_group == NULL);
5110   gdb_assert (sig_entry->dwo_unit == NULL);
5111
5112   sig_entry->per_cu.section = dwo_entry->section;
5113   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5114   sig_entry->per_cu.length = dwo_entry->length;
5115   sig_entry->per_cu.reading_dwo_directly = 1;
5116   sig_entry->per_cu.objfile = objfile;
5117   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5118   sig_entry->dwo_unit = dwo_entry;
5119 }
5120
5121 /* Subroutine of lookup_signatured_type.
5122    If we haven't read the TU yet, create the signatured_type data structure
5123    for a TU to be read in directly from a DWO file, bypassing the stub.
5124    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5125    using .gdb_index, then when reading a CU we want to stay in the DWO file
5126    containing that CU.  Otherwise we could end up reading several other DWO
5127    files (due to comdat folding) to process the transitive closure of all the
5128    mentioned TUs, and that can be slow.  The current DWO file will have every
5129    type signature that it needs.
5130    We only do this for .gdb_index because in the psymtab case we already have
5131    to read all the DWOs to build the type unit groups.  */
5132
5133 static struct signatured_type *
5134 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5135 {
5136   struct objfile *objfile = dwarf2_per_objfile->objfile;
5137   struct dwo_file *dwo_file;
5138   struct dwo_unit find_dwo_entry, *dwo_entry;
5139   struct signatured_type find_sig_entry, *sig_entry;
5140   void **slot;
5141
5142   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5143
5144   /* If TU skeletons have been removed then we may not have read in any
5145      TUs yet.  */
5146   if (dwarf2_per_objfile->signatured_types == NULL)
5147     {
5148       dwarf2_per_objfile->signatured_types
5149         = allocate_signatured_type_table (objfile);
5150     }
5151
5152   /* We only ever need to read in one copy of a signatured type.
5153      Use the global signatured_types array to do our own comdat-folding
5154      of types.  If this is the first time we're reading this TU, and
5155      the TU has an entry in .gdb_index, replace the recorded data from
5156      .gdb_index with this TU.  */
5157
5158   find_sig_entry.signature = sig;
5159   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5160                          &find_sig_entry, INSERT);
5161   sig_entry = (struct signatured_type *) *slot;
5162
5163   /* We can get here with the TU already read, *or* in the process of being
5164      read.  Don't reassign the global entry to point to this DWO if that's
5165      the case.  Also note that if the TU is already being read, it may not
5166      have come from a DWO, the program may be a mix of Fission-compiled
5167      code and non-Fission-compiled code.  */
5168
5169   /* Have we already tried to read this TU?
5170      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5171      needn't exist in the global table yet).  */
5172   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5173     return sig_entry;
5174
5175   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5176      dwo_unit of the TU itself.  */
5177   dwo_file = cu->dwo_unit->dwo_file;
5178
5179   /* Ok, this is the first time we're reading this TU.  */
5180   if (dwo_file->tus == NULL)
5181     return NULL;
5182   find_dwo_entry.signature = sig;
5183   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5184   if (dwo_entry == NULL)
5185     return NULL;
5186
5187   /* If the global table doesn't have an entry for this TU, add one.  */
5188   if (sig_entry == NULL)
5189     sig_entry = add_type_unit (sig, slot);
5190
5191   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5192   sig_entry->per_cu.tu_read = 1;
5193   return sig_entry;
5194 }
5195
5196 /* Subroutine of lookup_signatured_type.
5197    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5198    then try the DWP file.  If the TU stub (skeleton) has been removed then
5199    it won't be in .gdb_index.  */
5200
5201 static struct signatured_type *
5202 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5203 {
5204   struct objfile *objfile = dwarf2_per_objfile->objfile;
5205   struct dwp_file *dwp_file = get_dwp_file ();
5206   struct dwo_unit *dwo_entry;
5207   struct signatured_type find_sig_entry, *sig_entry;
5208   void **slot;
5209
5210   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5211   gdb_assert (dwp_file != NULL);
5212
5213   /* If TU skeletons have been removed then we may not have read in any
5214      TUs yet.  */
5215   if (dwarf2_per_objfile->signatured_types == NULL)
5216     {
5217       dwarf2_per_objfile->signatured_types
5218         = allocate_signatured_type_table (objfile);
5219     }
5220
5221   find_sig_entry.signature = sig;
5222   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5223                          &find_sig_entry, INSERT);
5224   sig_entry = (struct signatured_type *) *slot;
5225
5226   /* Have we already tried to read this TU?
5227      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5228      needn't exist in the global table yet).  */
5229   if (sig_entry != NULL)
5230     return sig_entry;
5231
5232   if (dwp_file->tus == NULL)
5233     return NULL;
5234   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5235                                       sig, 1 /* is_debug_types */);
5236   if (dwo_entry == NULL)
5237     return NULL;
5238
5239   sig_entry = add_type_unit (sig, slot);
5240   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5241
5242   return sig_entry;
5243 }
5244
5245 /* Lookup a signature based type for DW_FORM_ref_sig8.
5246    Returns NULL if signature SIG is not present in the table.
5247    It is up to the caller to complain about this.  */
5248
5249 static struct signatured_type *
5250 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5251 {
5252   if (cu->dwo_unit
5253       && dwarf2_per_objfile->using_index)
5254     {
5255       /* We're in a DWO/DWP file, and we're using .gdb_index.
5256          These cases require special processing.  */
5257       if (get_dwp_file () == NULL)
5258         return lookup_dwo_signatured_type (cu, sig);
5259       else
5260         return lookup_dwp_signatured_type (cu, sig);
5261     }
5262   else
5263     {
5264       struct signatured_type find_entry, *entry;
5265
5266       if (dwarf2_per_objfile->signatured_types == NULL)
5267         return NULL;
5268       find_entry.signature = sig;
5269       entry = ((struct signatured_type *)
5270                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5271       return entry;
5272     }
5273 }
5274 \f
5275 /* Low level DIE reading support.  */
5276
5277 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5278
5279 static void
5280 init_cu_die_reader (struct die_reader_specs *reader,
5281                     struct dwarf2_cu *cu,
5282                     struct dwarf2_section_info *section,
5283                     struct dwo_file *dwo_file)
5284 {
5285   gdb_assert (section->readin && section->buffer != NULL);
5286   reader->abfd = get_section_bfd_owner (section);
5287   reader->cu = cu;
5288   reader->dwo_file = dwo_file;
5289   reader->die_section = section;
5290   reader->buffer = section->buffer;
5291   reader->buffer_end = section->buffer + section->size;
5292   reader->comp_dir = NULL;
5293 }
5294
5295 /* Subroutine of init_cutu_and_read_dies to simplify it.
5296    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5297    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5298    already.
5299
5300    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5301    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5302    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5303    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5304    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5305    STUB_COMP_DIR may be non-NULL.
5306    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5307    are filled in with the info of the DIE from the DWO file.
5308    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5309    provided an abbrev table to use.
5310    The result is non-zero if a valid (non-dummy) DIE was found.  */
5311
5312 static int
5313 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5314                         struct dwo_unit *dwo_unit,
5315                         int abbrev_table_provided,
5316                         struct die_info *stub_comp_unit_die,
5317                         const char *stub_comp_dir,
5318                         struct die_reader_specs *result_reader,
5319                         const gdb_byte **result_info_ptr,
5320                         struct die_info **result_comp_unit_die,
5321                         int *result_has_children)
5322 {
5323   struct objfile *objfile = dwarf2_per_objfile->objfile;
5324   struct dwarf2_cu *cu = this_cu->cu;
5325   struct dwarf2_section_info *section;
5326   bfd *abfd;
5327   const gdb_byte *begin_info_ptr, *info_ptr;
5328   ULONGEST signature; /* Or dwo_id.  */
5329   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5330   int i,num_extra_attrs;
5331   struct dwarf2_section_info *dwo_abbrev_section;
5332   struct attribute *attr;
5333   struct die_info *comp_unit_die;
5334
5335   /* At most one of these may be provided.  */
5336   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5337
5338   /* These attributes aren't processed until later:
5339      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5340      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5341      referenced later.  However, these attributes are found in the stub
5342      which we won't have later.  In order to not impose this complication
5343      on the rest of the code, we read them here and copy them to the
5344      DWO CU/TU die.  */
5345
5346   stmt_list = NULL;
5347   low_pc = NULL;
5348   high_pc = NULL;
5349   ranges = NULL;
5350   comp_dir = NULL;
5351
5352   if (stub_comp_unit_die != NULL)
5353     {
5354       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5355          DWO file.  */
5356       if (! this_cu->is_debug_types)
5357         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5358       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5359       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5360       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5361       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5362
5363       /* There should be a DW_AT_addr_base attribute here (if needed).
5364          We need the value before we can process DW_FORM_GNU_addr_index.  */
5365       cu->addr_base = 0;
5366       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5367       if (attr)
5368         cu->addr_base = DW_UNSND (attr);
5369
5370       /* There should be a DW_AT_ranges_base attribute here (if needed).
5371          We need the value before we can process DW_AT_ranges.  */
5372       cu->ranges_base = 0;
5373       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5374       if (attr)
5375         cu->ranges_base = DW_UNSND (attr);
5376     }
5377   else if (stub_comp_dir != NULL)
5378     {
5379       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5380       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5381       comp_dir->name = DW_AT_comp_dir;
5382       comp_dir->form = DW_FORM_string;
5383       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5384       DW_STRING (comp_dir) = stub_comp_dir;
5385     }
5386
5387   /* Set up for reading the DWO CU/TU.  */
5388   cu->dwo_unit = dwo_unit;
5389   section = dwo_unit->section;
5390   dwarf2_read_section (objfile, section);
5391   abfd = get_section_bfd_owner (section);
5392   begin_info_ptr = info_ptr = (section->buffer
5393                                + to_underlying (dwo_unit->sect_off));
5394   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5395   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5396
5397   if (this_cu->is_debug_types)
5398     {
5399       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5400
5401       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5402                                                 dwo_abbrev_section,
5403                                                 info_ptr, rcuh_kind::TYPE);
5404       /* This is not an assert because it can be caused by bad debug info.  */
5405       if (sig_type->signature != cu->header.signature)
5406         {
5407           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5408                    " TU at offset 0x%x [in module %s]"),
5409                  hex_string (sig_type->signature),
5410                  hex_string (cu->header.signature),
5411                  to_underlying (dwo_unit->sect_off),
5412                  bfd_get_filename (abfd));
5413         }
5414       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5415       /* For DWOs coming from DWP files, we don't know the CU length
5416          nor the type's offset in the TU until now.  */
5417       dwo_unit->length = get_cu_length (&cu->header);
5418       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5419
5420       /* Establish the type offset that can be used to lookup the type.
5421          For DWO files, we don't know it until now.  */
5422       sig_type->type_offset_in_section
5423         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5424     }
5425   else
5426     {
5427       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5428                                                 dwo_abbrev_section,
5429                                                 info_ptr, rcuh_kind::COMPILE);
5430       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5431       /* For DWOs coming from DWP files, we don't know the CU length
5432          until now.  */
5433       dwo_unit->length = get_cu_length (&cu->header);
5434     }
5435
5436   /* Replace the CU's original abbrev table with the DWO's.
5437      Reminder: We can't read the abbrev table until we've read the header.  */
5438   if (abbrev_table_provided)
5439     {
5440       /* Don't free the provided abbrev table, the caller of
5441          init_cutu_and_read_dies owns it.  */
5442       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5443       /* Ensure the DWO abbrev table gets freed.  */
5444       make_cleanup (dwarf2_free_abbrev_table, cu);
5445     }
5446   else
5447     {
5448       dwarf2_free_abbrev_table (cu);
5449       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5450       /* Leave any existing abbrev table cleanup as is.  */
5451     }
5452
5453   /* Read in the die, but leave space to copy over the attributes
5454      from the stub.  This has the benefit of simplifying the rest of
5455      the code - all the work to maintain the illusion of a single
5456      DW_TAG_{compile,type}_unit DIE is done here.  */
5457   num_extra_attrs = ((stmt_list != NULL)
5458                      + (low_pc != NULL)
5459                      + (high_pc != NULL)
5460                      + (ranges != NULL)
5461                      + (comp_dir != NULL));
5462   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5463                               result_has_children, num_extra_attrs);
5464
5465   /* Copy over the attributes from the stub to the DIE we just read in.  */
5466   comp_unit_die = *result_comp_unit_die;
5467   i = comp_unit_die->num_attrs;
5468   if (stmt_list != NULL)
5469     comp_unit_die->attrs[i++] = *stmt_list;
5470   if (low_pc != NULL)
5471     comp_unit_die->attrs[i++] = *low_pc;
5472   if (high_pc != NULL)
5473     comp_unit_die->attrs[i++] = *high_pc;
5474   if (ranges != NULL)
5475     comp_unit_die->attrs[i++] = *ranges;
5476   if (comp_dir != NULL)
5477     comp_unit_die->attrs[i++] = *comp_dir;
5478   comp_unit_die->num_attrs += num_extra_attrs;
5479
5480   if (dwarf_die_debug)
5481     {
5482       fprintf_unfiltered (gdb_stdlog,
5483                           "Read die from %s@0x%x of %s:\n",
5484                           get_section_name (section),
5485                           (unsigned) (begin_info_ptr - section->buffer),
5486                           bfd_get_filename (abfd));
5487       dump_die (comp_unit_die, dwarf_die_debug);
5488     }
5489
5490   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5491      TUs by skipping the stub and going directly to the entry in the DWO file.
5492      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5493      to get it via circuitous means.  Blech.  */
5494   if (comp_dir != NULL)
5495     result_reader->comp_dir = DW_STRING (comp_dir);
5496
5497   /* Skip dummy compilation units.  */
5498   if (info_ptr >= begin_info_ptr + dwo_unit->length
5499       || peek_abbrev_code (abfd, info_ptr) == 0)
5500     return 0;
5501
5502   *result_info_ptr = info_ptr;
5503   return 1;
5504 }
5505
5506 /* Subroutine of init_cutu_and_read_dies to simplify it.
5507    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5508    Returns NULL if the specified DWO unit cannot be found.  */
5509
5510 static struct dwo_unit *
5511 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5512                  struct die_info *comp_unit_die)
5513 {
5514   struct dwarf2_cu *cu = this_cu->cu;
5515   struct attribute *attr;
5516   ULONGEST signature;
5517   struct dwo_unit *dwo_unit;
5518   const char *comp_dir, *dwo_name;
5519
5520   gdb_assert (cu != NULL);
5521
5522   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5523   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5524   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5525
5526   if (this_cu->is_debug_types)
5527     {
5528       struct signatured_type *sig_type;
5529
5530       /* Since this_cu is the first member of struct signatured_type,
5531          we can go from a pointer to one to a pointer to the other.  */
5532       sig_type = (struct signatured_type *) this_cu;
5533       signature = sig_type->signature;
5534       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5535     }
5536   else
5537     {
5538       struct attribute *attr;
5539
5540       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5541       if (! attr)
5542         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5543                  " [in module %s]"),
5544                dwo_name, objfile_name (this_cu->objfile));
5545       signature = DW_UNSND (attr);
5546       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5547                                        signature);
5548     }
5549
5550   return dwo_unit;
5551 }
5552
5553 /* Subroutine of init_cutu_and_read_dies to simplify it.
5554    See it for a description of the parameters.
5555    Read a TU directly from a DWO file, bypassing the stub.
5556
5557    Note: This function could be a little bit simpler if we shared cleanups
5558    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5559    to do, so we keep this function self-contained.  Or we could move this
5560    into our caller, but it's complex enough already.  */
5561
5562 static void
5563 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5564                            int use_existing_cu, int keep,
5565                            die_reader_func_ftype *die_reader_func,
5566                            void *data)
5567 {
5568   struct dwarf2_cu *cu;
5569   struct signatured_type *sig_type;
5570   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5571   struct die_reader_specs reader;
5572   const gdb_byte *info_ptr;
5573   struct die_info *comp_unit_die;
5574   int has_children;
5575
5576   /* Verify we can do the following downcast, and that we have the
5577      data we need.  */
5578   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5579   sig_type = (struct signatured_type *) this_cu;
5580   gdb_assert (sig_type->dwo_unit != NULL);
5581
5582   cleanups = make_cleanup (null_cleanup, NULL);
5583
5584   if (use_existing_cu && this_cu->cu != NULL)
5585     {
5586       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5587       cu = this_cu->cu;
5588       /* There's no need to do the rereading_dwo_cu handling that
5589          init_cutu_and_read_dies does since we don't read the stub.  */
5590     }
5591   else
5592     {
5593       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5594       gdb_assert (this_cu->cu == NULL);
5595       cu = XNEW (struct dwarf2_cu);
5596       init_one_comp_unit (cu, this_cu);
5597       /* If an error occurs while loading, release our storage.  */
5598       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5599     }
5600
5601   /* A future optimization, if needed, would be to use an existing
5602      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5603      could share abbrev tables.  */
5604
5605   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5606                               0 /* abbrev_table_provided */,
5607                               NULL /* stub_comp_unit_die */,
5608                               sig_type->dwo_unit->dwo_file->comp_dir,
5609                               &reader, &info_ptr,
5610                               &comp_unit_die, &has_children) == 0)
5611     {
5612       /* Dummy die.  */
5613       do_cleanups (cleanups);
5614       return;
5615     }
5616
5617   /* All the "real" work is done here.  */
5618   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5619
5620   /* This duplicates the code in init_cutu_and_read_dies,
5621      but the alternative is making the latter more complex.
5622      This function is only for the special case of using DWO files directly:
5623      no point in overly complicating the general case just to handle this.  */
5624   if (free_cu_cleanup != NULL)
5625     {
5626       if (keep)
5627         {
5628           /* We've successfully allocated this compilation unit.  Let our
5629              caller clean it up when finished with it.  */
5630           discard_cleanups (free_cu_cleanup);
5631
5632           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5633              So we have to manually free the abbrev table.  */
5634           dwarf2_free_abbrev_table (cu);
5635
5636           /* Link this CU into read_in_chain.  */
5637           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5638           dwarf2_per_objfile->read_in_chain = this_cu;
5639         }
5640       else
5641         do_cleanups (free_cu_cleanup);
5642     }
5643
5644   do_cleanups (cleanups);
5645 }
5646
5647 /* Initialize a CU (or TU) and read its DIEs.
5648    If the CU defers to a DWO file, read the DWO file as well.
5649
5650    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5651    Otherwise the table specified in the comp unit header is read in and used.
5652    This is an optimization for when we already have the abbrev table.
5653
5654    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5655    Otherwise, a new CU is allocated with xmalloc.
5656
5657    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5658    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5659
5660    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5661    linker) then DIE_READER_FUNC will not get called.  */
5662
5663 static void
5664 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5665                          struct abbrev_table *abbrev_table,
5666                          int use_existing_cu, int keep,
5667                          die_reader_func_ftype *die_reader_func,
5668                          void *data)
5669 {
5670   struct objfile *objfile = dwarf2_per_objfile->objfile;
5671   struct dwarf2_section_info *section = this_cu->section;
5672   bfd *abfd = get_section_bfd_owner (section);
5673   struct dwarf2_cu *cu;
5674   const gdb_byte *begin_info_ptr, *info_ptr;
5675   struct die_reader_specs reader;
5676   struct die_info *comp_unit_die;
5677   int has_children;
5678   struct attribute *attr;
5679   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5680   struct signatured_type *sig_type = NULL;
5681   struct dwarf2_section_info *abbrev_section;
5682   /* Non-zero if CU currently points to a DWO file and we need to
5683      reread it.  When this happens we need to reread the skeleton die
5684      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5685   int rereading_dwo_cu = 0;
5686
5687   if (dwarf_die_debug)
5688     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5689                         this_cu->is_debug_types ? "type" : "comp",
5690                         to_underlying (this_cu->sect_off));
5691
5692   if (use_existing_cu)
5693     gdb_assert (keep);
5694
5695   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5696      file (instead of going through the stub), short-circuit all of this.  */
5697   if (this_cu->reading_dwo_directly)
5698     {
5699       /* Narrow down the scope of possibilities to have to understand.  */
5700       gdb_assert (this_cu->is_debug_types);
5701       gdb_assert (abbrev_table == NULL);
5702       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5703                                  die_reader_func, data);
5704       return;
5705     }
5706
5707   cleanups = make_cleanup (null_cleanup, NULL);
5708
5709   /* This is cheap if the section is already read in.  */
5710   dwarf2_read_section (objfile, section);
5711
5712   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5713
5714   abbrev_section = get_abbrev_section_for_cu (this_cu);
5715
5716   if (use_existing_cu && this_cu->cu != NULL)
5717     {
5718       cu = this_cu->cu;
5719       /* If this CU is from a DWO file we need to start over, we need to
5720          refetch the attributes from the skeleton CU.
5721          This could be optimized by retrieving those attributes from when we
5722          were here the first time: the previous comp_unit_die was stored in
5723          comp_unit_obstack.  But there's no data yet that we need this
5724          optimization.  */
5725       if (cu->dwo_unit != NULL)
5726         rereading_dwo_cu = 1;
5727     }
5728   else
5729     {
5730       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5731       gdb_assert (this_cu->cu == NULL);
5732       cu = XNEW (struct dwarf2_cu);
5733       init_one_comp_unit (cu, this_cu);
5734       /* If an error occurs while loading, release our storage.  */
5735       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5736     }
5737
5738   /* Get the header.  */
5739   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5740     {
5741       /* We already have the header, there's no need to read it in again.  */
5742       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5743     }
5744   else
5745     {
5746       if (this_cu->is_debug_types)
5747         {
5748           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5749                                                     abbrev_section, info_ptr,
5750                                                     rcuh_kind::TYPE);
5751
5752           /* Since per_cu is the first member of struct signatured_type,
5753              we can go from a pointer to one to a pointer to the other.  */
5754           sig_type = (struct signatured_type *) this_cu;
5755           gdb_assert (sig_type->signature == cu->header.signature);
5756           gdb_assert (sig_type->type_offset_in_tu
5757                       == cu->header.type_cu_offset_in_tu);
5758           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5759
5760           /* LENGTH has not been set yet for type units if we're
5761              using .gdb_index.  */
5762           this_cu->length = get_cu_length (&cu->header);
5763
5764           /* Establish the type offset that can be used to lookup the type.  */
5765           sig_type->type_offset_in_section =
5766             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5767
5768           this_cu->dwarf_version = cu->header.version;
5769         }
5770       else
5771         {
5772           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5773                                                     abbrev_section,
5774                                                     info_ptr,
5775                                                     rcuh_kind::COMPILE);
5776
5777           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5778           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5779           this_cu->dwarf_version = cu->header.version;
5780         }
5781     }
5782
5783   /* Skip dummy compilation units.  */
5784   if (info_ptr >= begin_info_ptr + this_cu->length
5785       || peek_abbrev_code (abfd, info_ptr) == 0)
5786     {
5787       do_cleanups (cleanups);
5788       return;
5789     }
5790
5791   /* If we don't have them yet, read the abbrevs for this compilation unit.
5792      And if we need to read them now, make sure they're freed when we're
5793      done.  Note that it's important that if the CU had an abbrev table
5794      on entry we don't free it when we're done: Somewhere up the call stack
5795      it may be in use.  */
5796   if (abbrev_table != NULL)
5797     {
5798       gdb_assert (cu->abbrev_table == NULL);
5799       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5800       cu->abbrev_table = abbrev_table;
5801     }
5802   else if (cu->abbrev_table == NULL)
5803     {
5804       dwarf2_read_abbrevs (cu, abbrev_section);
5805       make_cleanup (dwarf2_free_abbrev_table, cu);
5806     }
5807   else if (rereading_dwo_cu)
5808     {
5809       dwarf2_free_abbrev_table (cu);
5810       dwarf2_read_abbrevs (cu, abbrev_section);
5811     }
5812
5813   /* Read the top level CU/TU die.  */
5814   init_cu_die_reader (&reader, cu, section, NULL);
5815   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5816
5817   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5818      from the DWO file.
5819      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5820      DWO CU, that this test will fail (the attribute will not be present).  */
5821   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5822   if (attr)
5823     {
5824       struct dwo_unit *dwo_unit;
5825       struct die_info *dwo_comp_unit_die;
5826
5827       if (has_children)
5828         {
5829           complaint (&symfile_complaints,
5830                      _("compilation unit with DW_AT_GNU_dwo_name"
5831                        " has children (offset 0x%x) [in module %s]"),
5832                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5833         }
5834       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5835       if (dwo_unit != NULL)
5836         {
5837           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5838                                       abbrev_table != NULL,
5839                                       comp_unit_die, NULL,
5840                                       &reader, &info_ptr,
5841                                       &dwo_comp_unit_die, &has_children) == 0)
5842             {
5843               /* Dummy die.  */
5844               do_cleanups (cleanups);
5845               return;
5846             }
5847           comp_unit_die = dwo_comp_unit_die;
5848         }
5849       else
5850         {
5851           /* Yikes, we couldn't find the rest of the DIE, we only have
5852              the stub.  A complaint has already been logged.  There's
5853              not much more we can do except pass on the stub DIE to
5854              die_reader_func.  We don't want to throw an error on bad
5855              debug info.  */
5856         }
5857     }
5858
5859   /* All of the above is setup for this call.  Yikes.  */
5860   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5861
5862   /* Done, clean up.  */
5863   if (free_cu_cleanup != NULL)
5864     {
5865       if (keep)
5866         {
5867           /* We've successfully allocated this compilation unit.  Let our
5868              caller clean it up when finished with it.  */
5869           discard_cleanups (free_cu_cleanup);
5870
5871           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5872              So we have to manually free the abbrev table.  */
5873           dwarf2_free_abbrev_table (cu);
5874
5875           /* Link this CU into read_in_chain.  */
5876           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5877           dwarf2_per_objfile->read_in_chain = this_cu;
5878         }
5879       else
5880         do_cleanups (free_cu_cleanup);
5881     }
5882
5883   do_cleanups (cleanups);
5884 }
5885
5886 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5887    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5888    to have already done the lookup to find the DWO file).
5889
5890    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5891    THIS_CU->is_debug_types, but nothing else.
5892
5893    We fill in THIS_CU->length.
5894
5895    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5896    linker) then DIE_READER_FUNC will not get called.
5897
5898    THIS_CU->cu is always freed when done.
5899    This is done in order to not leave THIS_CU->cu in a state where we have
5900    to care whether it refers to the "main" CU or the DWO CU.  */
5901
5902 static void
5903 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5904                                    struct dwo_file *dwo_file,
5905                                    die_reader_func_ftype *die_reader_func,
5906                                    void *data)
5907 {
5908   struct objfile *objfile = dwarf2_per_objfile->objfile;
5909   struct dwarf2_section_info *section = this_cu->section;
5910   bfd *abfd = get_section_bfd_owner (section);
5911   struct dwarf2_section_info *abbrev_section;
5912   struct dwarf2_cu cu;
5913   const gdb_byte *begin_info_ptr, *info_ptr;
5914   struct die_reader_specs reader;
5915   struct cleanup *cleanups;
5916   struct die_info *comp_unit_die;
5917   int has_children;
5918
5919   if (dwarf_die_debug)
5920     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5921                         this_cu->is_debug_types ? "type" : "comp",
5922                         to_underlying (this_cu->sect_off));
5923
5924   gdb_assert (this_cu->cu == NULL);
5925
5926   abbrev_section = (dwo_file != NULL
5927                     ? &dwo_file->sections.abbrev
5928                     : get_abbrev_section_for_cu (this_cu));
5929
5930   /* This is cheap if the section is already read in.  */
5931   dwarf2_read_section (objfile, section);
5932
5933   init_one_comp_unit (&cu, this_cu);
5934
5935   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5936
5937   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5938   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5939                                             abbrev_section, info_ptr,
5940                                             (this_cu->is_debug_types
5941                                              ? rcuh_kind::TYPE
5942                                              : rcuh_kind::COMPILE));
5943
5944   this_cu->length = get_cu_length (&cu.header);
5945
5946   /* Skip dummy compilation units.  */
5947   if (info_ptr >= begin_info_ptr + this_cu->length
5948       || peek_abbrev_code (abfd, info_ptr) == 0)
5949     {
5950       do_cleanups (cleanups);
5951       return;
5952     }
5953
5954   dwarf2_read_abbrevs (&cu, abbrev_section);
5955   make_cleanup (dwarf2_free_abbrev_table, &cu);
5956
5957   init_cu_die_reader (&reader, &cu, section, dwo_file);
5958   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5959
5960   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5961
5962   do_cleanups (cleanups);
5963 }
5964
5965 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5966    does not lookup the specified DWO file.
5967    This cannot be used to read DWO files.
5968
5969    THIS_CU->cu is always freed when done.
5970    This is done in order to not leave THIS_CU->cu in a state where we have
5971    to care whether it refers to the "main" CU or the DWO CU.
5972    We can revisit this if the data shows there's a performance issue.  */
5973
5974 static void
5975 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5976                                 die_reader_func_ftype *die_reader_func,
5977                                 void *data)
5978 {
5979   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5980 }
5981 \f
5982 /* Type Unit Groups.
5983
5984    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5985    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5986    so that all types coming from the same compilation (.o file) are grouped
5987    together.  A future step could be to put the types in the same symtab as
5988    the CU the types ultimately came from.  */
5989
5990 static hashval_t
5991 hash_type_unit_group (const void *item)
5992 {
5993   const struct type_unit_group *tu_group
5994     = (const struct type_unit_group *) item;
5995
5996   return hash_stmt_list_entry (&tu_group->hash);
5997 }
5998
5999 static int
6000 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6001 {
6002   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6003   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6004
6005   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6006 }
6007
6008 /* Allocate a hash table for type unit groups.  */
6009
6010 static htab_t
6011 allocate_type_unit_groups_table (void)
6012 {
6013   return htab_create_alloc_ex (3,
6014                                hash_type_unit_group,
6015                                eq_type_unit_group,
6016                                NULL,
6017                                &dwarf2_per_objfile->objfile->objfile_obstack,
6018                                hashtab_obstack_allocate,
6019                                dummy_obstack_deallocate);
6020 }
6021
6022 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6023    partial symtabs.  We combine several TUs per psymtab to not let the size
6024    of any one psymtab grow too big.  */
6025 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6026 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6027
6028 /* Helper routine for get_type_unit_group.
6029    Create the type_unit_group object used to hold one or more TUs.  */
6030
6031 static struct type_unit_group *
6032 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6033 {
6034   struct objfile *objfile = dwarf2_per_objfile->objfile;
6035   struct dwarf2_per_cu_data *per_cu;
6036   struct type_unit_group *tu_group;
6037
6038   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6039                              struct type_unit_group);
6040   per_cu = &tu_group->per_cu;
6041   per_cu->objfile = objfile;
6042
6043   if (dwarf2_per_objfile->using_index)
6044     {
6045       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6046                                         struct dwarf2_per_cu_quick_data);
6047     }
6048   else
6049     {
6050       unsigned int line_offset = to_underlying (line_offset_struct);
6051       struct partial_symtab *pst;
6052       char *name;
6053
6054       /* Give the symtab a useful name for debug purposes.  */
6055       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6056         name = xstrprintf ("<type_units_%d>",
6057                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6058       else
6059         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6060
6061       pst = create_partial_symtab (per_cu, name);
6062       pst->anonymous = 1;
6063
6064       xfree (name);
6065     }
6066
6067   tu_group->hash.dwo_unit = cu->dwo_unit;
6068   tu_group->hash.line_sect_off = line_offset_struct;
6069
6070   return tu_group;
6071 }
6072
6073 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6074    STMT_LIST is a DW_AT_stmt_list attribute.  */
6075
6076 static struct type_unit_group *
6077 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6078 {
6079   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6080   struct type_unit_group *tu_group;
6081   void **slot;
6082   unsigned int line_offset;
6083   struct type_unit_group type_unit_group_for_lookup;
6084
6085   if (dwarf2_per_objfile->type_unit_groups == NULL)
6086     {
6087       dwarf2_per_objfile->type_unit_groups =
6088         allocate_type_unit_groups_table ();
6089     }
6090
6091   /* Do we need to create a new group, or can we use an existing one?  */
6092
6093   if (stmt_list)
6094     {
6095       line_offset = DW_UNSND (stmt_list);
6096       ++tu_stats->nr_symtab_sharers;
6097     }
6098   else
6099     {
6100       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6101          We can do various things here like create one group per TU or
6102          spread them over multiple groups to split up the expansion work.
6103          To avoid worst case scenarios (too many groups or too large groups)
6104          we, umm, group them in bunches.  */
6105       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6106                      | (tu_stats->nr_stmt_less_type_units
6107                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6108       ++tu_stats->nr_stmt_less_type_units;
6109     }
6110
6111   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6112   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6113   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6114                          &type_unit_group_for_lookup, INSERT);
6115   if (*slot != NULL)
6116     {
6117       tu_group = (struct type_unit_group *) *slot;
6118       gdb_assert (tu_group != NULL);
6119     }
6120   else
6121     {
6122       sect_offset line_offset_struct = (sect_offset) line_offset;
6123       tu_group = create_type_unit_group (cu, line_offset_struct);
6124       *slot = tu_group;
6125       ++tu_stats->nr_symtabs;
6126     }
6127
6128   return tu_group;
6129 }
6130 \f
6131 /* Partial symbol tables.  */
6132
6133 /* Create a psymtab named NAME and assign it to PER_CU.
6134
6135    The caller must fill in the following details:
6136    dirname, textlow, texthigh.  */
6137
6138 static struct partial_symtab *
6139 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6140 {
6141   struct objfile *objfile = per_cu->objfile;
6142   struct partial_symtab *pst;
6143
6144   pst = start_psymtab_common (objfile, name, 0,
6145                               objfile->global_psymbols,
6146                               objfile->static_psymbols);
6147
6148   pst->psymtabs_addrmap_supported = 1;
6149
6150   /* This is the glue that links PST into GDB's symbol API.  */
6151   pst->read_symtab_private = per_cu;
6152   pst->read_symtab = dwarf2_read_symtab;
6153   per_cu->v.psymtab = pst;
6154
6155   return pst;
6156 }
6157
6158 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6159    type.  */
6160
6161 struct process_psymtab_comp_unit_data
6162 {
6163   /* True if we are reading a DW_TAG_partial_unit.  */
6164
6165   int want_partial_unit;
6166
6167   /* The "pretend" language that is used if the CU doesn't declare a
6168      language.  */
6169
6170   enum language pretend_language;
6171 };
6172
6173 /* die_reader_func for process_psymtab_comp_unit.  */
6174
6175 static void
6176 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6177                                   const gdb_byte *info_ptr,
6178                                   struct die_info *comp_unit_die,
6179                                   int has_children,
6180                                   void *data)
6181 {
6182   struct dwarf2_cu *cu = reader->cu;
6183   struct objfile *objfile = cu->objfile;
6184   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6185   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6186   CORE_ADDR baseaddr;
6187   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6188   struct partial_symtab *pst;
6189   enum pc_bounds_kind cu_bounds_kind;
6190   const char *filename;
6191   struct process_psymtab_comp_unit_data *info
6192     = (struct process_psymtab_comp_unit_data *) data;
6193
6194   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6195     return;
6196
6197   gdb_assert (! per_cu->is_debug_types);
6198
6199   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6200
6201   cu->list_in_scope = &file_symbols;
6202
6203   /* Allocate a new partial symbol table structure.  */
6204   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6205   if (filename == NULL)
6206     filename = "";
6207
6208   pst = create_partial_symtab (per_cu, filename);
6209
6210   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6211   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6212
6213   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6214
6215   dwarf2_find_base_address (comp_unit_die, cu);
6216
6217   /* Possibly set the default values of LOWPC and HIGHPC from
6218      `DW_AT_ranges'.  */
6219   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6220                                          &best_highpc, cu, pst);
6221   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6222     /* Store the contiguous range if it is not empty; it can be empty for
6223        CUs with no code.  */
6224     addrmap_set_empty (objfile->psymtabs_addrmap,
6225                        gdbarch_adjust_dwarf2_addr (gdbarch,
6226                                                    best_lowpc + baseaddr),
6227                        gdbarch_adjust_dwarf2_addr (gdbarch,
6228                                                    best_highpc + baseaddr) - 1,
6229                        pst);
6230
6231   /* Check if comp unit has_children.
6232      If so, read the rest of the partial symbols from this comp unit.
6233      If not, there's no more debug_info for this comp unit.  */
6234   if (has_children)
6235     {
6236       struct partial_die_info *first_die;
6237       CORE_ADDR lowpc, highpc;
6238
6239       lowpc = ((CORE_ADDR) -1);
6240       highpc = ((CORE_ADDR) 0);
6241
6242       first_die = load_partial_dies (reader, info_ptr, 1);
6243
6244       scan_partial_symbols (first_die, &lowpc, &highpc,
6245                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6246
6247       /* If we didn't find a lowpc, set it to highpc to avoid
6248          complaints from `maint check'.  */
6249       if (lowpc == ((CORE_ADDR) -1))
6250         lowpc = highpc;
6251
6252       /* If the compilation unit didn't have an explicit address range,
6253          then use the information extracted from its child dies.  */
6254       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6255         {
6256           best_lowpc = lowpc;
6257           best_highpc = highpc;
6258         }
6259     }
6260   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6261   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6262
6263   end_psymtab_common (objfile, pst);
6264
6265   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6266     {
6267       int i;
6268       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6269       struct dwarf2_per_cu_data *iter;
6270
6271       /* Fill in 'dependencies' here; we fill in 'users' in a
6272          post-pass.  */
6273       pst->number_of_dependencies = len;
6274       pst->dependencies =
6275         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6276       for (i = 0;
6277            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6278                         i, iter);
6279            ++i)
6280         pst->dependencies[i] = iter->v.psymtab;
6281
6282       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6283     }
6284
6285   /* Get the list of files included in the current compilation unit,
6286      and build a psymtab for each of them.  */
6287   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6288
6289   if (dwarf_read_debug)
6290     {
6291       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6292
6293       fprintf_unfiltered (gdb_stdlog,
6294                           "Psymtab for %s unit @0x%x: %s - %s"
6295                           ", %d global, %d static syms\n",
6296                           per_cu->is_debug_types ? "type" : "comp",
6297                           to_underlying (per_cu->sect_off),
6298                           paddress (gdbarch, pst->textlow),
6299                           paddress (gdbarch, pst->texthigh),
6300                           pst->n_global_syms, pst->n_static_syms);
6301     }
6302 }
6303
6304 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6305    Process compilation unit THIS_CU for a psymtab.  */
6306
6307 static void
6308 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6309                            int want_partial_unit,
6310                            enum language pretend_language)
6311 {
6312   /* If this compilation unit was already read in, free the
6313      cached copy in order to read it in again.  This is
6314      necessary because we skipped some symbols when we first
6315      read in the compilation unit (see load_partial_dies).
6316      This problem could be avoided, but the benefit is unclear.  */
6317   if (this_cu->cu != NULL)
6318     free_one_cached_comp_unit (this_cu);
6319
6320   if (this_cu->is_debug_types)
6321     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6322                              NULL);
6323   else
6324     {
6325       process_psymtab_comp_unit_data info;
6326       info.want_partial_unit = want_partial_unit;
6327       info.pretend_language = pretend_language;
6328       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6329                                process_psymtab_comp_unit_reader, &info);
6330     }
6331
6332   /* Age out any secondary CUs.  */
6333   age_cached_comp_units ();
6334 }
6335
6336 /* Reader function for build_type_psymtabs.  */
6337
6338 static void
6339 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6340                             const gdb_byte *info_ptr,
6341                             struct die_info *type_unit_die,
6342                             int has_children,
6343                             void *data)
6344 {
6345   struct objfile *objfile = dwarf2_per_objfile->objfile;
6346   struct dwarf2_cu *cu = reader->cu;
6347   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6348   struct signatured_type *sig_type;
6349   struct type_unit_group *tu_group;
6350   struct attribute *attr;
6351   struct partial_die_info *first_die;
6352   CORE_ADDR lowpc, highpc;
6353   struct partial_symtab *pst;
6354
6355   gdb_assert (data == NULL);
6356   gdb_assert (per_cu->is_debug_types);
6357   sig_type = (struct signatured_type *) per_cu;
6358
6359   if (! has_children)
6360     return;
6361
6362   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6363   tu_group = get_type_unit_group (cu, attr);
6364
6365   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6366
6367   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6368   cu->list_in_scope = &file_symbols;
6369   pst = create_partial_symtab (per_cu, "");
6370   pst->anonymous = 1;
6371
6372   first_die = load_partial_dies (reader, info_ptr, 1);
6373
6374   lowpc = (CORE_ADDR) -1;
6375   highpc = (CORE_ADDR) 0;
6376   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6377
6378   end_psymtab_common (objfile, pst);
6379 }
6380
6381 /* Struct used to sort TUs by their abbreviation table offset.  */
6382
6383 struct tu_abbrev_offset
6384 {
6385   struct signatured_type *sig_type;
6386   sect_offset abbrev_offset;
6387 };
6388
6389 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6390
6391 static int
6392 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6393 {
6394   const struct tu_abbrev_offset * const *a
6395     = (const struct tu_abbrev_offset * const*) ap;
6396   const struct tu_abbrev_offset * const *b
6397     = (const struct tu_abbrev_offset * const*) bp;
6398   sect_offset aoff = (*a)->abbrev_offset;
6399   sect_offset boff = (*b)->abbrev_offset;
6400
6401   return (aoff > boff) - (aoff < boff);
6402 }
6403
6404 /* Efficiently read all the type units.
6405    This does the bulk of the work for build_type_psymtabs.
6406
6407    The efficiency is because we sort TUs by the abbrev table they use and
6408    only read each abbrev table once.  In one program there are 200K TUs
6409    sharing 8K abbrev tables.
6410
6411    The main purpose of this function is to support building the
6412    dwarf2_per_objfile->type_unit_groups table.
6413    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6414    can collapse the search space by grouping them by stmt_list.
6415    The savings can be significant, in the same program from above the 200K TUs
6416    share 8K stmt_list tables.
6417
6418    FUNC is expected to call get_type_unit_group, which will create the
6419    struct type_unit_group if necessary and add it to
6420    dwarf2_per_objfile->type_unit_groups.  */
6421
6422 static void
6423 build_type_psymtabs_1 (void)
6424 {
6425   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6426   struct cleanup *cleanups;
6427   struct abbrev_table *abbrev_table;
6428   sect_offset abbrev_offset;
6429   struct tu_abbrev_offset *sorted_by_abbrev;
6430   int i;
6431
6432   /* It's up to the caller to not call us multiple times.  */
6433   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6434
6435   if (dwarf2_per_objfile->n_type_units == 0)
6436     return;
6437
6438   /* TUs typically share abbrev tables, and there can be way more TUs than
6439      abbrev tables.  Sort by abbrev table to reduce the number of times we
6440      read each abbrev table in.
6441      Alternatives are to punt or to maintain a cache of abbrev tables.
6442      This is simpler and efficient enough for now.
6443
6444      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6445      symtab to use).  Typically TUs with the same abbrev offset have the same
6446      stmt_list value too so in practice this should work well.
6447
6448      The basic algorithm here is:
6449
6450       sort TUs by abbrev table
6451       for each TU with same abbrev table:
6452         read abbrev table if first user
6453         read TU top level DIE
6454           [IWBN if DWO skeletons had DW_AT_stmt_list]
6455         call FUNC  */
6456
6457   if (dwarf_read_debug)
6458     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6459
6460   /* Sort in a separate table to maintain the order of all_type_units
6461      for .gdb_index: TU indices directly index all_type_units.  */
6462   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6463                               dwarf2_per_objfile->n_type_units);
6464   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6465     {
6466       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6467
6468       sorted_by_abbrev[i].sig_type = sig_type;
6469       sorted_by_abbrev[i].abbrev_offset =
6470         read_abbrev_offset (sig_type->per_cu.section,
6471                             sig_type->per_cu.sect_off);
6472     }
6473   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6474   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6475          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6476
6477   abbrev_offset = (sect_offset) ~(unsigned) 0;
6478   abbrev_table = NULL;
6479   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6480
6481   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6482     {
6483       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6484
6485       /* Switch to the next abbrev table if necessary.  */
6486       if (abbrev_table == NULL
6487           || tu->abbrev_offset != abbrev_offset)
6488         {
6489           if (abbrev_table != NULL)
6490             {
6491               abbrev_table_free (abbrev_table);
6492               /* Reset to NULL in case abbrev_table_read_table throws
6493                  an error: abbrev_table_free_cleanup will get called.  */
6494               abbrev_table = NULL;
6495             }
6496           abbrev_offset = tu->abbrev_offset;
6497           abbrev_table =
6498             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6499                                      abbrev_offset);
6500           ++tu_stats->nr_uniq_abbrev_tables;
6501         }
6502
6503       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6504                                build_type_psymtabs_reader, NULL);
6505     }
6506
6507   do_cleanups (cleanups);
6508 }
6509
6510 /* Print collected type unit statistics.  */
6511
6512 static void
6513 print_tu_stats (void)
6514 {
6515   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6516
6517   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6518   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6519                       dwarf2_per_objfile->n_type_units);
6520   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6521                       tu_stats->nr_uniq_abbrev_tables);
6522   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6523                       tu_stats->nr_symtabs);
6524   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6525                       tu_stats->nr_symtab_sharers);
6526   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6527                       tu_stats->nr_stmt_less_type_units);
6528   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6529                       tu_stats->nr_all_type_units_reallocs);
6530 }
6531
6532 /* Traversal function for build_type_psymtabs.  */
6533
6534 static int
6535 build_type_psymtab_dependencies (void **slot, void *info)
6536 {
6537   struct objfile *objfile = dwarf2_per_objfile->objfile;
6538   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6539   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6540   struct partial_symtab *pst = per_cu->v.psymtab;
6541   int len = VEC_length (sig_type_ptr, tu_group->tus);
6542   struct signatured_type *iter;
6543   int i;
6544
6545   gdb_assert (len > 0);
6546   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6547
6548   pst->number_of_dependencies = len;
6549   pst->dependencies =
6550     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6551   for (i = 0;
6552        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6553        ++i)
6554     {
6555       gdb_assert (iter->per_cu.is_debug_types);
6556       pst->dependencies[i] = iter->per_cu.v.psymtab;
6557       iter->type_unit_group = tu_group;
6558     }
6559
6560   VEC_free (sig_type_ptr, tu_group->tus);
6561
6562   return 1;
6563 }
6564
6565 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6566    Build partial symbol tables for the .debug_types comp-units.  */
6567
6568 static void
6569 build_type_psymtabs (struct objfile *objfile)
6570 {
6571   if (! create_all_type_units (objfile))
6572     return;
6573
6574   build_type_psymtabs_1 ();
6575 }
6576
6577 /* Traversal function for process_skeletonless_type_unit.
6578    Read a TU in a DWO file and build partial symbols for it.  */
6579
6580 static int
6581 process_skeletonless_type_unit (void **slot, void *info)
6582 {
6583   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6584   struct objfile *objfile = (struct objfile *) info;
6585   struct signatured_type find_entry, *entry;
6586
6587   /* If this TU doesn't exist in the global table, add it and read it in.  */
6588
6589   if (dwarf2_per_objfile->signatured_types == NULL)
6590     {
6591       dwarf2_per_objfile->signatured_types
6592         = allocate_signatured_type_table (objfile);
6593     }
6594
6595   find_entry.signature = dwo_unit->signature;
6596   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6597                          INSERT);
6598   /* If we've already seen this type there's nothing to do.  What's happening
6599      is we're doing our own version of comdat-folding here.  */
6600   if (*slot != NULL)
6601     return 1;
6602
6603   /* This does the job that create_all_type_units would have done for
6604      this TU.  */
6605   entry = add_type_unit (dwo_unit->signature, slot);
6606   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6607   *slot = entry;
6608
6609   /* This does the job that build_type_psymtabs_1 would have done.  */
6610   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6611                            build_type_psymtabs_reader, NULL);
6612
6613   return 1;
6614 }
6615
6616 /* Traversal function for process_skeletonless_type_units.  */
6617
6618 static int
6619 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6620 {
6621   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6622
6623   if (dwo_file->tus != NULL)
6624     {
6625       htab_traverse_noresize (dwo_file->tus,
6626                               process_skeletonless_type_unit, info);
6627     }
6628
6629   return 1;
6630 }
6631
6632 /* Scan all TUs of DWO files, verifying we've processed them.
6633    This is needed in case a TU was emitted without its skeleton.
6634    Note: This can't be done until we know what all the DWO files are.  */
6635
6636 static void
6637 process_skeletonless_type_units (struct objfile *objfile)
6638 {
6639   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6640   if (get_dwp_file () == NULL
6641       && dwarf2_per_objfile->dwo_files != NULL)
6642     {
6643       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6644                               process_dwo_file_for_skeletonless_type_units,
6645                               objfile);
6646     }
6647 }
6648
6649 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6650
6651 static void
6652 set_partial_user (struct objfile *objfile)
6653 {
6654   int i;
6655
6656   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6657     {
6658       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6659       struct partial_symtab *pst = per_cu->v.psymtab;
6660       int j;
6661
6662       if (pst == NULL)
6663         continue;
6664
6665       for (j = 0; j < pst->number_of_dependencies; ++j)
6666         {
6667           /* Set the 'user' field only if it is not already set.  */
6668           if (pst->dependencies[j]->user == NULL)
6669             pst->dependencies[j]->user = pst;
6670         }
6671     }
6672 }
6673
6674 /* Build the partial symbol table by doing a quick pass through the
6675    .debug_info and .debug_abbrev sections.  */
6676
6677 static void
6678 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6679 {
6680   struct cleanup *back_to;
6681   int i;
6682
6683   if (dwarf_read_debug)
6684     {
6685       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6686                           objfile_name (objfile));
6687     }
6688
6689   dwarf2_per_objfile->reading_partial_symbols = 1;
6690
6691   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6692
6693   /* Any cached compilation units will be linked by the per-objfile
6694      read_in_chain.  Make sure to free them when we're done.  */
6695   back_to = make_cleanup (free_cached_comp_units, NULL);
6696
6697   build_type_psymtabs (objfile);
6698
6699   create_all_comp_units (objfile);
6700
6701   /* Create a temporary address map on a temporary obstack.  We later
6702      copy this to the final obstack.  */
6703   auto_obstack temp_obstack;
6704
6705   scoped_restore save_psymtabs_addrmap
6706     = make_scoped_restore (&objfile->psymtabs_addrmap,
6707                            addrmap_create_mutable (&temp_obstack));
6708
6709   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6710     {
6711       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6712
6713       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6714     }
6715
6716   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6717   process_skeletonless_type_units (objfile);
6718
6719   /* Now that all TUs have been processed we can fill in the dependencies.  */
6720   if (dwarf2_per_objfile->type_unit_groups != NULL)
6721     {
6722       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6723                               build_type_psymtab_dependencies, NULL);
6724     }
6725
6726   if (dwarf_read_debug)
6727     print_tu_stats ();
6728
6729   set_partial_user (objfile);
6730
6731   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6732                                                     &objfile->objfile_obstack);
6733   /* At this point we want to keep the address map.  */
6734   save_psymtabs_addrmap.release ();
6735
6736   do_cleanups (back_to);
6737
6738   if (dwarf_read_debug)
6739     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6740                         objfile_name (objfile));
6741 }
6742
6743 /* die_reader_func for load_partial_comp_unit.  */
6744
6745 static void
6746 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6747                                const gdb_byte *info_ptr,
6748                                struct die_info *comp_unit_die,
6749                                int has_children,
6750                                void *data)
6751 {
6752   struct dwarf2_cu *cu = reader->cu;
6753
6754   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6755
6756   /* Check if comp unit has_children.
6757      If so, read the rest of the partial symbols from this comp unit.
6758      If not, there's no more debug_info for this comp unit.  */
6759   if (has_children)
6760     load_partial_dies (reader, info_ptr, 0);
6761 }
6762
6763 /* Load the partial DIEs for a secondary CU into memory.
6764    This is also used when rereading a primary CU with load_all_dies.  */
6765
6766 static void
6767 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6768 {
6769   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6770                            load_partial_comp_unit_reader, NULL);
6771 }
6772
6773 static void
6774 read_comp_units_from_section (struct objfile *objfile,
6775                               struct dwarf2_section_info *section,
6776                               struct dwarf2_section_info *abbrev_section,
6777                               unsigned int is_dwz,
6778                               int *n_allocated,
6779                               int *n_comp_units,
6780                               struct dwarf2_per_cu_data ***all_comp_units)
6781 {
6782   const gdb_byte *info_ptr;
6783   bfd *abfd = get_section_bfd_owner (section);
6784
6785   if (dwarf_read_debug)
6786     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6787                         get_section_name (section),
6788                         get_section_file_name (section));
6789
6790   dwarf2_read_section (objfile, section);
6791
6792   info_ptr = section->buffer;
6793
6794   while (info_ptr < section->buffer + section->size)
6795     {
6796       struct dwarf2_per_cu_data *this_cu;
6797
6798       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6799
6800       comp_unit_head cu_header;
6801       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6802                                      info_ptr, rcuh_kind::COMPILE);
6803
6804       /* Save the compilation unit for later lookup.  */
6805       if (cu_header.unit_type != DW_UT_type)
6806         {
6807           this_cu = XOBNEW (&objfile->objfile_obstack,
6808                             struct dwarf2_per_cu_data);
6809           memset (this_cu, 0, sizeof (*this_cu));
6810         }
6811       else
6812         {
6813           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6814                                   struct signatured_type);
6815           memset (sig_type, 0, sizeof (*sig_type));
6816           sig_type->signature = cu_header.signature;
6817           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6818           this_cu = &sig_type->per_cu;
6819         }
6820       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6821       this_cu->sect_off = sect_off;
6822       this_cu->length = cu_header.length + cu_header.initial_length_size;
6823       this_cu->is_dwz = is_dwz;
6824       this_cu->objfile = objfile;
6825       this_cu->section = section;
6826
6827       if (*n_comp_units == *n_allocated)
6828         {
6829           *n_allocated *= 2;
6830           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6831                                         *all_comp_units, *n_allocated);
6832         }
6833       (*all_comp_units)[*n_comp_units] = this_cu;
6834       ++*n_comp_units;
6835
6836       info_ptr = info_ptr + this_cu->length;
6837     }
6838 }
6839
6840 /* Create a list of all compilation units in OBJFILE.
6841    This is only done for -readnow and building partial symtabs.  */
6842
6843 static void
6844 create_all_comp_units (struct objfile *objfile)
6845 {
6846   int n_allocated;
6847   int n_comp_units;
6848   struct dwarf2_per_cu_data **all_comp_units;
6849   struct dwz_file *dwz;
6850
6851   n_comp_units = 0;
6852   n_allocated = 10;
6853   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6854
6855   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6856                                 &dwarf2_per_objfile->abbrev, 0,
6857                                 &n_allocated, &n_comp_units, &all_comp_units);
6858
6859   dwz = dwarf2_get_dwz_file ();
6860   if (dwz != NULL)
6861     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6862                                   &n_allocated, &n_comp_units,
6863                                   &all_comp_units);
6864
6865   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6866                                                   struct dwarf2_per_cu_data *,
6867                                                   n_comp_units);
6868   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6869           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6870   xfree (all_comp_units);
6871   dwarf2_per_objfile->n_comp_units = n_comp_units;
6872 }
6873
6874 /* Process all loaded DIEs for compilation unit CU, starting at
6875    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6876    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6877    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6878    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6879
6880 static void
6881 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6882                       CORE_ADDR *highpc, int set_addrmap,
6883                       struct dwarf2_cu *cu)
6884 {
6885   struct partial_die_info *pdi;
6886
6887   /* Now, march along the PDI's, descending into ones which have
6888      interesting children but skipping the children of the other ones,
6889      until we reach the end of the compilation unit.  */
6890
6891   pdi = first_die;
6892
6893   while (pdi != NULL)
6894     {
6895       fixup_partial_die (pdi, cu);
6896
6897       /* Anonymous namespaces or modules have no name but have interesting
6898          children, so we need to look at them.  Ditto for anonymous
6899          enums.  */
6900
6901       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6902           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6903           || pdi->tag == DW_TAG_imported_unit)
6904         {
6905           switch (pdi->tag)
6906             {
6907             case DW_TAG_subprogram:
6908               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6909               break;
6910             case DW_TAG_constant:
6911             case DW_TAG_variable:
6912             case DW_TAG_typedef:
6913             case DW_TAG_union_type:
6914               if (!pdi->is_declaration)
6915                 {
6916                   add_partial_symbol (pdi, cu);
6917                 }
6918               break;
6919             case DW_TAG_class_type:
6920             case DW_TAG_interface_type:
6921             case DW_TAG_structure_type:
6922               if (!pdi->is_declaration)
6923                 {
6924                   add_partial_symbol (pdi, cu);
6925                 }
6926               if (cu->language == language_rust && pdi->has_children)
6927                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6928                                       set_addrmap, cu);
6929               break;
6930             case DW_TAG_enumeration_type:
6931               if (!pdi->is_declaration)
6932                 add_partial_enumeration (pdi, cu);
6933               break;
6934             case DW_TAG_base_type:
6935             case DW_TAG_subrange_type:
6936               /* File scope base type definitions are added to the partial
6937                  symbol table.  */
6938               add_partial_symbol (pdi, cu);
6939               break;
6940             case DW_TAG_namespace:
6941               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6942               break;
6943             case DW_TAG_module:
6944               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6945               break;
6946             case DW_TAG_imported_unit:
6947               {
6948                 struct dwarf2_per_cu_data *per_cu;
6949
6950                 /* For now we don't handle imported units in type units.  */
6951                 if (cu->per_cu->is_debug_types)
6952                   {
6953                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6954                              " supported in type units [in module %s]"),
6955                            objfile_name (cu->objfile));
6956                   }
6957
6958                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6959                                                            pdi->is_dwz,
6960                                                            cu->objfile);
6961
6962                 /* Go read the partial unit, if needed.  */
6963                 if (per_cu->v.psymtab == NULL)
6964                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6965
6966                 VEC_safe_push (dwarf2_per_cu_ptr,
6967                                cu->per_cu->imported_symtabs, per_cu);
6968               }
6969               break;
6970             case DW_TAG_imported_declaration:
6971               add_partial_symbol (pdi, cu);
6972               break;
6973             default:
6974               break;
6975             }
6976         }
6977
6978       /* If the die has a sibling, skip to the sibling.  */
6979
6980       pdi = pdi->die_sibling;
6981     }
6982 }
6983
6984 /* Functions used to compute the fully scoped name of a partial DIE.
6985
6986    Normally, this is simple.  For C++, the parent DIE's fully scoped
6987    name is concatenated with "::" and the partial DIE's name.
6988    Enumerators are an exception; they use the scope of their parent
6989    enumeration type, i.e. the name of the enumeration type is not
6990    prepended to the enumerator.
6991
6992    There are two complexities.  One is DW_AT_specification; in this
6993    case "parent" means the parent of the target of the specification,
6994    instead of the direct parent of the DIE.  The other is compilers
6995    which do not emit DW_TAG_namespace; in this case we try to guess
6996    the fully qualified name of structure types from their members'
6997    linkage names.  This must be done using the DIE's children rather
6998    than the children of any DW_AT_specification target.  We only need
6999    to do this for structures at the top level, i.e. if the target of
7000    any DW_AT_specification (if any; otherwise the DIE itself) does not
7001    have a parent.  */
7002
7003 /* Compute the scope prefix associated with PDI's parent, in
7004    compilation unit CU.  The result will be allocated on CU's
7005    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7006    field.  NULL is returned if no prefix is necessary.  */
7007 static const char *
7008 partial_die_parent_scope (struct partial_die_info *pdi,
7009                           struct dwarf2_cu *cu)
7010 {
7011   const char *grandparent_scope;
7012   struct partial_die_info *parent, *real_pdi;
7013
7014   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7015      then this means the parent of the specification DIE.  */
7016
7017   real_pdi = pdi;
7018   while (real_pdi->has_specification)
7019     real_pdi = find_partial_die (real_pdi->spec_offset,
7020                                  real_pdi->spec_is_dwz, cu);
7021
7022   parent = real_pdi->die_parent;
7023   if (parent == NULL)
7024     return NULL;
7025
7026   if (parent->scope_set)
7027     return parent->scope;
7028
7029   fixup_partial_die (parent, cu);
7030
7031   grandparent_scope = partial_die_parent_scope (parent, cu);
7032
7033   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7034      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7035      Work around this problem here.  */
7036   if (cu->language == language_cplus
7037       && parent->tag == DW_TAG_namespace
7038       && strcmp (parent->name, "::") == 0
7039       && grandparent_scope == NULL)
7040     {
7041       parent->scope = NULL;
7042       parent->scope_set = 1;
7043       return NULL;
7044     }
7045
7046   if (pdi->tag == DW_TAG_enumerator)
7047     /* Enumerators should not get the name of the enumeration as a prefix.  */
7048     parent->scope = grandparent_scope;
7049   else if (parent->tag == DW_TAG_namespace
7050       || parent->tag == DW_TAG_module
7051       || parent->tag == DW_TAG_structure_type
7052       || parent->tag == DW_TAG_class_type
7053       || parent->tag == DW_TAG_interface_type
7054       || parent->tag == DW_TAG_union_type
7055       || parent->tag == DW_TAG_enumeration_type)
7056     {
7057       if (grandparent_scope == NULL)
7058         parent->scope = parent->name;
7059       else
7060         parent->scope = typename_concat (&cu->comp_unit_obstack,
7061                                          grandparent_scope,
7062                                          parent->name, 0, cu);
7063     }
7064   else
7065     {
7066       /* FIXME drow/2004-04-01: What should we be doing with
7067          function-local names?  For partial symbols, we should probably be
7068          ignoring them.  */
7069       complaint (&symfile_complaints,
7070                  _("unhandled containing DIE tag %d for DIE at %d"),
7071                  parent->tag, to_underlying (pdi->sect_off));
7072       parent->scope = grandparent_scope;
7073     }
7074
7075   parent->scope_set = 1;
7076   return parent->scope;
7077 }
7078
7079 /* Return the fully scoped name associated with PDI, from compilation unit
7080    CU.  The result will be allocated with malloc.  */
7081
7082 static char *
7083 partial_die_full_name (struct partial_die_info *pdi,
7084                        struct dwarf2_cu *cu)
7085 {
7086   const char *parent_scope;
7087
7088   /* If this is a template instantiation, we can not work out the
7089      template arguments from partial DIEs.  So, unfortunately, we have
7090      to go through the full DIEs.  At least any work we do building
7091      types here will be reused if full symbols are loaded later.  */
7092   if (pdi->has_template_arguments)
7093     {
7094       fixup_partial_die (pdi, cu);
7095
7096       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7097         {
7098           struct die_info *die;
7099           struct attribute attr;
7100           struct dwarf2_cu *ref_cu = cu;
7101
7102           /* DW_FORM_ref_addr is using section offset.  */
7103           attr.name = (enum dwarf_attribute) 0;
7104           attr.form = DW_FORM_ref_addr;
7105           attr.u.unsnd = to_underlying (pdi->sect_off);
7106           die = follow_die_ref (NULL, &attr, &ref_cu);
7107
7108           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7109         }
7110     }
7111
7112   parent_scope = partial_die_parent_scope (pdi, cu);
7113   if (parent_scope == NULL)
7114     return NULL;
7115   else
7116     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7117 }
7118
7119 static void
7120 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7121 {
7122   struct objfile *objfile = cu->objfile;
7123   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7124   CORE_ADDR addr = 0;
7125   const char *actual_name = NULL;
7126   CORE_ADDR baseaddr;
7127   char *built_actual_name;
7128
7129   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7130
7131   built_actual_name = partial_die_full_name (pdi, cu);
7132   if (built_actual_name != NULL)
7133     actual_name = built_actual_name;
7134
7135   if (actual_name == NULL)
7136     actual_name = pdi->name;
7137
7138   switch (pdi->tag)
7139     {
7140     case DW_TAG_subprogram:
7141       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7142       if (pdi->is_external || cu->language == language_ada)
7143         {
7144           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7145              of the global scope.  But in Ada, we want to be able to access
7146              nested procedures globally.  So all Ada subprograms are stored
7147              in the global scope.  */
7148           add_psymbol_to_list (actual_name, strlen (actual_name),
7149                                built_actual_name != NULL,
7150                                VAR_DOMAIN, LOC_BLOCK,
7151                                &objfile->global_psymbols,
7152                                addr, cu->language, objfile);
7153         }
7154       else
7155         {
7156           add_psymbol_to_list (actual_name, strlen (actual_name),
7157                                built_actual_name != NULL,
7158                                VAR_DOMAIN, LOC_BLOCK,
7159                                &objfile->static_psymbols,
7160                                addr, cu->language, objfile);
7161         }
7162
7163       if (pdi->main_subprogram && actual_name != NULL)
7164         set_objfile_main_name (objfile, actual_name, cu->language);
7165       break;
7166     case DW_TAG_constant:
7167       {
7168         std::vector<partial_symbol *> *list;
7169
7170         if (pdi->is_external)
7171           list = &objfile->global_psymbols;
7172         else
7173           list = &objfile->static_psymbols;
7174         add_psymbol_to_list (actual_name, strlen (actual_name),
7175                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7176                              list, 0, cu->language, objfile);
7177       }
7178       break;
7179     case DW_TAG_variable:
7180       if (pdi->d.locdesc)
7181         addr = decode_locdesc (pdi->d.locdesc, cu);
7182
7183       if (pdi->d.locdesc
7184           && addr == 0
7185           && !dwarf2_per_objfile->has_section_at_zero)
7186         {
7187           /* A global or static variable may also have been stripped
7188              out by the linker if unused, in which case its address
7189              will be nullified; do not add such variables into partial
7190              symbol table then.  */
7191         }
7192       else if (pdi->is_external)
7193         {
7194           /* Global Variable.
7195              Don't enter into the minimal symbol tables as there is
7196              a minimal symbol table entry from the ELF symbols already.
7197              Enter into partial symbol table if it has a location
7198              descriptor or a type.
7199              If the location descriptor is missing, new_symbol will create
7200              a LOC_UNRESOLVED symbol, the address of the variable will then
7201              be determined from the minimal symbol table whenever the variable
7202              is referenced.
7203              The address for the partial symbol table entry is not
7204              used by GDB, but it comes in handy for debugging partial symbol
7205              table building.  */
7206
7207           if (pdi->d.locdesc || pdi->has_type)
7208             add_psymbol_to_list (actual_name, strlen (actual_name),
7209                                  built_actual_name != NULL,
7210                                  VAR_DOMAIN, LOC_STATIC,
7211                                  &objfile->global_psymbols,
7212                                  addr + baseaddr,
7213                                  cu->language, objfile);
7214         }
7215       else
7216         {
7217           int has_loc = pdi->d.locdesc != NULL;
7218
7219           /* Static Variable.  Skip symbols whose value we cannot know (those
7220              without location descriptors or constant values).  */
7221           if (!has_loc && !pdi->has_const_value)
7222             {
7223               xfree (built_actual_name);
7224               return;
7225             }
7226
7227           add_psymbol_to_list (actual_name, strlen (actual_name),
7228                                built_actual_name != NULL,
7229                                VAR_DOMAIN, LOC_STATIC,
7230                                &objfile->static_psymbols,
7231                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7232                                cu->language, objfile);
7233         }
7234       break;
7235     case DW_TAG_typedef:
7236     case DW_TAG_base_type:
7237     case DW_TAG_subrange_type:
7238       add_psymbol_to_list (actual_name, strlen (actual_name),
7239                            built_actual_name != NULL,
7240                            VAR_DOMAIN, LOC_TYPEDEF,
7241                            &objfile->static_psymbols,
7242                            0, cu->language, objfile);
7243       break;
7244     case DW_TAG_imported_declaration:
7245     case DW_TAG_namespace:
7246       add_psymbol_to_list (actual_name, strlen (actual_name),
7247                            built_actual_name != NULL,
7248                            VAR_DOMAIN, LOC_TYPEDEF,
7249                            &objfile->global_psymbols,
7250                            0, cu->language, objfile);
7251       break;
7252     case DW_TAG_module:
7253       add_psymbol_to_list (actual_name, strlen (actual_name),
7254                            built_actual_name != NULL,
7255                            MODULE_DOMAIN, LOC_TYPEDEF,
7256                            &objfile->global_psymbols,
7257                            0, cu->language, objfile);
7258       break;
7259     case DW_TAG_class_type:
7260     case DW_TAG_interface_type:
7261     case DW_TAG_structure_type:
7262     case DW_TAG_union_type:
7263     case DW_TAG_enumeration_type:
7264       /* Skip external references.  The DWARF standard says in the section
7265          about "Structure, Union, and Class Type Entries": "An incomplete
7266          structure, union or class type is represented by a structure,
7267          union or class entry that does not have a byte size attribute
7268          and that has a DW_AT_declaration attribute."  */
7269       if (!pdi->has_byte_size && pdi->is_declaration)
7270         {
7271           xfree (built_actual_name);
7272           return;
7273         }
7274
7275       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7276          static vs. global.  */
7277       add_psymbol_to_list (actual_name, strlen (actual_name),
7278                            built_actual_name != NULL,
7279                            STRUCT_DOMAIN, LOC_TYPEDEF,
7280                            cu->language == language_cplus
7281                            ? &objfile->global_psymbols
7282                            : &objfile->static_psymbols,
7283                            0, cu->language, objfile);
7284
7285       break;
7286     case DW_TAG_enumerator:
7287       add_psymbol_to_list (actual_name, strlen (actual_name),
7288                            built_actual_name != NULL,
7289                            VAR_DOMAIN, LOC_CONST,
7290                            cu->language == language_cplus
7291                            ? &objfile->global_psymbols
7292                            : &objfile->static_psymbols,
7293                            0, cu->language, objfile);
7294       break;
7295     default:
7296       break;
7297     }
7298
7299   xfree (built_actual_name);
7300 }
7301
7302 /* Read a partial die corresponding to a namespace; also, add a symbol
7303    corresponding to that namespace to the symbol table.  NAMESPACE is
7304    the name of the enclosing namespace.  */
7305
7306 static void
7307 add_partial_namespace (struct partial_die_info *pdi,
7308                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7309                        int set_addrmap, struct dwarf2_cu *cu)
7310 {
7311   /* Add a symbol for the namespace.  */
7312
7313   add_partial_symbol (pdi, cu);
7314
7315   /* Now scan partial symbols in that namespace.  */
7316
7317   if (pdi->has_children)
7318     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7319 }
7320
7321 /* Read a partial die corresponding to a Fortran module.  */
7322
7323 static void
7324 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7325                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7326 {
7327   /* Add a symbol for the namespace.  */
7328
7329   add_partial_symbol (pdi, cu);
7330
7331   /* Now scan partial symbols in that module.  */
7332
7333   if (pdi->has_children)
7334     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7335 }
7336
7337 /* Read a partial die corresponding to a subprogram and create a partial
7338    symbol for that subprogram.  When the CU language allows it, this
7339    routine also defines a partial symbol for each nested subprogram
7340    that this subprogram contains.  If SET_ADDRMAP is true, record the
7341    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7342    and highest PC values found in PDI.
7343
7344    PDI may also be a lexical block, in which case we simply search
7345    recursively for subprograms defined inside that lexical block.
7346    Again, this is only performed when the CU language allows this
7347    type of definitions.  */
7348
7349 static void
7350 add_partial_subprogram (struct partial_die_info *pdi,
7351                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7352                         int set_addrmap, struct dwarf2_cu *cu)
7353 {
7354   if (pdi->tag == DW_TAG_subprogram)
7355     {
7356       if (pdi->has_pc_info)
7357         {
7358           if (pdi->lowpc < *lowpc)
7359             *lowpc = pdi->lowpc;
7360           if (pdi->highpc > *highpc)
7361             *highpc = pdi->highpc;
7362           if (set_addrmap)
7363             {
7364               struct objfile *objfile = cu->objfile;
7365               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7366               CORE_ADDR baseaddr;
7367               CORE_ADDR highpc;
7368               CORE_ADDR lowpc;
7369
7370               baseaddr = ANOFFSET (objfile->section_offsets,
7371                                    SECT_OFF_TEXT (objfile));
7372               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7373                                                   pdi->lowpc + baseaddr);
7374               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7375                                                    pdi->highpc + baseaddr);
7376               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7377                                  cu->per_cu->v.psymtab);
7378             }
7379         }
7380
7381       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7382         {
7383           if (!pdi->is_declaration)
7384             /* Ignore subprogram DIEs that do not have a name, they are
7385                illegal.  Do not emit a complaint at this point, we will
7386                do so when we convert this psymtab into a symtab.  */
7387             if (pdi->name)
7388               add_partial_symbol (pdi, cu);
7389         }
7390     }
7391
7392   if (! pdi->has_children)
7393     return;
7394
7395   if (cu->language == language_ada)
7396     {
7397       pdi = pdi->die_child;
7398       while (pdi != NULL)
7399         {
7400           fixup_partial_die (pdi, cu);
7401           if (pdi->tag == DW_TAG_subprogram
7402               || pdi->tag == DW_TAG_lexical_block)
7403             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7404           pdi = pdi->die_sibling;
7405         }
7406     }
7407 }
7408
7409 /* Read a partial die corresponding to an enumeration type.  */
7410
7411 static void
7412 add_partial_enumeration (struct partial_die_info *enum_pdi,
7413                          struct dwarf2_cu *cu)
7414 {
7415   struct partial_die_info *pdi;
7416
7417   if (enum_pdi->name != NULL)
7418     add_partial_symbol (enum_pdi, cu);
7419
7420   pdi = enum_pdi->die_child;
7421   while (pdi)
7422     {
7423       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7424         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7425       else
7426         add_partial_symbol (pdi, cu);
7427       pdi = pdi->die_sibling;
7428     }
7429 }
7430
7431 /* Return the initial uleb128 in the die at INFO_PTR.  */
7432
7433 static unsigned int
7434 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7435 {
7436   unsigned int bytes_read;
7437
7438   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7439 }
7440
7441 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7442    Return the corresponding abbrev, or NULL if the number is zero (indicating
7443    an empty DIE).  In either case *BYTES_READ will be set to the length of
7444    the initial number.  */
7445
7446 static struct abbrev_info *
7447 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7448                  struct dwarf2_cu *cu)
7449 {
7450   bfd *abfd = cu->objfile->obfd;
7451   unsigned int abbrev_number;
7452   struct abbrev_info *abbrev;
7453
7454   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7455
7456   if (abbrev_number == 0)
7457     return NULL;
7458
7459   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7460   if (!abbrev)
7461     {
7462       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7463                " at offset 0x%x [in module %s]"),
7464              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7465              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7466     }
7467
7468   return abbrev;
7469 }
7470
7471 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7472    Returns a pointer to the end of a series of DIEs, terminated by an empty
7473    DIE.  Any children of the skipped DIEs will also be skipped.  */
7474
7475 static const gdb_byte *
7476 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7477 {
7478   struct dwarf2_cu *cu = reader->cu;
7479   struct abbrev_info *abbrev;
7480   unsigned int bytes_read;
7481
7482   while (1)
7483     {
7484       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7485       if (abbrev == NULL)
7486         return info_ptr + bytes_read;
7487       else
7488         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7489     }
7490 }
7491
7492 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7493    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7494    abbrev corresponding to that skipped uleb128 should be passed in
7495    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7496    children.  */
7497
7498 static const gdb_byte *
7499 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7500               struct abbrev_info *abbrev)
7501 {
7502   unsigned int bytes_read;
7503   struct attribute attr;
7504   bfd *abfd = reader->abfd;
7505   struct dwarf2_cu *cu = reader->cu;
7506   const gdb_byte *buffer = reader->buffer;
7507   const gdb_byte *buffer_end = reader->buffer_end;
7508   unsigned int form, i;
7509
7510   for (i = 0; i < abbrev->num_attrs; i++)
7511     {
7512       /* The only abbrev we care about is DW_AT_sibling.  */
7513       if (abbrev->attrs[i].name == DW_AT_sibling)
7514         {
7515           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7516           if (attr.form == DW_FORM_ref_addr)
7517             complaint (&symfile_complaints,
7518                        _("ignoring absolute DW_AT_sibling"));
7519           else
7520             {
7521               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7522               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7523
7524               if (sibling_ptr < info_ptr)
7525                 complaint (&symfile_complaints,
7526                            _("DW_AT_sibling points backwards"));
7527               else if (sibling_ptr > reader->buffer_end)
7528                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7529               else
7530                 return sibling_ptr;
7531             }
7532         }
7533
7534       /* If it isn't DW_AT_sibling, skip this attribute.  */
7535       form = abbrev->attrs[i].form;
7536     skip_attribute:
7537       switch (form)
7538         {
7539         case DW_FORM_ref_addr:
7540           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7541              and later it is offset sized.  */
7542           if (cu->header.version == 2)
7543             info_ptr += cu->header.addr_size;
7544           else
7545             info_ptr += cu->header.offset_size;
7546           break;
7547         case DW_FORM_GNU_ref_alt:
7548           info_ptr += cu->header.offset_size;
7549           break;
7550         case DW_FORM_addr:
7551           info_ptr += cu->header.addr_size;
7552           break;
7553         case DW_FORM_data1:
7554         case DW_FORM_ref1:
7555         case DW_FORM_flag:
7556           info_ptr += 1;
7557           break;
7558         case DW_FORM_flag_present:
7559         case DW_FORM_implicit_const:
7560           break;
7561         case DW_FORM_data2:
7562         case DW_FORM_ref2:
7563           info_ptr += 2;
7564           break;
7565         case DW_FORM_data4:
7566         case DW_FORM_ref4:
7567           info_ptr += 4;
7568           break;
7569         case DW_FORM_data8:
7570         case DW_FORM_ref8:
7571         case DW_FORM_ref_sig8:
7572           info_ptr += 8;
7573           break;
7574         case DW_FORM_data16:
7575           info_ptr += 16;
7576           break;
7577         case DW_FORM_string:
7578           read_direct_string (abfd, info_ptr, &bytes_read);
7579           info_ptr += bytes_read;
7580           break;
7581         case DW_FORM_sec_offset:
7582         case DW_FORM_strp:
7583         case DW_FORM_GNU_strp_alt:
7584           info_ptr += cu->header.offset_size;
7585           break;
7586         case DW_FORM_exprloc:
7587         case DW_FORM_block:
7588           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7589           info_ptr += bytes_read;
7590           break;
7591         case DW_FORM_block1:
7592           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7593           break;
7594         case DW_FORM_block2:
7595           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7596           break;
7597         case DW_FORM_block4:
7598           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7599           break;
7600         case DW_FORM_sdata:
7601         case DW_FORM_udata:
7602         case DW_FORM_ref_udata:
7603         case DW_FORM_GNU_addr_index:
7604         case DW_FORM_GNU_str_index:
7605           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7606           break;
7607         case DW_FORM_indirect:
7608           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7609           info_ptr += bytes_read;
7610           /* We need to continue parsing from here, so just go back to
7611              the top.  */
7612           goto skip_attribute;
7613
7614         default:
7615           error (_("Dwarf Error: Cannot handle %s "
7616                    "in DWARF reader [in module %s]"),
7617                  dwarf_form_name (form),
7618                  bfd_get_filename (abfd));
7619         }
7620     }
7621
7622   if (abbrev->has_children)
7623     return skip_children (reader, info_ptr);
7624   else
7625     return info_ptr;
7626 }
7627
7628 /* Locate ORIG_PDI's sibling.
7629    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7630
7631 static const gdb_byte *
7632 locate_pdi_sibling (const struct die_reader_specs *reader,
7633                     struct partial_die_info *orig_pdi,
7634                     const gdb_byte *info_ptr)
7635 {
7636   /* Do we know the sibling already?  */
7637
7638   if (orig_pdi->sibling)
7639     return orig_pdi->sibling;
7640
7641   /* Are there any children to deal with?  */
7642
7643   if (!orig_pdi->has_children)
7644     return info_ptr;
7645
7646   /* Skip the children the long way.  */
7647
7648   return skip_children (reader, info_ptr);
7649 }
7650
7651 /* Expand this partial symbol table into a full symbol table.  SELF is
7652    not NULL.  */
7653
7654 static void
7655 dwarf2_read_symtab (struct partial_symtab *self,
7656                     struct objfile *objfile)
7657 {
7658   if (self->readin)
7659     {
7660       warning (_("bug: psymtab for %s is already read in."),
7661                self->filename);
7662     }
7663   else
7664     {
7665       if (info_verbose)
7666         {
7667           printf_filtered (_("Reading in symbols for %s..."),
7668                            self->filename);
7669           gdb_flush (gdb_stdout);
7670         }
7671
7672       /* Restore our global data.  */
7673       dwarf2_per_objfile
7674         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7675                                                       dwarf2_objfile_data_key);
7676
7677       /* If this psymtab is constructed from a debug-only objfile, the
7678          has_section_at_zero flag will not necessarily be correct.  We
7679          can get the correct value for this flag by looking at the data
7680          associated with the (presumably stripped) associated objfile.  */
7681       if (objfile->separate_debug_objfile_backlink)
7682         {
7683           struct dwarf2_per_objfile *dpo_backlink
7684             = ((struct dwarf2_per_objfile *)
7685                objfile_data (objfile->separate_debug_objfile_backlink,
7686                              dwarf2_objfile_data_key));
7687
7688           dwarf2_per_objfile->has_section_at_zero
7689             = dpo_backlink->has_section_at_zero;
7690         }
7691
7692       dwarf2_per_objfile->reading_partial_symbols = 0;
7693
7694       psymtab_to_symtab_1 (self);
7695
7696       /* Finish up the debug error message.  */
7697       if (info_verbose)
7698         printf_filtered (_("done.\n"));
7699     }
7700
7701   process_cu_includes ();
7702 }
7703 \f
7704 /* Reading in full CUs.  */
7705
7706 /* Add PER_CU to the queue.  */
7707
7708 static void
7709 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7710                  enum language pretend_language)
7711 {
7712   struct dwarf2_queue_item *item;
7713
7714   per_cu->queued = 1;
7715   item = XNEW (struct dwarf2_queue_item);
7716   item->per_cu = per_cu;
7717   item->pretend_language = pretend_language;
7718   item->next = NULL;
7719
7720   if (dwarf2_queue == NULL)
7721     dwarf2_queue = item;
7722   else
7723     dwarf2_queue_tail->next = item;
7724
7725   dwarf2_queue_tail = item;
7726 }
7727
7728 /* If PER_CU is not yet queued, add it to the queue.
7729    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7730    dependency.
7731    The result is non-zero if PER_CU was queued, otherwise the result is zero
7732    meaning either PER_CU is already queued or it is already loaded.
7733
7734    N.B. There is an invariant here that if a CU is queued then it is loaded.
7735    The caller is required to load PER_CU if we return non-zero.  */
7736
7737 static int
7738 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7739                        struct dwarf2_per_cu_data *per_cu,
7740                        enum language pretend_language)
7741 {
7742   /* We may arrive here during partial symbol reading, if we need full
7743      DIEs to process an unusual case (e.g. template arguments).  Do
7744      not queue PER_CU, just tell our caller to load its DIEs.  */
7745   if (dwarf2_per_objfile->reading_partial_symbols)
7746     {
7747       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7748         return 1;
7749       return 0;
7750     }
7751
7752   /* Mark the dependence relation so that we don't flush PER_CU
7753      too early.  */
7754   if (dependent_cu != NULL)
7755     dwarf2_add_dependence (dependent_cu, per_cu);
7756
7757   /* If it's already on the queue, we have nothing to do.  */
7758   if (per_cu->queued)
7759     return 0;
7760
7761   /* If the compilation unit is already loaded, just mark it as
7762      used.  */
7763   if (per_cu->cu != NULL)
7764     {
7765       per_cu->cu->last_used = 0;
7766       return 0;
7767     }
7768
7769   /* Add it to the queue.  */
7770   queue_comp_unit (per_cu, pretend_language);
7771
7772   return 1;
7773 }
7774
7775 /* Process the queue.  */
7776
7777 static void
7778 process_queue (void)
7779 {
7780   struct dwarf2_queue_item *item, *next_item;
7781
7782   if (dwarf_read_debug)
7783     {
7784       fprintf_unfiltered (gdb_stdlog,
7785                           "Expanding one or more symtabs of objfile %s ...\n",
7786                           objfile_name (dwarf2_per_objfile->objfile));
7787     }
7788
7789   /* The queue starts out with one item, but following a DIE reference
7790      may load a new CU, adding it to the end of the queue.  */
7791   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7792     {
7793       if ((dwarf2_per_objfile->using_index
7794            ? !item->per_cu->v.quick->compunit_symtab
7795            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7796           /* Skip dummy CUs.  */
7797           && item->per_cu->cu != NULL)
7798         {
7799           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7800           unsigned int debug_print_threshold;
7801           char buf[100];
7802
7803           if (per_cu->is_debug_types)
7804             {
7805               struct signatured_type *sig_type =
7806                 (struct signatured_type *) per_cu;
7807
7808               sprintf (buf, "TU %s at offset 0x%x",
7809                        hex_string (sig_type->signature),
7810                        to_underlying (per_cu->sect_off));
7811               /* There can be 100s of TUs.
7812                  Only print them in verbose mode.  */
7813               debug_print_threshold = 2;
7814             }
7815           else
7816             {
7817               sprintf (buf, "CU at offset 0x%x",
7818                        to_underlying (per_cu->sect_off));
7819               debug_print_threshold = 1;
7820             }
7821
7822           if (dwarf_read_debug >= debug_print_threshold)
7823             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7824
7825           if (per_cu->is_debug_types)
7826             process_full_type_unit (per_cu, item->pretend_language);
7827           else
7828             process_full_comp_unit (per_cu, item->pretend_language);
7829
7830           if (dwarf_read_debug >= debug_print_threshold)
7831             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7832         }
7833
7834       item->per_cu->queued = 0;
7835       next_item = item->next;
7836       xfree (item);
7837     }
7838
7839   dwarf2_queue_tail = NULL;
7840
7841   if (dwarf_read_debug)
7842     {
7843       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7844                           objfile_name (dwarf2_per_objfile->objfile));
7845     }
7846 }
7847
7848 /* Free all allocated queue entries.  This function only releases anything if
7849    an error was thrown; if the queue was processed then it would have been
7850    freed as we went along.  */
7851
7852 static void
7853 dwarf2_release_queue (void *dummy)
7854 {
7855   struct dwarf2_queue_item *item, *last;
7856
7857   item = dwarf2_queue;
7858   while (item)
7859     {
7860       /* Anything still marked queued is likely to be in an
7861          inconsistent state, so discard it.  */
7862       if (item->per_cu->queued)
7863         {
7864           if (item->per_cu->cu != NULL)
7865             free_one_cached_comp_unit (item->per_cu);
7866           item->per_cu->queued = 0;
7867         }
7868
7869       last = item;
7870       item = item->next;
7871       xfree (last);
7872     }
7873
7874   dwarf2_queue = dwarf2_queue_tail = NULL;
7875 }
7876
7877 /* Read in full symbols for PST, and anything it depends on.  */
7878
7879 static void
7880 psymtab_to_symtab_1 (struct partial_symtab *pst)
7881 {
7882   struct dwarf2_per_cu_data *per_cu;
7883   int i;
7884
7885   if (pst->readin)
7886     return;
7887
7888   for (i = 0; i < pst->number_of_dependencies; i++)
7889     if (!pst->dependencies[i]->readin
7890         && pst->dependencies[i]->user == NULL)
7891       {
7892         /* Inform about additional files that need to be read in.  */
7893         if (info_verbose)
7894           {
7895             /* FIXME: i18n: Need to make this a single string.  */
7896             fputs_filtered (" ", gdb_stdout);
7897             wrap_here ("");
7898             fputs_filtered ("and ", gdb_stdout);
7899             wrap_here ("");
7900             printf_filtered ("%s...", pst->dependencies[i]->filename);
7901             wrap_here ("");     /* Flush output.  */
7902             gdb_flush (gdb_stdout);
7903           }
7904         psymtab_to_symtab_1 (pst->dependencies[i]);
7905       }
7906
7907   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7908
7909   if (per_cu == NULL)
7910     {
7911       /* It's an include file, no symbols to read for it.
7912          Everything is in the parent symtab.  */
7913       pst->readin = 1;
7914       return;
7915     }
7916
7917   dw2_do_instantiate_symtab (per_cu);
7918 }
7919
7920 /* Trivial hash function for die_info: the hash value of a DIE
7921    is its offset in .debug_info for this objfile.  */
7922
7923 static hashval_t
7924 die_hash (const void *item)
7925 {
7926   const struct die_info *die = (const struct die_info *) item;
7927
7928   return to_underlying (die->sect_off);
7929 }
7930
7931 /* Trivial comparison function for die_info structures: two DIEs
7932    are equal if they have the same offset.  */
7933
7934 static int
7935 die_eq (const void *item_lhs, const void *item_rhs)
7936 {
7937   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7938   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7939
7940   return die_lhs->sect_off == die_rhs->sect_off;
7941 }
7942
7943 /* die_reader_func for load_full_comp_unit.
7944    This is identical to read_signatured_type_reader,
7945    but is kept separate for now.  */
7946
7947 static void
7948 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7949                             const gdb_byte *info_ptr,
7950                             struct die_info *comp_unit_die,
7951                             int has_children,
7952                             void *data)
7953 {
7954   struct dwarf2_cu *cu = reader->cu;
7955   enum language *language_ptr = (enum language *) data;
7956
7957   gdb_assert (cu->die_hash == NULL);
7958   cu->die_hash =
7959     htab_create_alloc_ex (cu->header.length / 12,
7960                           die_hash,
7961                           die_eq,
7962                           NULL,
7963                           &cu->comp_unit_obstack,
7964                           hashtab_obstack_allocate,
7965                           dummy_obstack_deallocate);
7966
7967   if (has_children)
7968     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7969                                                   &info_ptr, comp_unit_die);
7970   cu->dies = comp_unit_die;
7971   /* comp_unit_die is not stored in die_hash, no need.  */
7972
7973   /* We try not to read any attributes in this function, because not
7974      all CUs needed for references have been loaded yet, and symbol
7975      table processing isn't initialized.  But we have to set the CU language,
7976      or we won't be able to build types correctly.
7977      Similarly, if we do not read the producer, we can not apply
7978      producer-specific interpretation.  */
7979   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7980 }
7981
7982 /* Load the DIEs associated with PER_CU into memory.  */
7983
7984 static void
7985 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7986                      enum language pretend_language)
7987 {
7988   gdb_assert (! this_cu->is_debug_types);
7989
7990   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7991                            load_full_comp_unit_reader, &pretend_language);
7992 }
7993
7994 /* Add a DIE to the delayed physname list.  */
7995
7996 static void
7997 add_to_method_list (struct type *type, int fnfield_index, int index,
7998                     const char *name, struct die_info *die,
7999                     struct dwarf2_cu *cu)
8000 {
8001   struct delayed_method_info mi;
8002   mi.type = type;
8003   mi.fnfield_index = fnfield_index;
8004   mi.index = index;
8005   mi.name = name;
8006   mi.die = die;
8007   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8008 }
8009
8010 /* A cleanup for freeing the delayed method list.  */
8011
8012 static void
8013 free_delayed_list (void *ptr)
8014 {
8015   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8016   if (cu->method_list != NULL)
8017     {
8018       VEC_free (delayed_method_info, cu->method_list);
8019       cu->method_list = NULL;
8020     }
8021 }
8022
8023 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8024    "const" / "volatile".  If so, decrements LEN by the length of the
8025    modifier and return true.  Otherwise return false.  */
8026
8027 template<size_t N>
8028 static bool
8029 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8030 {
8031   size_t mod_len = sizeof (mod) - 1;
8032   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8033     {
8034       len -= mod_len;
8035       return true;
8036     }
8037   return false;
8038 }
8039
8040 /* Compute the physnames of any methods on the CU's method list.
8041
8042    The computation of method physnames is delayed in order to avoid the
8043    (bad) condition that one of the method's formal parameters is of an as yet
8044    incomplete type.  */
8045
8046 static void
8047 compute_delayed_physnames (struct dwarf2_cu *cu)
8048 {
8049   int i;
8050   struct delayed_method_info *mi;
8051
8052   /* Only C++ delays computing physnames.  */
8053   if (VEC_empty (delayed_method_info, cu->method_list))
8054     return;
8055   gdb_assert (cu->language == language_cplus);
8056
8057   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8058     {
8059       const char *physname;
8060       struct fn_fieldlist *fn_flp
8061         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8062       physname = dwarf2_physname (mi->name, mi->die, cu);
8063       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8064         = physname ? physname : "";
8065
8066       /* Since there's no tag to indicate whether a method is a
8067          const/volatile overload, extract that information out of the
8068          demangled name.  */
8069       if (physname != NULL)
8070         {
8071           size_t len = strlen (physname);
8072
8073           while (1)
8074             {
8075               if (physname[len] == ')') /* shortcut */
8076                 break;
8077               else if (check_modifier (physname, len, " const"))
8078                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8079               else if (check_modifier (physname, len, " volatile"))
8080                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8081               else
8082                 break;
8083             }
8084         }
8085     }
8086 }
8087
8088 /* Go objects should be embedded in a DW_TAG_module DIE,
8089    and it's not clear if/how imported objects will appear.
8090    To keep Go support simple until that's worked out,
8091    go back through what we've read and create something usable.
8092    We could do this while processing each DIE, and feels kinda cleaner,
8093    but that way is more invasive.
8094    This is to, for example, allow the user to type "p var" or "b main"
8095    without having to specify the package name, and allow lookups
8096    of module.object to work in contexts that use the expression
8097    parser.  */
8098
8099 static void
8100 fixup_go_packaging (struct dwarf2_cu *cu)
8101 {
8102   char *package_name = NULL;
8103   struct pending *list;
8104   int i;
8105
8106   for (list = global_symbols; list != NULL; list = list->next)
8107     {
8108       for (i = 0; i < list->nsyms; ++i)
8109         {
8110           struct symbol *sym = list->symbol[i];
8111
8112           if (SYMBOL_LANGUAGE (sym) == language_go
8113               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8114             {
8115               char *this_package_name = go_symbol_package_name (sym);
8116
8117               if (this_package_name == NULL)
8118                 continue;
8119               if (package_name == NULL)
8120                 package_name = this_package_name;
8121               else
8122                 {
8123                   if (strcmp (package_name, this_package_name) != 0)
8124                     complaint (&symfile_complaints,
8125                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8126                                (symbol_symtab (sym) != NULL
8127                                 ? symtab_to_filename_for_display
8128                                     (symbol_symtab (sym))
8129                                 : objfile_name (cu->objfile)),
8130                                this_package_name, package_name);
8131                   xfree (this_package_name);
8132                 }
8133             }
8134         }
8135     }
8136
8137   if (package_name != NULL)
8138     {
8139       struct objfile *objfile = cu->objfile;
8140       const char *saved_package_name
8141         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8142                                         package_name,
8143                                         strlen (package_name));
8144       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8145                                      saved_package_name);
8146       struct symbol *sym;
8147
8148       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8149
8150       sym = allocate_symbol (objfile);
8151       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8152       SYMBOL_SET_NAMES (sym, saved_package_name,
8153                         strlen (saved_package_name), 0, objfile);
8154       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8155          e.g., "main" finds the "main" module and not C's main().  */
8156       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8157       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8158       SYMBOL_TYPE (sym) = type;
8159
8160       add_symbol_to_list (sym, &global_symbols);
8161
8162       xfree (package_name);
8163     }
8164 }
8165
8166 /* Return the symtab for PER_CU.  This works properly regardless of
8167    whether we're using the index or psymtabs.  */
8168
8169 static struct compunit_symtab *
8170 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8171 {
8172   return (dwarf2_per_objfile->using_index
8173           ? per_cu->v.quick->compunit_symtab
8174           : per_cu->v.psymtab->compunit_symtab);
8175 }
8176
8177 /* A helper function for computing the list of all symbol tables
8178    included by PER_CU.  */
8179
8180 static void
8181 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8182                                 htab_t all_children, htab_t all_type_symtabs,
8183                                 struct dwarf2_per_cu_data *per_cu,
8184                                 struct compunit_symtab *immediate_parent)
8185 {
8186   void **slot;
8187   int ix;
8188   struct compunit_symtab *cust;
8189   struct dwarf2_per_cu_data *iter;
8190
8191   slot = htab_find_slot (all_children, per_cu, INSERT);
8192   if (*slot != NULL)
8193     {
8194       /* This inclusion and its children have been processed.  */
8195       return;
8196     }
8197
8198   *slot = per_cu;
8199   /* Only add a CU if it has a symbol table.  */
8200   cust = get_compunit_symtab (per_cu);
8201   if (cust != NULL)
8202     {
8203       /* If this is a type unit only add its symbol table if we haven't
8204          seen it yet (type unit per_cu's can share symtabs).  */
8205       if (per_cu->is_debug_types)
8206         {
8207           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8208           if (*slot == NULL)
8209             {
8210               *slot = cust;
8211               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8212               if (cust->user == NULL)
8213                 cust->user = immediate_parent;
8214             }
8215         }
8216       else
8217         {
8218           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8219           if (cust->user == NULL)
8220             cust->user = immediate_parent;
8221         }
8222     }
8223
8224   for (ix = 0;
8225        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8226        ++ix)
8227     {
8228       recursively_compute_inclusions (result, all_children,
8229                                       all_type_symtabs, iter, cust);
8230     }
8231 }
8232
8233 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8234    PER_CU.  */
8235
8236 static void
8237 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8238 {
8239   gdb_assert (! per_cu->is_debug_types);
8240
8241   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8242     {
8243       int ix, len;
8244       struct dwarf2_per_cu_data *per_cu_iter;
8245       struct compunit_symtab *compunit_symtab_iter;
8246       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8247       htab_t all_children, all_type_symtabs;
8248       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8249
8250       /* If we don't have a symtab, we can just skip this case.  */
8251       if (cust == NULL)
8252         return;
8253
8254       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8255                                         NULL, xcalloc, xfree);
8256       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8257                                             NULL, xcalloc, xfree);
8258
8259       for (ix = 0;
8260            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8261                         ix, per_cu_iter);
8262            ++ix)
8263         {
8264           recursively_compute_inclusions (&result_symtabs, all_children,
8265                                           all_type_symtabs, per_cu_iter,
8266                                           cust);
8267         }
8268
8269       /* Now we have a transitive closure of all the included symtabs.  */
8270       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8271       cust->includes
8272         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8273                      struct compunit_symtab *, len + 1);
8274       for (ix = 0;
8275            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8276                         compunit_symtab_iter);
8277            ++ix)
8278         cust->includes[ix] = compunit_symtab_iter;
8279       cust->includes[len] = NULL;
8280
8281       VEC_free (compunit_symtab_ptr, result_symtabs);
8282       htab_delete (all_children);
8283       htab_delete (all_type_symtabs);
8284     }
8285 }
8286
8287 /* Compute the 'includes' field for the symtabs of all the CUs we just
8288    read.  */
8289
8290 static void
8291 process_cu_includes (void)
8292 {
8293   int ix;
8294   struct dwarf2_per_cu_data *iter;
8295
8296   for (ix = 0;
8297        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8298                     ix, iter);
8299        ++ix)
8300     {
8301       if (! iter->is_debug_types)
8302         compute_compunit_symtab_includes (iter);
8303     }
8304
8305   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8306 }
8307
8308 /* Generate full symbol information for PER_CU, whose DIEs have
8309    already been loaded into memory.  */
8310
8311 static void
8312 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8313                         enum language pretend_language)
8314 {
8315   struct dwarf2_cu *cu = per_cu->cu;
8316   struct objfile *objfile = per_cu->objfile;
8317   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8318   CORE_ADDR lowpc, highpc;
8319   struct compunit_symtab *cust;
8320   struct cleanup *back_to, *delayed_list_cleanup;
8321   CORE_ADDR baseaddr;
8322   struct block *static_block;
8323   CORE_ADDR addr;
8324
8325   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8326
8327   buildsym_init ();
8328   back_to = make_cleanup (really_free_pendings, NULL);
8329   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8330
8331   cu->list_in_scope = &file_symbols;
8332
8333   cu->language = pretend_language;
8334   cu->language_defn = language_def (cu->language);
8335
8336   /* Do line number decoding in read_file_scope () */
8337   process_die (cu->dies, cu);
8338
8339   /* For now fudge the Go package.  */
8340   if (cu->language == language_go)
8341     fixup_go_packaging (cu);
8342
8343   /* Now that we have processed all the DIEs in the CU, all the types 
8344      should be complete, and it should now be safe to compute all of the
8345      physnames.  */
8346   compute_delayed_physnames (cu);
8347   do_cleanups (delayed_list_cleanup);
8348
8349   /* Some compilers don't define a DW_AT_high_pc attribute for the
8350      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8351      it, by scanning the DIE's below the compilation unit.  */
8352   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8353
8354   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8355   static_block = end_symtab_get_static_block (addr, 0, 1);
8356
8357   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8358      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8359      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8360      addrmap to help ensure it has an accurate map of pc values belonging to
8361      this comp unit.  */
8362   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8363
8364   cust = end_symtab_from_static_block (static_block,
8365                                        SECT_OFF_TEXT (objfile), 0);
8366
8367   if (cust != NULL)
8368     {
8369       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8370
8371       /* Set symtab language to language from DW_AT_language.  If the
8372          compilation is from a C file generated by language preprocessors, do
8373          not set the language if it was already deduced by start_subfile.  */
8374       if (!(cu->language == language_c
8375             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8376         COMPUNIT_FILETABS (cust)->language = cu->language;
8377
8378       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8379          produce DW_AT_location with location lists but it can be possibly
8380          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8381          there were bugs in prologue debug info, fixed later in GCC-4.5
8382          by "unwind info for epilogues" patch (which is not directly related).
8383
8384          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8385          needed, it would be wrong due to missing DW_AT_producer there.
8386
8387          Still one can confuse GDB by using non-standard GCC compilation
8388          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8389          */ 
8390       if (cu->has_loclist && gcc_4_minor >= 5)
8391         cust->locations_valid = 1;
8392
8393       if (gcc_4_minor >= 5)
8394         cust->epilogue_unwind_valid = 1;
8395
8396       cust->call_site_htab = cu->call_site_htab;
8397     }
8398
8399   if (dwarf2_per_objfile->using_index)
8400     per_cu->v.quick->compunit_symtab = cust;
8401   else
8402     {
8403       struct partial_symtab *pst = per_cu->v.psymtab;
8404       pst->compunit_symtab = cust;
8405       pst->readin = 1;
8406     }
8407
8408   /* Push it for inclusion processing later.  */
8409   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8410
8411   do_cleanups (back_to);
8412 }
8413
8414 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8415    already been loaded into memory.  */
8416
8417 static void
8418 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8419                         enum language pretend_language)
8420 {
8421   struct dwarf2_cu *cu = per_cu->cu;
8422   struct objfile *objfile = per_cu->objfile;
8423   struct compunit_symtab *cust;
8424   struct cleanup *back_to, *delayed_list_cleanup;
8425   struct signatured_type *sig_type;
8426
8427   gdb_assert (per_cu->is_debug_types);
8428   sig_type = (struct signatured_type *) per_cu;
8429
8430   buildsym_init ();
8431   back_to = make_cleanup (really_free_pendings, NULL);
8432   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8433
8434   cu->list_in_scope = &file_symbols;
8435
8436   cu->language = pretend_language;
8437   cu->language_defn = language_def (cu->language);
8438
8439   /* The symbol tables are set up in read_type_unit_scope.  */
8440   process_die (cu->dies, cu);
8441
8442   /* For now fudge the Go package.  */
8443   if (cu->language == language_go)
8444     fixup_go_packaging (cu);
8445
8446   /* Now that we have processed all the DIEs in the CU, all the types 
8447      should be complete, and it should now be safe to compute all of the
8448      physnames.  */
8449   compute_delayed_physnames (cu);
8450   do_cleanups (delayed_list_cleanup);
8451
8452   /* TUs share symbol tables.
8453      If this is the first TU to use this symtab, complete the construction
8454      of it with end_expandable_symtab.  Otherwise, complete the addition of
8455      this TU's symbols to the existing symtab.  */
8456   if (sig_type->type_unit_group->compunit_symtab == NULL)
8457     {
8458       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8459       sig_type->type_unit_group->compunit_symtab = cust;
8460
8461       if (cust != NULL)
8462         {
8463           /* Set symtab language to language from DW_AT_language.  If the
8464              compilation is from a C file generated by language preprocessors,
8465              do not set the language if it was already deduced by
8466              start_subfile.  */
8467           if (!(cu->language == language_c
8468                 && COMPUNIT_FILETABS (cust)->language != language_c))
8469             COMPUNIT_FILETABS (cust)->language = cu->language;
8470         }
8471     }
8472   else
8473     {
8474       augment_type_symtab ();
8475       cust = sig_type->type_unit_group->compunit_symtab;
8476     }
8477
8478   if (dwarf2_per_objfile->using_index)
8479     per_cu->v.quick->compunit_symtab = cust;
8480   else
8481     {
8482       struct partial_symtab *pst = per_cu->v.psymtab;
8483       pst->compunit_symtab = cust;
8484       pst->readin = 1;
8485     }
8486
8487   do_cleanups (back_to);
8488 }
8489
8490 /* Process an imported unit DIE.  */
8491
8492 static void
8493 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8494 {
8495   struct attribute *attr;
8496
8497   /* For now we don't handle imported units in type units.  */
8498   if (cu->per_cu->is_debug_types)
8499     {
8500       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8501                " supported in type units [in module %s]"),
8502              objfile_name (cu->objfile));
8503     }
8504
8505   attr = dwarf2_attr (die, DW_AT_import, cu);
8506   if (attr != NULL)
8507     {
8508       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8509       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8510       dwarf2_per_cu_data *per_cu
8511         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8512
8513       /* If necessary, add it to the queue and load its DIEs.  */
8514       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8515         load_full_comp_unit (per_cu, cu->language);
8516
8517       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8518                      per_cu);
8519     }
8520 }
8521
8522 /* RAII object that represents a process_die scope: i.e.,
8523    starts/finishes processing a DIE.  */
8524 class process_die_scope
8525 {
8526 public:
8527   process_die_scope (die_info *die, dwarf2_cu *cu)
8528     : m_die (die), m_cu (cu)
8529   {
8530     /* We should only be processing DIEs not already in process.  */
8531     gdb_assert (!m_die->in_process);
8532     m_die->in_process = true;
8533   }
8534
8535   ~process_die_scope ()
8536   {
8537     m_die->in_process = false;
8538
8539     /* If we're done processing the DIE for the CU that owns the line
8540        header, we don't need the line header anymore.  */
8541     if (m_cu->line_header_die_owner == m_die)
8542       {
8543         delete m_cu->line_header;
8544         m_cu->line_header = NULL;
8545         m_cu->line_header_die_owner = NULL;
8546       }
8547   }
8548
8549 private:
8550   die_info *m_die;
8551   dwarf2_cu *m_cu;
8552 };
8553
8554 /* Process a die and its children.  */
8555
8556 static void
8557 process_die (struct die_info *die, struct dwarf2_cu *cu)
8558 {
8559   process_die_scope scope (die, cu);
8560
8561   switch (die->tag)
8562     {
8563     case DW_TAG_padding:
8564       break;
8565     case DW_TAG_compile_unit:
8566     case DW_TAG_partial_unit:
8567       read_file_scope (die, cu);
8568       break;
8569     case DW_TAG_type_unit:
8570       read_type_unit_scope (die, cu);
8571       break;
8572     case DW_TAG_subprogram:
8573     case DW_TAG_inlined_subroutine:
8574       read_func_scope (die, cu);
8575       break;
8576     case DW_TAG_lexical_block:
8577     case DW_TAG_try_block:
8578     case DW_TAG_catch_block:
8579       read_lexical_block_scope (die, cu);
8580       break;
8581     case DW_TAG_call_site:
8582     case DW_TAG_GNU_call_site:
8583       read_call_site_scope (die, cu);
8584       break;
8585     case DW_TAG_class_type:
8586     case DW_TAG_interface_type:
8587     case DW_TAG_structure_type:
8588     case DW_TAG_union_type:
8589       process_structure_scope (die, cu);
8590       break;
8591     case DW_TAG_enumeration_type:
8592       process_enumeration_scope (die, cu);
8593       break;
8594
8595     /* These dies have a type, but processing them does not create
8596        a symbol or recurse to process the children.  Therefore we can
8597        read them on-demand through read_type_die.  */
8598     case DW_TAG_subroutine_type:
8599     case DW_TAG_set_type:
8600     case DW_TAG_array_type:
8601     case DW_TAG_pointer_type:
8602     case DW_TAG_ptr_to_member_type:
8603     case DW_TAG_reference_type:
8604     case DW_TAG_rvalue_reference_type:
8605     case DW_TAG_string_type:
8606       break;
8607
8608     case DW_TAG_base_type:
8609     case DW_TAG_subrange_type:
8610     case DW_TAG_typedef:
8611       /* Add a typedef symbol for the type definition, if it has a
8612          DW_AT_name.  */
8613       new_symbol (die, read_type_die (die, cu), cu);
8614       break;
8615     case DW_TAG_common_block:
8616       read_common_block (die, cu);
8617       break;
8618     case DW_TAG_common_inclusion:
8619       break;
8620     case DW_TAG_namespace:
8621       cu->processing_has_namespace_info = 1;
8622       read_namespace (die, cu);
8623       break;
8624     case DW_TAG_module:
8625       cu->processing_has_namespace_info = 1;
8626       read_module (die, cu);
8627       break;
8628     case DW_TAG_imported_declaration:
8629       cu->processing_has_namespace_info = 1;
8630       if (read_namespace_alias (die, cu))
8631         break;
8632       /* The declaration is not a global namespace alias: fall through.  */
8633     case DW_TAG_imported_module:
8634       cu->processing_has_namespace_info = 1;
8635       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8636                                  || cu->language != language_fortran))
8637         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8638                    dwarf_tag_name (die->tag));
8639       read_import_statement (die, cu);
8640       break;
8641
8642     case DW_TAG_imported_unit:
8643       process_imported_unit_die (die, cu);
8644       break;
8645
8646     default:
8647       new_symbol (die, NULL, cu);
8648       break;
8649     }
8650 }
8651 \f
8652 /* DWARF name computation.  */
8653
8654 /* A helper function for dwarf2_compute_name which determines whether DIE
8655    needs to have the name of the scope prepended to the name listed in the
8656    die.  */
8657
8658 static int
8659 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8660 {
8661   struct attribute *attr;
8662
8663   switch (die->tag)
8664     {
8665     case DW_TAG_namespace:
8666     case DW_TAG_typedef:
8667     case DW_TAG_class_type:
8668     case DW_TAG_interface_type:
8669     case DW_TAG_structure_type:
8670     case DW_TAG_union_type:
8671     case DW_TAG_enumeration_type:
8672     case DW_TAG_enumerator:
8673     case DW_TAG_subprogram:
8674     case DW_TAG_inlined_subroutine:
8675     case DW_TAG_member:
8676     case DW_TAG_imported_declaration:
8677       return 1;
8678
8679     case DW_TAG_variable:
8680     case DW_TAG_constant:
8681       /* We only need to prefix "globally" visible variables.  These include
8682          any variable marked with DW_AT_external or any variable that
8683          lives in a namespace.  [Variables in anonymous namespaces
8684          require prefixing, but they are not DW_AT_external.]  */
8685
8686       if (dwarf2_attr (die, DW_AT_specification, cu))
8687         {
8688           struct dwarf2_cu *spec_cu = cu;
8689
8690           return die_needs_namespace (die_specification (die, &spec_cu),
8691                                       spec_cu);
8692         }
8693
8694       attr = dwarf2_attr (die, DW_AT_external, cu);
8695       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8696           && die->parent->tag != DW_TAG_module)
8697         return 0;
8698       /* A variable in a lexical block of some kind does not need a
8699          namespace, even though in C++ such variables may be external
8700          and have a mangled name.  */
8701       if (die->parent->tag ==  DW_TAG_lexical_block
8702           || die->parent->tag ==  DW_TAG_try_block
8703           || die->parent->tag ==  DW_TAG_catch_block
8704           || die->parent->tag == DW_TAG_subprogram)
8705         return 0;
8706       return 1;
8707
8708     default:
8709       return 0;
8710     }
8711 }
8712
8713 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
8714    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8715    defined for the given DIE.  */
8716
8717 static struct attribute *
8718 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
8719 {
8720   struct attribute *attr;
8721
8722   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8723   if (attr == NULL)
8724     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8725
8726   return attr;
8727 }
8728
8729 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
8730    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8731    defined for the given DIE.  */
8732
8733 static const char *
8734 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
8735 {
8736   const char *linkage_name;
8737
8738   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8739   if (linkage_name == NULL)
8740     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8741
8742   return linkage_name;
8743 }
8744
8745 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8746    compute the physname for the object, which include a method's:
8747    - formal parameters (C++),
8748    - receiver type (Go),
8749
8750    The term "physname" is a bit confusing.
8751    For C++, for example, it is the demangled name.
8752    For Go, for example, it's the mangled name.
8753
8754    For Ada, return the DIE's linkage name rather than the fully qualified
8755    name.  PHYSNAME is ignored..
8756
8757    The result is allocated on the objfile_obstack and canonicalized.  */
8758
8759 static const char *
8760 dwarf2_compute_name (const char *name,
8761                      struct die_info *die, struct dwarf2_cu *cu,
8762                      int physname)
8763 {
8764   struct objfile *objfile = cu->objfile;
8765
8766   if (name == NULL)
8767     name = dwarf2_name (die, cu);
8768
8769   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8770      but otherwise compute it by typename_concat inside GDB.
8771      FIXME: Actually this is not really true, or at least not always true.
8772      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8773      Fortran names because there is no mangling standard.  So new_symbol_full
8774      will set the demangled name to the result of dwarf2_full_name, and it is
8775      the demangled name that GDB uses if it exists.  */
8776   if (cu->language == language_ada
8777       || (cu->language == language_fortran && physname))
8778     {
8779       /* For Ada unit, we prefer the linkage name over the name, as
8780          the former contains the exported name, which the user expects
8781          to be able to reference.  Ideally, we want the user to be able
8782          to reference this entity using either natural or linkage name,
8783          but we haven't started looking at this enhancement yet.  */
8784       const char *linkage_name = dw2_linkage_name (die, cu);
8785
8786       if (linkage_name != NULL)
8787         return linkage_name;
8788     }
8789
8790   /* These are the only languages we know how to qualify names in.  */
8791   if (name != NULL
8792       && (cu->language == language_cplus
8793           || cu->language == language_fortran || cu->language == language_d
8794           || cu->language == language_rust))
8795     {
8796       if (die_needs_namespace (die, cu))
8797         {
8798           long length;
8799           const char *prefix;
8800           const char *canonical_name = NULL;
8801
8802           string_file buf;
8803
8804           prefix = determine_prefix (die, cu);
8805           if (*prefix != '\0')
8806             {
8807               char *prefixed_name = typename_concat (NULL, prefix, name,
8808                                                      physname, cu);
8809
8810               buf.puts (prefixed_name);
8811               xfree (prefixed_name);
8812             }
8813           else
8814             buf.puts (name);
8815
8816           /* Template parameters may be specified in the DIE's DW_AT_name, or
8817              as children with DW_TAG_template_type_param or
8818              DW_TAG_value_type_param.  If the latter, add them to the name
8819              here.  If the name already has template parameters, then
8820              skip this step; some versions of GCC emit both, and
8821              it is more efficient to use the pre-computed name.
8822
8823              Something to keep in mind about this process: it is very
8824              unlikely, or in some cases downright impossible, to produce
8825              something that will match the mangled name of a function.
8826              If the definition of the function has the same debug info,
8827              we should be able to match up with it anyway.  But fallbacks
8828              using the minimal symbol, for instance to find a method
8829              implemented in a stripped copy of libstdc++, will not work.
8830              If we do not have debug info for the definition, we will have to
8831              match them up some other way.
8832
8833              When we do name matching there is a related problem with function
8834              templates; two instantiated function templates are allowed to
8835              differ only by their return types, which we do not add here.  */
8836
8837           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8838             {
8839               struct attribute *attr;
8840               struct die_info *child;
8841               int first = 1;
8842
8843               die->building_fullname = 1;
8844
8845               for (child = die->child; child != NULL; child = child->sibling)
8846                 {
8847                   struct type *type;
8848                   LONGEST value;
8849                   const gdb_byte *bytes;
8850                   struct dwarf2_locexpr_baton *baton;
8851                   struct value *v;
8852
8853                   if (child->tag != DW_TAG_template_type_param
8854                       && child->tag != DW_TAG_template_value_param)
8855                     continue;
8856
8857                   if (first)
8858                     {
8859                       buf.puts ("<");
8860                       first = 0;
8861                     }
8862                   else
8863                     buf.puts (", ");
8864
8865                   attr = dwarf2_attr (child, DW_AT_type, cu);
8866                   if (attr == NULL)
8867                     {
8868                       complaint (&symfile_complaints,
8869                                  _("template parameter missing DW_AT_type"));
8870                       buf.puts ("UNKNOWN_TYPE");
8871                       continue;
8872                     }
8873                   type = die_type (child, cu);
8874
8875                   if (child->tag == DW_TAG_template_type_param)
8876                     {
8877                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8878                       continue;
8879                     }
8880
8881                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8882                   if (attr == NULL)
8883                     {
8884                       complaint (&symfile_complaints,
8885                                  _("template parameter missing "
8886                                    "DW_AT_const_value"));
8887                       buf.puts ("UNKNOWN_VALUE");
8888                       continue;
8889                     }
8890
8891                   dwarf2_const_value_attr (attr, type, name,
8892                                            &cu->comp_unit_obstack, cu,
8893                                            &value, &bytes, &baton);
8894
8895                   if (TYPE_NOSIGN (type))
8896                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8897                        changed, this can use value_print instead.  */
8898                     c_printchar (value, type, &buf);
8899                   else
8900                     {
8901                       struct value_print_options opts;
8902
8903                       if (baton != NULL)
8904                         v = dwarf2_evaluate_loc_desc (type, NULL,
8905                                                       baton->data,
8906                                                       baton->size,
8907                                                       baton->per_cu);
8908                       else if (bytes != NULL)
8909                         {
8910                           v = allocate_value (type);
8911                           memcpy (value_contents_writeable (v), bytes,
8912                                   TYPE_LENGTH (type));
8913                         }
8914                       else
8915                         v = value_from_longest (type, value);
8916
8917                       /* Specify decimal so that we do not depend on
8918                          the radix.  */
8919                       get_formatted_print_options (&opts, 'd');
8920                       opts.raw = 1;
8921                       value_print (v, &buf, &opts);
8922                       release_value (v);
8923                       value_free (v);
8924                     }
8925                 }
8926
8927               die->building_fullname = 0;
8928
8929               if (!first)
8930                 {
8931                   /* Close the argument list, with a space if necessary
8932                      (nested templates).  */
8933                   if (!buf.empty () && buf.string ().back () == '>')
8934                     buf.puts (" >");
8935                   else
8936                     buf.puts (">");
8937                 }
8938             }
8939
8940           /* For C++ methods, append formal parameter type
8941              information, if PHYSNAME.  */
8942
8943           if (physname && die->tag == DW_TAG_subprogram
8944               && cu->language == language_cplus)
8945             {
8946               struct type *type = read_type_die (die, cu);
8947
8948               c_type_print_args (type, &buf, 1, cu->language,
8949                                  &type_print_raw_options);
8950
8951               if (cu->language == language_cplus)
8952                 {
8953                   /* Assume that an artificial first parameter is
8954                      "this", but do not crash if it is not.  RealView
8955                      marks unnamed (and thus unused) parameters as
8956                      artificial; there is no way to differentiate
8957                      the two cases.  */
8958                   if (TYPE_NFIELDS (type) > 0
8959                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8960                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8961                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8962                                                                         0))))
8963                     buf.puts (" const");
8964                 }
8965             }
8966
8967           const std::string &intermediate_name = buf.string ();
8968
8969           if (cu->language == language_cplus)
8970             canonical_name
8971               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8972                                           &objfile->per_bfd->storage_obstack);
8973
8974           /* If we only computed INTERMEDIATE_NAME, or if
8975              INTERMEDIATE_NAME is already canonical, then we need to
8976              copy it to the appropriate obstack.  */
8977           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8978             name = ((const char *)
8979                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8980                                    intermediate_name.c_str (),
8981                                    intermediate_name.length ()));
8982           else
8983             name = canonical_name;
8984         }
8985     }
8986
8987   return name;
8988 }
8989
8990 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8991    If scope qualifiers are appropriate they will be added.  The result
8992    will be allocated on the storage_obstack, or NULL if the DIE does
8993    not have a name.  NAME may either be from a previous call to
8994    dwarf2_name or NULL.
8995
8996    The output string will be canonicalized (if C++).  */
8997
8998 static const char *
8999 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9000 {
9001   return dwarf2_compute_name (name, die, cu, 0);
9002 }
9003
9004 /* Construct a physname for the given DIE in CU.  NAME may either be
9005    from a previous call to dwarf2_name or NULL.  The result will be
9006    allocated on the objfile_objstack or NULL if the DIE does not have a
9007    name.
9008
9009    The output string will be canonicalized (if C++).  */
9010
9011 static const char *
9012 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9013 {
9014   struct objfile *objfile = cu->objfile;
9015   const char *retval, *mangled = NULL, *canon = NULL;
9016   int need_copy = 1;
9017
9018   /* In this case dwarf2_compute_name is just a shortcut not building anything
9019      on its own.  */
9020   if (!die_needs_namespace (die, cu))
9021     return dwarf2_compute_name (name, die, cu, 1);
9022
9023   mangled = dw2_linkage_name (die, cu);
9024
9025   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9026      See https://github.com/rust-lang/rust/issues/32925.  */
9027   if (cu->language == language_rust && mangled != NULL
9028       && strchr (mangled, '{') != NULL)
9029     mangled = NULL;
9030
9031   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9032      has computed.  */
9033   gdb::unique_xmalloc_ptr<char> demangled;
9034   if (mangled != NULL)
9035     {
9036       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9037          type.  It is easier for GDB users to search for such functions as
9038          `name(params)' than `long name(params)'.  In such case the minimal
9039          symbol names do not match the full symbol names but for template
9040          functions there is never a need to look up their definition from their
9041          declaration so the only disadvantage remains the minimal symbol
9042          variant `long name(params)' does not have the proper inferior type.
9043          */
9044
9045       if (cu->language == language_go)
9046         {
9047           /* This is a lie, but we already lie to the caller new_symbol_full.
9048              new_symbol_full assumes we return the mangled name.
9049              This just undoes that lie until things are cleaned up.  */
9050         }
9051       else
9052         {
9053           demangled.reset (gdb_demangle (mangled,
9054                                          (DMGL_PARAMS | DMGL_ANSI
9055                                           | DMGL_RET_DROP)));
9056         }
9057       if (demangled)
9058         canon = demangled.get ();
9059       else
9060         {
9061           canon = mangled;
9062           need_copy = 0;
9063         }
9064     }
9065
9066   if (canon == NULL || check_physname)
9067     {
9068       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9069
9070       if (canon != NULL && strcmp (physname, canon) != 0)
9071         {
9072           /* It may not mean a bug in GDB.  The compiler could also
9073              compute DW_AT_linkage_name incorrectly.  But in such case
9074              GDB would need to be bug-to-bug compatible.  */
9075
9076           complaint (&symfile_complaints,
9077                      _("Computed physname <%s> does not match demangled <%s> "
9078                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9079                      physname, canon, mangled, to_underlying (die->sect_off),
9080                      objfile_name (objfile));
9081
9082           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9083              is available here - over computed PHYSNAME.  It is safer
9084              against both buggy GDB and buggy compilers.  */
9085
9086           retval = canon;
9087         }
9088       else
9089         {
9090           retval = physname;
9091           need_copy = 0;
9092         }
9093     }
9094   else
9095     retval = canon;
9096
9097   if (need_copy)
9098     retval = ((const char *)
9099               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9100                              retval, strlen (retval)));
9101
9102   return retval;
9103 }
9104
9105 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9106    a new symbol for it.
9107
9108    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9109
9110 static int
9111 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9112 {
9113   struct attribute *attr;
9114
9115   /* If the die does not have a name, this is not a namespace
9116      alias.  */
9117   attr = dwarf2_attr (die, DW_AT_name, cu);
9118   if (attr != NULL)
9119     {
9120       int num;
9121       struct die_info *d = die;
9122       struct dwarf2_cu *imported_cu = cu;
9123
9124       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9125          keep inspecting DIEs until we hit the underlying import.  */
9126 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9127       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9128         {
9129           attr = dwarf2_attr (d, DW_AT_import, cu);
9130           if (attr == NULL)
9131             break;
9132
9133           d = follow_die_ref (d, attr, &imported_cu);
9134           if (d->tag != DW_TAG_imported_declaration)
9135             break;
9136         }
9137
9138       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9139         {
9140           complaint (&symfile_complaints,
9141                      _("DIE at 0x%x has too many recursively imported "
9142                        "declarations"), to_underlying (d->sect_off));
9143           return 0;
9144         }
9145
9146       if (attr != NULL)
9147         {
9148           struct type *type;
9149           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9150
9151           type = get_die_type_at_offset (sect_off, cu->per_cu);
9152           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9153             {
9154               /* This declaration is a global namespace alias.  Add
9155                  a symbol for it whose type is the aliased namespace.  */
9156               new_symbol (die, type, cu);
9157               return 1;
9158             }
9159         }
9160     }
9161
9162   return 0;
9163 }
9164
9165 /* Return the using directives repository (global or local?) to use in the
9166    current context for LANGUAGE.
9167
9168    For Ada, imported declarations can materialize renamings, which *may* be
9169    global.  However it is impossible (for now?) in DWARF to distinguish
9170    "external" imported declarations and "static" ones.  As all imported
9171    declarations seem to be static in all other languages, make them all CU-wide
9172    global only in Ada.  */
9173
9174 static struct using_direct **
9175 using_directives (enum language language)
9176 {
9177   if (language == language_ada && context_stack_depth == 0)
9178     return &global_using_directives;
9179   else
9180     return &local_using_directives;
9181 }
9182
9183 /* Read the import statement specified by the given die and record it.  */
9184
9185 static void
9186 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9187 {
9188   struct objfile *objfile = cu->objfile;
9189   struct attribute *import_attr;
9190   struct die_info *imported_die, *child_die;
9191   struct dwarf2_cu *imported_cu;
9192   const char *imported_name;
9193   const char *imported_name_prefix;
9194   const char *canonical_name;
9195   const char *import_alias;
9196   const char *imported_declaration = NULL;
9197   const char *import_prefix;
9198   std::vector<const char *> excludes;
9199
9200   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9201   if (import_attr == NULL)
9202     {
9203       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9204                  dwarf_tag_name (die->tag));
9205       return;
9206     }
9207
9208   imported_cu = cu;
9209   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9210   imported_name = dwarf2_name (imported_die, imported_cu);
9211   if (imported_name == NULL)
9212     {
9213       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9214
9215         The import in the following code:
9216         namespace A
9217           {
9218             typedef int B;
9219           }
9220
9221         int main ()
9222           {
9223             using A::B;
9224             B b;
9225             return b;
9226           }
9227
9228         ...
9229          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9230             <52>   DW_AT_decl_file   : 1
9231             <53>   DW_AT_decl_line   : 6
9232             <54>   DW_AT_import      : <0x75>
9233          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9234             <59>   DW_AT_name        : B
9235             <5b>   DW_AT_decl_file   : 1
9236             <5c>   DW_AT_decl_line   : 2
9237             <5d>   DW_AT_type        : <0x6e>
9238         ...
9239          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9240             <76>   DW_AT_byte_size   : 4
9241             <77>   DW_AT_encoding    : 5        (signed)
9242
9243         imports the wrong die ( 0x75 instead of 0x58 ).
9244         This case will be ignored until the gcc bug is fixed.  */
9245       return;
9246     }
9247
9248   /* Figure out the local name after import.  */
9249   import_alias = dwarf2_name (die, cu);
9250
9251   /* Figure out where the statement is being imported to.  */
9252   import_prefix = determine_prefix (die, cu);
9253
9254   /* Figure out what the scope of the imported die is and prepend it
9255      to the name of the imported die.  */
9256   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9257
9258   if (imported_die->tag != DW_TAG_namespace
9259       && imported_die->tag != DW_TAG_module)
9260     {
9261       imported_declaration = imported_name;
9262       canonical_name = imported_name_prefix;
9263     }
9264   else if (strlen (imported_name_prefix) > 0)
9265     canonical_name = obconcat (&objfile->objfile_obstack,
9266                                imported_name_prefix,
9267                                (cu->language == language_d ? "." : "::"),
9268                                imported_name, (char *) NULL);
9269   else
9270     canonical_name = imported_name;
9271
9272   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9273     for (child_die = die->child; child_die && child_die->tag;
9274          child_die = sibling_die (child_die))
9275       {
9276         /* DWARF-4: A Fortran use statement with a “rename list” may be
9277            represented by an imported module entry with an import attribute
9278            referring to the module and owned entries corresponding to those
9279            entities that are renamed as part of being imported.  */
9280
9281         if (child_die->tag != DW_TAG_imported_declaration)
9282           {
9283             complaint (&symfile_complaints,
9284                        _("child DW_TAG_imported_declaration expected "
9285                          "- DIE at 0x%x [in module %s]"),
9286                        to_underlying (child_die->sect_off), objfile_name (objfile));
9287             continue;
9288           }
9289
9290         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9291         if (import_attr == NULL)
9292           {
9293             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9294                        dwarf_tag_name (child_die->tag));
9295             continue;
9296           }
9297
9298         imported_cu = cu;
9299         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9300                                               &imported_cu);
9301         imported_name = dwarf2_name (imported_die, imported_cu);
9302         if (imported_name == NULL)
9303           {
9304             complaint (&symfile_complaints,
9305                        _("child DW_TAG_imported_declaration has unknown "
9306                          "imported name - DIE at 0x%x [in module %s]"),
9307                        to_underlying (child_die->sect_off), objfile_name (objfile));
9308             continue;
9309           }
9310
9311         excludes.push_back (imported_name);
9312
9313         process_die (child_die, cu);
9314       }
9315
9316   add_using_directive (using_directives (cu->language),
9317                        import_prefix,
9318                        canonical_name,
9319                        import_alias,
9320                        imported_declaration,
9321                        excludes,
9322                        0,
9323                        &objfile->objfile_obstack);
9324 }
9325
9326 /* ICC<14 does not output the required DW_AT_declaration on incomplete
9327    types, but gives them a size of zero.  Starting with version 14,
9328    ICC is compatible with GCC.  */
9329
9330 static int
9331 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
9332 {
9333   if (!cu->checked_producer)
9334     check_producer (cu);
9335
9336   return cu->producer_is_icc_lt_14;
9337 }
9338
9339 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9340    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9341    this, it was first present in GCC release 4.3.0.  */
9342
9343 static int
9344 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9345 {
9346   if (!cu->checked_producer)
9347     check_producer (cu);
9348
9349   return cu->producer_is_gcc_lt_4_3;
9350 }
9351
9352 static file_and_directory
9353 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9354 {
9355   file_and_directory res;
9356
9357   /* Find the filename.  Do not use dwarf2_name here, since the filename
9358      is not a source language identifier.  */
9359   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9360   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9361
9362   if (res.comp_dir == NULL
9363       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9364       && IS_ABSOLUTE_PATH (res.name))
9365     {
9366       res.comp_dir_storage = ldirname (res.name);
9367       if (!res.comp_dir_storage.empty ())
9368         res.comp_dir = res.comp_dir_storage.c_str ();
9369     }
9370   if (res.comp_dir != NULL)
9371     {
9372       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9373          directory, get rid of it.  */
9374       const char *cp = strchr (res.comp_dir, ':');
9375
9376       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9377         res.comp_dir = cp + 1;
9378     }
9379
9380   if (res.name == NULL)
9381     res.name = "<unknown>";
9382
9383   return res;
9384 }
9385
9386 /* Handle DW_AT_stmt_list for a compilation unit.
9387    DIE is the DW_TAG_compile_unit die for CU.
9388    COMP_DIR is the compilation directory.  LOWPC is passed to
9389    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9390
9391 static void
9392 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9393                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9394 {
9395   struct objfile *objfile = dwarf2_per_objfile->objfile;
9396   struct attribute *attr;
9397   struct line_header line_header_local;
9398   hashval_t line_header_local_hash;
9399   unsigned u;
9400   void **slot;
9401   int decode_mapping;
9402
9403   gdb_assert (! cu->per_cu->is_debug_types);
9404
9405   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9406   if (attr == NULL)
9407     return;
9408
9409   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9410
9411   /* The line header hash table is only created if needed (it exists to
9412      prevent redundant reading of the line table for partial_units).
9413      If we're given a partial_unit, we'll need it.  If we're given a
9414      compile_unit, then use the line header hash table if it's already
9415      created, but don't create one just yet.  */
9416
9417   if (dwarf2_per_objfile->line_header_hash == NULL
9418       && die->tag == DW_TAG_partial_unit)
9419     {
9420       dwarf2_per_objfile->line_header_hash
9421         = htab_create_alloc_ex (127, line_header_hash_voidp,
9422                                 line_header_eq_voidp,
9423                                 free_line_header_voidp,
9424                                 &objfile->objfile_obstack,
9425                                 hashtab_obstack_allocate,
9426                                 dummy_obstack_deallocate);
9427     }
9428
9429   line_header_local.sect_off = line_offset;
9430   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9431   line_header_local_hash = line_header_hash (&line_header_local);
9432   if (dwarf2_per_objfile->line_header_hash != NULL)
9433     {
9434       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9435                                        &line_header_local,
9436                                        line_header_local_hash, NO_INSERT);
9437
9438       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9439          is not present in *SLOT (since if there is something in *SLOT then
9440          it will be for a partial_unit).  */
9441       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9442         {
9443           gdb_assert (*slot != NULL);
9444           cu->line_header = (struct line_header *) *slot;
9445           return;
9446         }
9447     }
9448
9449   /* dwarf_decode_line_header does not yet provide sufficient information.
9450      We always have to call also dwarf_decode_lines for it.  */
9451   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9452   if (lh == NULL)
9453     return;
9454
9455   cu->line_header = lh.release ();
9456   cu->line_header_die_owner = die;
9457
9458   if (dwarf2_per_objfile->line_header_hash == NULL)
9459     slot = NULL;
9460   else
9461     {
9462       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9463                                        &line_header_local,
9464                                        line_header_local_hash, INSERT);
9465       gdb_assert (slot != NULL);
9466     }
9467   if (slot != NULL && *slot == NULL)
9468     {
9469       /* This newly decoded line number information unit will be owned
9470          by line_header_hash hash table.  */
9471       *slot = cu->line_header;
9472       cu->line_header_die_owner = NULL;
9473     }
9474   else
9475     {
9476       /* We cannot free any current entry in (*slot) as that struct line_header
9477          may be already used by multiple CUs.  Create only temporary decoded
9478          line_header for this CU - it may happen at most once for each line
9479          number information unit.  And if we're not using line_header_hash
9480          then this is what we want as well.  */
9481       gdb_assert (die->tag != DW_TAG_partial_unit);
9482     }
9483   decode_mapping = (die->tag != DW_TAG_partial_unit);
9484   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9485                       decode_mapping);
9486
9487 }
9488
9489 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9490
9491 static void
9492 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9493 {
9494   struct objfile *objfile = dwarf2_per_objfile->objfile;
9495   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9496   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9497   CORE_ADDR highpc = ((CORE_ADDR) 0);
9498   struct attribute *attr;
9499   struct die_info *child_die;
9500   CORE_ADDR baseaddr;
9501
9502   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9503
9504   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9505
9506   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9507      from finish_block.  */
9508   if (lowpc == ((CORE_ADDR) -1))
9509     lowpc = highpc;
9510   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9511
9512   file_and_directory fnd = find_file_and_directory (die, cu);
9513
9514   prepare_one_comp_unit (cu, die, cu->language);
9515
9516   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9517      standardised yet.  As a workaround for the language detection we fall
9518      back to the DW_AT_producer string.  */
9519   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9520     cu->language = language_opencl;
9521
9522   /* Similar hack for Go.  */
9523   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9524     set_cu_language (DW_LANG_Go, cu);
9525
9526   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9527
9528   /* Decode line number information if present.  We do this before
9529      processing child DIEs, so that the line header table is available
9530      for DW_AT_decl_file.  */
9531   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9532
9533   /* Process all dies in compilation unit.  */
9534   if (die->child != NULL)
9535     {
9536       child_die = die->child;
9537       while (child_die && child_die->tag)
9538         {
9539           process_die (child_die, cu);
9540           child_die = sibling_die (child_die);
9541         }
9542     }
9543
9544   /* Decode macro information, if present.  Dwarf 2 macro information
9545      refers to information in the line number info statement program
9546      header, so we can only read it if we've read the header
9547      successfully.  */
9548   attr = dwarf2_attr (die, DW_AT_macros, cu);
9549   if (attr == NULL)
9550     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9551   if (attr && cu->line_header)
9552     {
9553       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9554         complaint (&symfile_complaints,
9555                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9556
9557       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9558     }
9559   else
9560     {
9561       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9562       if (attr && cu->line_header)
9563         {
9564           unsigned int macro_offset = DW_UNSND (attr);
9565
9566           dwarf_decode_macros (cu, macro_offset, 0);
9567         }
9568     }
9569 }
9570
9571 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9572    Create the set of symtabs used by this TU, or if this TU is sharing
9573    symtabs with another TU and the symtabs have already been created
9574    then restore those symtabs in the line header.
9575    We don't need the pc/line-number mapping for type units.  */
9576
9577 static void
9578 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9579 {
9580   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9581   struct type_unit_group *tu_group;
9582   int first_time;
9583   struct attribute *attr;
9584   unsigned int i;
9585   struct signatured_type *sig_type;
9586
9587   gdb_assert (per_cu->is_debug_types);
9588   sig_type = (struct signatured_type *) per_cu;
9589
9590   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9591
9592   /* If we're using .gdb_index (includes -readnow) then
9593      per_cu->type_unit_group may not have been set up yet.  */
9594   if (sig_type->type_unit_group == NULL)
9595     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9596   tu_group = sig_type->type_unit_group;
9597
9598   /* If we've already processed this stmt_list there's no real need to
9599      do it again, we could fake it and just recreate the part we need
9600      (file name,index -> symtab mapping).  If data shows this optimization
9601      is useful we can do it then.  */
9602   first_time = tu_group->compunit_symtab == NULL;
9603
9604   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9605      debug info.  */
9606   line_header_up lh;
9607   if (attr != NULL)
9608     {
9609       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9610       lh = dwarf_decode_line_header (line_offset, cu);
9611     }
9612   if (lh == NULL)
9613     {
9614       if (first_time)
9615         dwarf2_start_symtab (cu, "", NULL, 0);
9616       else
9617         {
9618           gdb_assert (tu_group->symtabs == NULL);
9619           restart_symtab (tu_group->compunit_symtab, "", 0);
9620         }
9621       return;
9622     }
9623
9624   cu->line_header = lh.release ();
9625   cu->line_header_die_owner = die;
9626
9627   if (first_time)
9628     {
9629       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9630
9631       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9632          still initializing it, and our caller (a few levels up)
9633          process_full_type_unit still needs to know if this is the first
9634          time.  */
9635
9636       tu_group->num_symtabs = cu->line_header->file_names.size ();
9637       tu_group->symtabs = XNEWVEC (struct symtab *,
9638                                    cu->line_header->file_names.size ());
9639
9640       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9641         {
9642           file_entry &fe = cu->line_header->file_names[i];
9643
9644           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9645
9646           if (current_subfile->symtab == NULL)
9647             {
9648               /* NOTE: start_subfile will recognize when it's been
9649                  passed a file it has already seen.  So we can't
9650                  assume there's a simple mapping from
9651                  cu->line_header->file_names to subfiles, plus
9652                  cu->line_header->file_names may contain dups.  */
9653               current_subfile->symtab
9654                 = allocate_symtab (cust, current_subfile->name);
9655             }
9656
9657           fe.symtab = current_subfile->symtab;
9658           tu_group->symtabs[i] = fe.symtab;
9659         }
9660     }
9661   else
9662     {
9663       restart_symtab (tu_group->compunit_symtab, "", 0);
9664
9665       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9666         {
9667           file_entry &fe = cu->line_header->file_names[i];
9668
9669           fe.symtab = tu_group->symtabs[i];
9670         }
9671     }
9672
9673   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9674      so they don't have a "real" (so to speak) symtab anyway.
9675      There is later code that will assign the main symtab to all symbols
9676      that don't have one.  We need to handle the case of a symbol with a
9677      missing symtab (DW_AT_decl_file) anyway.  */
9678 }
9679
9680 /* Process DW_TAG_type_unit.
9681    For TUs we want to skip the first top level sibling if it's not the
9682    actual type being defined by this TU.  In this case the first top
9683    level sibling is there to provide context only.  */
9684
9685 static void
9686 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9687 {
9688   struct die_info *child_die;
9689
9690   prepare_one_comp_unit (cu, die, language_minimal);
9691
9692   /* Initialize (or reinitialize) the machinery for building symtabs.
9693      We do this before processing child DIEs, so that the line header table
9694      is available for DW_AT_decl_file.  */
9695   setup_type_unit_groups (die, cu);
9696
9697   if (die->child != NULL)
9698     {
9699       child_die = die->child;
9700       while (child_die && child_die->tag)
9701         {
9702           process_die (child_die, cu);
9703           child_die = sibling_die (child_die);
9704         }
9705     }
9706 }
9707 \f
9708 /* DWO/DWP files.
9709
9710    http://gcc.gnu.org/wiki/DebugFission
9711    http://gcc.gnu.org/wiki/DebugFissionDWP
9712
9713    To simplify handling of both DWO files ("object" files with the DWARF info)
9714    and DWP files (a file with the DWOs packaged up into one file), we treat
9715    DWP files as having a collection of virtual DWO files.  */
9716
9717 static hashval_t
9718 hash_dwo_file (const void *item)
9719 {
9720   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9721   hashval_t hash;
9722
9723   hash = htab_hash_string (dwo_file->dwo_name);
9724   if (dwo_file->comp_dir != NULL)
9725     hash += htab_hash_string (dwo_file->comp_dir);
9726   return hash;
9727 }
9728
9729 static int
9730 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9731 {
9732   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9733   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9734
9735   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9736     return 0;
9737   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9738     return lhs->comp_dir == rhs->comp_dir;
9739   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9740 }
9741
9742 /* Allocate a hash table for DWO files.  */
9743
9744 static htab_t
9745 allocate_dwo_file_hash_table (void)
9746 {
9747   struct objfile *objfile = dwarf2_per_objfile->objfile;
9748
9749   return htab_create_alloc_ex (41,
9750                                hash_dwo_file,
9751                                eq_dwo_file,
9752                                NULL,
9753                                &objfile->objfile_obstack,
9754                                hashtab_obstack_allocate,
9755                                dummy_obstack_deallocate);
9756 }
9757
9758 /* Lookup DWO file DWO_NAME.  */
9759
9760 static void **
9761 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9762 {
9763   struct dwo_file find_entry;
9764   void **slot;
9765
9766   if (dwarf2_per_objfile->dwo_files == NULL)
9767     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9768
9769   memset (&find_entry, 0, sizeof (find_entry));
9770   find_entry.dwo_name = dwo_name;
9771   find_entry.comp_dir = comp_dir;
9772   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9773
9774   return slot;
9775 }
9776
9777 static hashval_t
9778 hash_dwo_unit (const void *item)
9779 {
9780   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9781
9782   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9783   return dwo_unit->signature;
9784 }
9785
9786 static int
9787 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9788 {
9789   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9790   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9791
9792   /* The signature is assumed to be unique within the DWO file.
9793      So while object file CU dwo_id's always have the value zero,
9794      that's OK, assuming each object file DWO file has only one CU,
9795      and that's the rule for now.  */
9796   return lhs->signature == rhs->signature;
9797 }
9798
9799 /* Allocate a hash table for DWO CUs,TUs.
9800    There is one of these tables for each of CUs,TUs for each DWO file.  */
9801
9802 static htab_t
9803 allocate_dwo_unit_table (struct objfile *objfile)
9804 {
9805   /* Start out with a pretty small number.
9806      Generally DWO files contain only one CU and maybe some TUs.  */
9807   return htab_create_alloc_ex (3,
9808                                hash_dwo_unit,
9809                                eq_dwo_unit,
9810                                NULL,
9811                                &objfile->objfile_obstack,
9812                                hashtab_obstack_allocate,
9813                                dummy_obstack_deallocate);
9814 }
9815
9816 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9817
9818 struct create_dwo_cu_data
9819 {
9820   struct dwo_file *dwo_file;
9821   struct dwo_unit dwo_unit;
9822 };
9823
9824 /* die_reader_func for create_dwo_cu.  */
9825
9826 static void
9827 create_dwo_cu_reader (const struct die_reader_specs *reader,
9828                       const gdb_byte *info_ptr,
9829                       struct die_info *comp_unit_die,
9830                       int has_children,
9831                       void *datap)
9832 {
9833   struct dwarf2_cu *cu = reader->cu;
9834   sect_offset sect_off = cu->per_cu->sect_off;
9835   struct dwarf2_section_info *section = cu->per_cu->section;
9836   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9837   struct dwo_file *dwo_file = data->dwo_file;
9838   struct dwo_unit *dwo_unit = &data->dwo_unit;
9839   struct attribute *attr;
9840
9841   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9842   if (attr == NULL)
9843     {
9844       complaint (&symfile_complaints,
9845                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9846                    " its dwo_id [in module %s]"),
9847                  to_underlying (sect_off), dwo_file->dwo_name);
9848       return;
9849     }
9850
9851   dwo_unit->dwo_file = dwo_file;
9852   dwo_unit->signature = DW_UNSND (attr);
9853   dwo_unit->section = section;
9854   dwo_unit->sect_off = sect_off;
9855   dwo_unit->length = cu->per_cu->length;
9856
9857   if (dwarf_read_debug)
9858     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9859                         to_underlying (sect_off),
9860                         hex_string (dwo_unit->signature));
9861 }
9862
9863 /* Create the dwo_units for the CUs in a DWO_FILE.
9864    Note: This function processes DWO files only, not DWP files.  */
9865
9866 static void
9867 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9868                        htab_t &cus_htab)
9869 {
9870   struct objfile *objfile = dwarf2_per_objfile->objfile;
9871   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9872   const gdb_byte *info_ptr, *end_ptr;
9873
9874   dwarf2_read_section (objfile, &section);
9875   info_ptr = section.buffer;
9876
9877   if (info_ptr == NULL)
9878     return;
9879
9880   if (dwarf_read_debug)
9881     {
9882       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9883                           get_section_name (&section),
9884                           get_section_file_name (&section));
9885     }
9886
9887   end_ptr = info_ptr + section.size;
9888   while (info_ptr < end_ptr)
9889     {
9890       struct dwarf2_per_cu_data per_cu;
9891       struct create_dwo_cu_data create_dwo_cu_data;
9892       struct dwo_unit *dwo_unit;
9893       void **slot;
9894       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9895
9896       memset (&create_dwo_cu_data.dwo_unit, 0,
9897               sizeof (create_dwo_cu_data.dwo_unit));
9898       memset (&per_cu, 0, sizeof (per_cu));
9899       per_cu.objfile = objfile;
9900       per_cu.is_debug_types = 0;
9901       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9902       per_cu.section = &section;
9903       create_dwo_cu_data.dwo_file = &dwo_file;
9904
9905       init_cutu_and_read_dies_no_follow (
9906           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9907       info_ptr += per_cu.length;
9908
9909       // If the unit could not be parsed, skip it.
9910       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9911         continue;
9912
9913       if (cus_htab == NULL)
9914         cus_htab = allocate_dwo_unit_table (objfile);
9915
9916       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9917       *dwo_unit = create_dwo_cu_data.dwo_unit;
9918       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9919       gdb_assert (slot != NULL);
9920       if (*slot != NULL)
9921         {
9922           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9923           sect_offset dup_sect_off = dup_cu->sect_off;
9924
9925           complaint (&symfile_complaints,
9926                      _("debug cu entry at offset 0x%x is duplicate to"
9927                        " the entry at offset 0x%x, signature %s"),
9928                      to_underlying (sect_off), to_underlying (dup_sect_off),
9929                      hex_string (dwo_unit->signature));
9930         }
9931       *slot = (void *)dwo_unit;
9932     }
9933 }
9934
9935 /* DWP file .debug_{cu,tu}_index section format:
9936    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9937
9938    DWP Version 1:
9939
9940    Both index sections have the same format, and serve to map a 64-bit
9941    signature to a set of section numbers.  Each section begins with a header,
9942    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9943    indexes, and a pool of 32-bit section numbers.  The index sections will be
9944    aligned at 8-byte boundaries in the file.
9945
9946    The index section header consists of:
9947
9948     V, 32 bit version number
9949     -, 32 bits unused
9950     N, 32 bit number of compilation units or type units in the index
9951     M, 32 bit number of slots in the hash table
9952
9953    Numbers are recorded using the byte order of the application binary.
9954
9955    The hash table begins at offset 16 in the section, and consists of an array
9956    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9957    order of the application binary).  Unused slots in the hash table are 0.
9958    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9959
9960    The parallel table begins immediately after the hash table
9961    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9962    array of 32-bit indexes (using the byte order of the application binary),
9963    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9964    table contains a 32-bit index into the pool of section numbers.  For unused
9965    hash table slots, the corresponding entry in the parallel table will be 0.
9966
9967    The pool of section numbers begins immediately following the hash table
9968    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9969    section numbers consists of an array of 32-bit words (using the byte order
9970    of the application binary).  Each item in the array is indexed starting
9971    from 0.  The hash table entry provides the index of the first section
9972    number in the set.  Additional section numbers in the set follow, and the
9973    set is terminated by a 0 entry (section number 0 is not used in ELF).
9974
9975    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9976    section must be the first entry in the set, and the .debug_abbrev.dwo must
9977    be the second entry. Other members of the set may follow in any order.
9978
9979    ---
9980
9981    DWP Version 2:
9982
9983    DWP Version 2 combines all the .debug_info, etc. sections into one,
9984    and the entries in the index tables are now offsets into these sections.
9985    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9986    section.
9987
9988    Index Section Contents:
9989     Header
9990     Hash Table of Signatures   dwp_hash_table.hash_table
9991     Parallel Table of Indices  dwp_hash_table.unit_table
9992     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9993     Table of Section Sizes     dwp_hash_table.v2.sizes
9994
9995    The index section header consists of:
9996
9997     V, 32 bit version number
9998     L, 32 bit number of columns in the table of section offsets
9999     N, 32 bit number of compilation units or type units in the index
10000     M, 32 bit number of slots in the hash table
10001
10002    Numbers are recorded using the byte order of the application binary.
10003
10004    The hash table has the same format as version 1.
10005    The parallel table of indices has the same format as version 1,
10006    except that the entries are origin-1 indices into the table of sections
10007    offsets and the table of section sizes.
10008
10009    The table of offsets begins immediately following the parallel table
10010    (at offset 16 + 12 * M from the beginning of the section).  The table is
10011    a two-dimensional array of 32-bit words (using the byte order of the
10012    application binary), with L columns and N+1 rows, in row-major order.
10013    Each row in the array is indexed starting from 0.  The first row provides
10014    a key to the remaining rows: each column in this row provides an identifier
10015    for a debug section, and the offsets in the same column of subsequent rows
10016    refer to that section.  The section identifiers are:
10017
10018     DW_SECT_INFO         1  .debug_info.dwo
10019     DW_SECT_TYPES        2  .debug_types.dwo
10020     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10021     DW_SECT_LINE         4  .debug_line.dwo
10022     DW_SECT_LOC          5  .debug_loc.dwo
10023     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10024     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10025     DW_SECT_MACRO        8  .debug_macro.dwo
10026
10027    The offsets provided by the CU and TU index sections are the base offsets
10028    for the contributions made by each CU or TU to the corresponding section
10029    in the package file.  Each CU and TU header contains an abbrev_offset
10030    field, used to find the abbreviations table for that CU or TU within the
10031    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10032    be interpreted as relative to the base offset given in the index section.
10033    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10034    should be interpreted as relative to the base offset for .debug_line.dwo,
10035    and offsets into other debug sections obtained from DWARF attributes should
10036    also be interpreted as relative to the corresponding base offset.
10037
10038    The table of sizes begins immediately following the table of offsets.
10039    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10040    with L columns and N rows, in row-major order.  Each row in the array is
10041    indexed starting from 1 (row 0 is shared by the two tables).
10042
10043    ---
10044
10045    Hash table lookup is handled the same in version 1 and 2:
10046
10047    We assume that N and M will not exceed 2^32 - 1.
10048    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10049
10050    Given a 64-bit compilation unit signature or a type signature S, an entry
10051    in the hash table is located as follows:
10052
10053    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10054       the low-order k bits all set to 1.
10055
10056    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10057
10058    3) If the hash table entry at index H matches the signature, use that
10059       entry.  If the hash table entry at index H is unused (all zeroes),
10060       terminate the search: the signature is not present in the table.
10061
10062    4) Let H = (H + H') modulo M. Repeat at Step 3.
10063
10064    Because M > N and H' and M are relatively prime, the search is guaranteed
10065    to stop at an unused slot or find the match.  */
10066
10067 /* Create a hash table to map DWO IDs to their CU/TU entry in
10068    .debug_{info,types}.dwo in DWP_FILE.
10069    Returns NULL if there isn't one.
10070    Note: This function processes DWP files only, not DWO files.  */
10071
10072 static struct dwp_hash_table *
10073 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10074 {
10075   struct objfile *objfile = dwarf2_per_objfile->objfile;
10076   bfd *dbfd = dwp_file->dbfd;
10077   const gdb_byte *index_ptr, *index_end;
10078   struct dwarf2_section_info *index;
10079   uint32_t version, nr_columns, nr_units, nr_slots;
10080   struct dwp_hash_table *htab;
10081
10082   if (is_debug_types)
10083     index = &dwp_file->sections.tu_index;
10084   else
10085     index = &dwp_file->sections.cu_index;
10086
10087   if (dwarf2_section_empty_p (index))
10088     return NULL;
10089   dwarf2_read_section (objfile, index);
10090
10091   index_ptr = index->buffer;
10092   index_end = index_ptr + index->size;
10093
10094   version = read_4_bytes (dbfd, index_ptr);
10095   index_ptr += 4;
10096   if (version == 2)
10097     nr_columns = read_4_bytes (dbfd, index_ptr);
10098   else
10099     nr_columns = 0;
10100   index_ptr += 4;
10101   nr_units = read_4_bytes (dbfd, index_ptr);
10102   index_ptr += 4;
10103   nr_slots = read_4_bytes (dbfd, index_ptr);
10104   index_ptr += 4;
10105
10106   if (version != 1 && version != 2)
10107     {
10108       error (_("Dwarf Error: unsupported DWP file version (%s)"
10109                " [in module %s]"),
10110              pulongest (version), dwp_file->name);
10111     }
10112   if (nr_slots != (nr_slots & -nr_slots))
10113     {
10114       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10115                " is not power of 2 [in module %s]"),
10116              pulongest (nr_slots), dwp_file->name);
10117     }
10118
10119   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10120   htab->version = version;
10121   htab->nr_columns = nr_columns;
10122   htab->nr_units = nr_units;
10123   htab->nr_slots = nr_slots;
10124   htab->hash_table = index_ptr;
10125   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10126
10127   /* Exit early if the table is empty.  */
10128   if (nr_slots == 0 || nr_units == 0
10129       || (version == 2 && nr_columns == 0))
10130     {
10131       /* All must be zero.  */
10132       if (nr_slots != 0 || nr_units != 0
10133           || (version == 2 && nr_columns != 0))
10134         {
10135           complaint (&symfile_complaints,
10136                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10137                        " all zero [in modules %s]"),
10138                      dwp_file->name);
10139         }
10140       return htab;
10141     }
10142
10143   if (version == 1)
10144     {
10145       htab->section_pool.v1.indices =
10146         htab->unit_table + sizeof (uint32_t) * nr_slots;
10147       /* It's harder to decide whether the section is too small in v1.
10148          V1 is deprecated anyway so we punt.  */
10149     }
10150   else
10151     {
10152       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10153       int *ids = htab->section_pool.v2.section_ids;
10154       /* Reverse map for error checking.  */
10155       int ids_seen[DW_SECT_MAX + 1];
10156       int i;
10157
10158       if (nr_columns < 2)
10159         {
10160           error (_("Dwarf Error: bad DWP hash table, too few columns"
10161                    " in section table [in module %s]"),
10162                  dwp_file->name);
10163         }
10164       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10165         {
10166           error (_("Dwarf Error: bad DWP hash table, too many columns"
10167                    " in section table [in module %s]"),
10168                  dwp_file->name);
10169         }
10170       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10171       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10172       for (i = 0; i < nr_columns; ++i)
10173         {
10174           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10175
10176           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10177             {
10178               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10179                        " in section table [in module %s]"),
10180                      id, dwp_file->name);
10181             }
10182           if (ids_seen[id] != -1)
10183             {
10184               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10185                        " id %d in section table [in module %s]"),
10186                      id, dwp_file->name);
10187             }
10188           ids_seen[id] = i;
10189           ids[i] = id;
10190         }
10191       /* Must have exactly one info or types section.  */
10192       if (((ids_seen[DW_SECT_INFO] != -1)
10193            + (ids_seen[DW_SECT_TYPES] != -1))
10194           != 1)
10195         {
10196           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10197                    " DWO info/types section [in module %s]"),
10198                  dwp_file->name);
10199         }
10200       /* Must have an abbrev section.  */
10201       if (ids_seen[DW_SECT_ABBREV] == -1)
10202         {
10203           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10204                    " section [in module %s]"),
10205                  dwp_file->name);
10206         }
10207       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10208       htab->section_pool.v2.sizes =
10209         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10210                                          * nr_units * nr_columns);
10211       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10212                                           * nr_units * nr_columns))
10213           > index_end)
10214         {
10215           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10216                    " [in module %s]"),
10217                  dwp_file->name);
10218         }
10219     }
10220
10221   return htab;
10222 }
10223
10224 /* Update SECTIONS with the data from SECTP.
10225
10226    This function is like the other "locate" section routines that are
10227    passed to bfd_map_over_sections, but in this context the sections to
10228    read comes from the DWP V1 hash table, not the full ELF section table.
10229
10230    The result is non-zero for success, or zero if an error was found.  */
10231
10232 static int
10233 locate_v1_virtual_dwo_sections (asection *sectp,
10234                                 struct virtual_v1_dwo_sections *sections)
10235 {
10236   const struct dwop_section_names *names = &dwop_section_names;
10237
10238   if (section_is_p (sectp->name, &names->abbrev_dwo))
10239     {
10240       /* There can be only one.  */
10241       if (sections->abbrev.s.section != NULL)
10242         return 0;
10243       sections->abbrev.s.section = sectp;
10244       sections->abbrev.size = bfd_get_section_size (sectp);
10245     }
10246   else if (section_is_p (sectp->name, &names->info_dwo)
10247            || section_is_p (sectp->name, &names->types_dwo))
10248     {
10249       /* There can be only one.  */
10250       if (sections->info_or_types.s.section != NULL)
10251         return 0;
10252       sections->info_or_types.s.section = sectp;
10253       sections->info_or_types.size = bfd_get_section_size (sectp);
10254     }
10255   else if (section_is_p (sectp->name, &names->line_dwo))
10256     {
10257       /* There can be only one.  */
10258       if (sections->line.s.section != NULL)
10259         return 0;
10260       sections->line.s.section = sectp;
10261       sections->line.size = bfd_get_section_size (sectp);
10262     }
10263   else if (section_is_p (sectp->name, &names->loc_dwo))
10264     {
10265       /* There can be only one.  */
10266       if (sections->loc.s.section != NULL)
10267         return 0;
10268       sections->loc.s.section = sectp;
10269       sections->loc.size = bfd_get_section_size (sectp);
10270     }
10271   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10272     {
10273       /* There can be only one.  */
10274       if (sections->macinfo.s.section != NULL)
10275         return 0;
10276       sections->macinfo.s.section = sectp;
10277       sections->macinfo.size = bfd_get_section_size (sectp);
10278     }
10279   else if (section_is_p (sectp->name, &names->macro_dwo))
10280     {
10281       /* There can be only one.  */
10282       if (sections->macro.s.section != NULL)
10283         return 0;
10284       sections->macro.s.section = sectp;
10285       sections->macro.size = bfd_get_section_size (sectp);
10286     }
10287   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10288     {
10289       /* There can be only one.  */
10290       if (sections->str_offsets.s.section != NULL)
10291         return 0;
10292       sections->str_offsets.s.section = sectp;
10293       sections->str_offsets.size = bfd_get_section_size (sectp);
10294     }
10295   else
10296     {
10297       /* No other kind of section is valid.  */
10298       return 0;
10299     }
10300
10301   return 1;
10302 }
10303
10304 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10305    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10306    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10307    This is for DWP version 1 files.  */
10308
10309 static struct dwo_unit *
10310 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10311                            uint32_t unit_index,
10312                            const char *comp_dir,
10313                            ULONGEST signature, int is_debug_types)
10314 {
10315   struct objfile *objfile = dwarf2_per_objfile->objfile;
10316   const struct dwp_hash_table *dwp_htab =
10317     is_debug_types ? dwp_file->tus : dwp_file->cus;
10318   bfd *dbfd = dwp_file->dbfd;
10319   const char *kind = is_debug_types ? "TU" : "CU";
10320   struct dwo_file *dwo_file;
10321   struct dwo_unit *dwo_unit;
10322   struct virtual_v1_dwo_sections sections;
10323   void **dwo_file_slot;
10324   int i;
10325
10326   gdb_assert (dwp_file->version == 1);
10327
10328   if (dwarf_read_debug)
10329     {
10330       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10331                           kind,
10332                           pulongest (unit_index), hex_string (signature),
10333                           dwp_file->name);
10334     }
10335
10336   /* Fetch the sections of this DWO unit.
10337      Put a limit on the number of sections we look for so that bad data
10338      doesn't cause us to loop forever.  */
10339
10340 #define MAX_NR_V1_DWO_SECTIONS \
10341   (1 /* .debug_info or .debug_types */ \
10342    + 1 /* .debug_abbrev */ \
10343    + 1 /* .debug_line */ \
10344    + 1 /* .debug_loc */ \
10345    + 1 /* .debug_str_offsets */ \
10346    + 1 /* .debug_macro or .debug_macinfo */ \
10347    + 1 /* trailing zero */)
10348
10349   memset (&sections, 0, sizeof (sections));
10350
10351   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10352     {
10353       asection *sectp;
10354       uint32_t section_nr =
10355         read_4_bytes (dbfd,
10356                       dwp_htab->section_pool.v1.indices
10357                       + (unit_index + i) * sizeof (uint32_t));
10358
10359       if (section_nr == 0)
10360         break;
10361       if (section_nr >= dwp_file->num_sections)
10362         {
10363           error (_("Dwarf Error: bad DWP hash table, section number too large"
10364                    " [in module %s]"),
10365                  dwp_file->name);
10366         }
10367
10368       sectp = dwp_file->elf_sections[section_nr];
10369       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10370         {
10371           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10372                    " [in module %s]"),
10373                  dwp_file->name);
10374         }
10375     }
10376
10377   if (i < 2
10378       || dwarf2_section_empty_p (&sections.info_or_types)
10379       || dwarf2_section_empty_p (&sections.abbrev))
10380     {
10381       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10382                " [in module %s]"),
10383              dwp_file->name);
10384     }
10385   if (i == MAX_NR_V1_DWO_SECTIONS)
10386     {
10387       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10388                " [in module %s]"),
10389              dwp_file->name);
10390     }
10391
10392   /* It's easier for the rest of the code if we fake a struct dwo_file and
10393      have dwo_unit "live" in that.  At least for now.
10394
10395      The DWP file can be made up of a random collection of CUs and TUs.
10396      However, for each CU + set of TUs that came from the same original DWO
10397      file, we can combine them back into a virtual DWO file to save space
10398      (fewer struct dwo_file objects to allocate).  Remember that for really
10399      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10400
10401   std::string virtual_dwo_name =
10402     string_printf ("virtual-dwo/%d-%d-%d-%d",
10403                    get_section_id (&sections.abbrev),
10404                    get_section_id (&sections.line),
10405                    get_section_id (&sections.loc),
10406                    get_section_id (&sections.str_offsets));
10407   /* Can we use an existing virtual DWO file?  */
10408   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10409   /* Create one if necessary.  */
10410   if (*dwo_file_slot == NULL)
10411     {
10412       if (dwarf_read_debug)
10413         {
10414           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10415                               virtual_dwo_name.c_str ());
10416         }
10417       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10418       dwo_file->dwo_name
10419         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10420                                         virtual_dwo_name.c_str (),
10421                                         virtual_dwo_name.size ());
10422       dwo_file->comp_dir = comp_dir;
10423       dwo_file->sections.abbrev = sections.abbrev;
10424       dwo_file->sections.line = sections.line;
10425       dwo_file->sections.loc = sections.loc;
10426       dwo_file->sections.macinfo = sections.macinfo;
10427       dwo_file->sections.macro = sections.macro;
10428       dwo_file->sections.str_offsets = sections.str_offsets;
10429       /* The "str" section is global to the entire DWP file.  */
10430       dwo_file->sections.str = dwp_file->sections.str;
10431       /* The info or types section is assigned below to dwo_unit,
10432          there's no need to record it in dwo_file.
10433          Also, we can't simply record type sections in dwo_file because
10434          we record a pointer into the vector in dwo_unit.  As we collect more
10435          types we'll grow the vector and eventually have to reallocate space
10436          for it, invalidating all copies of pointers into the previous
10437          contents.  */
10438       *dwo_file_slot = dwo_file;
10439     }
10440   else
10441     {
10442       if (dwarf_read_debug)
10443         {
10444           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10445                               virtual_dwo_name.c_str ());
10446         }
10447       dwo_file = (struct dwo_file *) *dwo_file_slot;
10448     }
10449
10450   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10451   dwo_unit->dwo_file = dwo_file;
10452   dwo_unit->signature = signature;
10453   dwo_unit->section =
10454     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10455   *dwo_unit->section = sections.info_or_types;
10456   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10457
10458   return dwo_unit;
10459 }
10460
10461 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10462    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10463    piece within that section used by a TU/CU, return a virtual section
10464    of just that piece.  */
10465
10466 static struct dwarf2_section_info
10467 create_dwp_v2_section (struct dwarf2_section_info *section,
10468                        bfd_size_type offset, bfd_size_type size)
10469 {
10470   struct dwarf2_section_info result;
10471   asection *sectp;
10472
10473   gdb_assert (section != NULL);
10474   gdb_assert (!section->is_virtual);
10475
10476   memset (&result, 0, sizeof (result));
10477   result.s.containing_section = section;
10478   result.is_virtual = 1;
10479
10480   if (size == 0)
10481     return result;
10482
10483   sectp = get_section_bfd_section (section);
10484
10485   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10486      bounds of the real section.  This is a pretty-rare event, so just
10487      flag an error (easier) instead of a warning and trying to cope.  */
10488   if (sectp == NULL
10489       || offset + size > bfd_get_section_size (sectp))
10490     {
10491       bfd *abfd = sectp->owner;
10492
10493       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10494                " in section %s [in module %s]"),
10495              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10496              objfile_name (dwarf2_per_objfile->objfile));
10497     }
10498
10499   result.virtual_offset = offset;
10500   result.size = size;
10501   return result;
10502 }
10503
10504 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10505    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10506    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10507    This is for DWP version 2 files.  */
10508
10509 static struct dwo_unit *
10510 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10511                            uint32_t unit_index,
10512                            const char *comp_dir,
10513                            ULONGEST signature, int is_debug_types)
10514 {
10515   struct objfile *objfile = dwarf2_per_objfile->objfile;
10516   const struct dwp_hash_table *dwp_htab =
10517     is_debug_types ? dwp_file->tus : dwp_file->cus;
10518   bfd *dbfd = dwp_file->dbfd;
10519   const char *kind = is_debug_types ? "TU" : "CU";
10520   struct dwo_file *dwo_file;
10521   struct dwo_unit *dwo_unit;
10522   struct virtual_v2_dwo_sections sections;
10523   void **dwo_file_slot;
10524   int i;
10525
10526   gdb_assert (dwp_file->version == 2);
10527
10528   if (dwarf_read_debug)
10529     {
10530       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10531                           kind,
10532                           pulongest (unit_index), hex_string (signature),
10533                           dwp_file->name);
10534     }
10535
10536   /* Fetch the section offsets of this DWO unit.  */
10537
10538   memset (&sections, 0, sizeof (sections));
10539
10540   for (i = 0; i < dwp_htab->nr_columns; ++i)
10541     {
10542       uint32_t offset = read_4_bytes (dbfd,
10543                                       dwp_htab->section_pool.v2.offsets
10544                                       + (((unit_index - 1) * dwp_htab->nr_columns
10545                                           + i)
10546                                          * sizeof (uint32_t)));
10547       uint32_t size = read_4_bytes (dbfd,
10548                                     dwp_htab->section_pool.v2.sizes
10549                                     + (((unit_index - 1) * dwp_htab->nr_columns
10550                                         + i)
10551                                        * sizeof (uint32_t)));
10552
10553       switch (dwp_htab->section_pool.v2.section_ids[i])
10554         {
10555         case DW_SECT_INFO:
10556         case DW_SECT_TYPES:
10557           sections.info_or_types_offset = offset;
10558           sections.info_or_types_size = size;
10559           break;
10560         case DW_SECT_ABBREV:
10561           sections.abbrev_offset = offset;
10562           sections.abbrev_size = size;
10563           break;
10564         case DW_SECT_LINE:
10565           sections.line_offset = offset;
10566           sections.line_size = size;
10567           break;
10568         case DW_SECT_LOC:
10569           sections.loc_offset = offset;
10570           sections.loc_size = size;
10571           break;
10572         case DW_SECT_STR_OFFSETS:
10573           sections.str_offsets_offset = offset;
10574           sections.str_offsets_size = size;
10575           break;
10576         case DW_SECT_MACINFO:
10577           sections.macinfo_offset = offset;
10578           sections.macinfo_size = size;
10579           break;
10580         case DW_SECT_MACRO:
10581           sections.macro_offset = offset;
10582           sections.macro_size = size;
10583           break;
10584         }
10585     }
10586
10587   /* It's easier for the rest of the code if we fake a struct dwo_file and
10588      have dwo_unit "live" in that.  At least for now.
10589
10590      The DWP file can be made up of a random collection of CUs and TUs.
10591      However, for each CU + set of TUs that came from the same original DWO
10592      file, we can combine them back into a virtual DWO file to save space
10593      (fewer struct dwo_file objects to allocate).  Remember that for really
10594      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10595
10596   std::string virtual_dwo_name =
10597     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
10598                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10599                    (long) (sections.line_size ? sections.line_offset : 0),
10600                    (long) (sections.loc_size ? sections.loc_offset : 0),
10601                    (long) (sections.str_offsets_size
10602                            ? sections.str_offsets_offset : 0));
10603   /* Can we use an existing virtual DWO file?  */
10604   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10605   /* Create one if necessary.  */
10606   if (*dwo_file_slot == NULL)
10607     {
10608       if (dwarf_read_debug)
10609         {
10610           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10611                               virtual_dwo_name.c_str ());
10612         }
10613       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10614       dwo_file->dwo_name
10615         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10616                                         virtual_dwo_name.c_str (),
10617                                         virtual_dwo_name.size ());
10618       dwo_file->comp_dir = comp_dir;
10619       dwo_file->sections.abbrev =
10620         create_dwp_v2_section (&dwp_file->sections.abbrev,
10621                                sections.abbrev_offset, sections.abbrev_size);
10622       dwo_file->sections.line =
10623         create_dwp_v2_section (&dwp_file->sections.line,
10624                                sections.line_offset, sections.line_size);
10625       dwo_file->sections.loc =
10626         create_dwp_v2_section (&dwp_file->sections.loc,
10627                                sections.loc_offset, sections.loc_size);
10628       dwo_file->sections.macinfo =
10629         create_dwp_v2_section (&dwp_file->sections.macinfo,
10630                                sections.macinfo_offset, sections.macinfo_size);
10631       dwo_file->sections.macro =
10632         create_dwp_v2_section (&dwp_file->sections.macro,
10633                                sections.macro_offset, sections.macro_size);
10634       dwo_file->sections.str_offsets =
10635         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10636                                sections.str_offsets_offset,
10637                                sections.str_offsets_size);
10638       /* The "str" section is global to the entire DWP file.  */
10639       dwo_file->sections.str = dwp_file->sections.str;
10640       /* The info or types section is assigned below to dwo_unit,
10641          there's no need to record it in dwo_file.
10642          Also, we can't simply record type sections in dwo_file because
10643          we record a pointer into the vector in dwo_unit.  As we collect more
10644          types we'll grow the vector and eventually have to reallocate space
10645          for it, invalidating all copies of pointers into the previous
10646          contents.  */
10647       *dwo_file_slot = dwo_file;
10648     }
10649   else
10650     {
10651       if (dwarf_read_debug)
10652         {
10653           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10654                               virtual_dwo_name.c_str ());
10655         }
10656       dwo_file = (struct dwo_file *) *dwo_file_slot;
10657     }
10658
10659   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10660   dwo_unit->dwo_file = dwo_file;
10661   dwo_unit->signature = signature;
10662   dwo_unit->section =
10663     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10664   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10665                                               ? &dwp_file->sections.types
10666                                               : &dwp_file->sections.info,
10667                                               sections.info_or_types_offset,
10668                                               sections.info_or_types_size);
10669   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10670
10671   return dwo_unit;
10672 }
10673
10674 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10675    Returns NULL if the signature isn't found.  */
10676
10677 static struct dwo_unit *
10678 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10679                         ULONGEST signature, int is_debug_types)
10680 {
10681   const struct dwp_hash_table *dwp_htab =
10682     is_debug_types ? dwp_file->tus : dwp_file->cus;
10683   bfd *dbfd = dwp_file->dbfd;
10684   uint32_t mask = dwp_htab->nr_slots - 1;
10685   uint32_t hash = signature & mask;
10686   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10687   unsigned int i;
10688   void **slot;
10689   struct dwo_unit find_dwo_cu;
10690
10691   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10692   find_dwo_cu.signature = signature;
10693   slot = htab_find_slot (is_debug_types
10694                          ? dwp_file->loaded_tus
10695                          : dwp_file->loaded_cus,
10696                          &find_dwo_cu, INSERT);
10697
10698   if (*slot != NULL)
10699     return (struct dwo_unit *) *slot;
10700
10701   /* Use a for loop so that we don't loop forever on bad debug info.  */
10702   for (i = 0; i < dwp_htab->nr_slots; ++i)
10703     {
10704       ULONGEST signature_in_table;
10705
10706       signature_in_table =
10707         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10708       if (signature_in_table == signature)
10709         {
10710           uint32_t unit_index =
10711             read_4_bytes (dbfd,
10712                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10713
10714           if (dwp_file->version == 1)
10715             {
10716               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10717                                                  comp_dir, signature,
10718                                                  is_debug_types);
10719             }
10720           else
10721             {
10722               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10723                                                  comp_dir, signature,
10724                                                  is_debug_types);
10725             }
10726           return (struct dwo_unit *) *slot;
10727         }
10728       if (signature_in_table == 0)
10729         return NULL;
10730       hash = (hash + hash2) & mask;
10731     }
10732
10733   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10734            " [in module %s]"),
10735          dwp_file->name);
10736 }
10737
10738 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10739    Open the file specified by FILE_NAME and hand it off to BFD for
10740    preliminary analysis.  Return a newly initialized bfd *, which
10741    includes a canonicalized copy of FILE_NAME.
10742    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10743    SEARCH_CWD is true if the current directory is to be searched.
10744    It will be searched before debug-file-directory.
10745    If successful, the file is added to the bfd include table of the
10746    objfile's bfd (see gdb_bfd_record_inclusion).
10747    If unable to find/open the file, return NULL.
10748    NOTE: This function is derived from symfile_bfd_open.  */
10749
10750 static gdb_bfd_ref_ptr
10751 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10752 {
10753   int desc, flags;
10754   char *absolute_name;
10755   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10756      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10757      to debug_file_directory.  */
10758   char *search_path;
10759   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10760
10761   if (search_cwd)
10762     {
10763       if (*debug_file_directory != '\0')
10764         search_path = concat (".", dirname_separator_string,
10765                               debug_file_directory, (char *) NULL);
10766       else
10767         search_path = xstrdup (".");
10768     }
10769   else
10770     search_path = xstrdup (debug_file_directory);
10771
10772   flags = OPF_RETURN_REALPATH;
10773   if (is_dwp)
10774     flags |= OPF_SEARCH_IN_PATH;
10775   desc = openp (search_path, flags, file_name,
10776                 O_RDONLY | O_BINARY, &absolute_name);
10777   xfree (search_path);
10778   if (desc < 0)
10779     return NULL;
10780
10781   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10782   xfree (absolute_name);
10783   if (sym_bfd == NULL)
10784     return NULL;
10785   bfd_set_cacheable (sym_bfd.get (), 1);
10786
10787   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10788     return NULL;
10789
10790   /* Success.  Record the bfd as having been included by the objfile's bfd.
10791      This is important because things like demangled_names_hash lives in the
10792      objfile's per_bfd space and may have references to things like symbol
10793      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10794   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10795
10796   return sym_bfd;
10797 }
10798
10799 /* Try to open DWO file FILE_NAME.
10800    COMP_DIR is the DW_AT_comp_dir attribute.
10801    The result is the bfd handle of the file.
10802    If there is a problem finding or opening the file, return NULL.
10803    Upon success, the canonicalized path of the file is stored in the bfd,
10804    same as symfile_bfd_open.  */
10805
10806 static gdb_bfd_ref_ptr
10807 open_dwo_file (const char *file_name, const char *comp_dir)
10808 {
10809   if (IS_ABSOLUTE_PATH (file_name))
10810     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10811
10812   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10813
10814   if (comp_dir != NULL)
10815     {
10816       char *path_to_try = concat (comp_dir, SLASH_STRING,
10817                                   file_name, (char *) NULL);
10818
10819       /* NOTE: If comp_dir is a relative path, this will also try the
10820          search path, which seems useful.  */
10821       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10822                                                 1 /*search_cwd*/));
10823       xfree (path_to_try);
10824       if (abfd != NULL)
10825         return abfd;
10826     }
10827
10828   /* That didn't work, try debug-file-directory, which, despite its name,
10829      is a list of paths.  */
10830
10831   if (*debug_file_directory == '\0')
10832     return NULL;
10833
10834   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10835 }
10836
10837 /* This function is mapped across the sections and remembers the offset and
10838    size of each of the DWO debugging sections we are interested in.  */
10839
10840 static void
10841 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10842 {
10843   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10844   const struct dwop_section_names *names = &dwop_section_names;
10845
10846   if (section_is_p (sectp->name, &names->abbrev_dwo))
10847     {
10848       dwo_sections->abbrev.s.section = sectp;
10849       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10850     }
10851   else if (section_is_p (sectp->name, &names->info_dwo))
10852     {
10853       dwo_sections->info.s.section = sectp;
10854       dwo_sections->info.size = bfd_get_section_size (sectp);
10855     }
10856   else if (section_is_p (sectp->name, &names->line_dwo))
10857     {
10858       dwo_sections->line.s.section = sectp;
10859       dwo_sections->line.size = bfd_get_section_size (sectp);
10860     }
10861   else if (section_is_p (sectp->name, &names->loc_dwo))
10862     {
10863       dwo_sections->loc.s.section = sectp;
10864       dwo_sections->loc.size = bfd_get_section_size (sectp);
10865     }
10866   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10867     {
10868       dwo_sections->macinfo.s.section = sectp;
10869       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10870     }
10871   else if (section_is_p (sectp->name, &names->macro_dwo))
10872     {
10873       dwo_sections->macro.s.section = sectp;
10874       dwo_sections->macro.size = bfd_get_section_size (sectp);
10875     }
10876   else if (section_is_p (sectp->name, &names->str_dwo))
10877     {
10878       dwo_sections->str.s.section = sectp;
10879       dwo_sections->str.size = bfd_get_section_size (sectp);
10880     }
10881   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10882     {
10883       dwo_sections->str_offsets.s.section = sectp;
10884       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10885     }
10886   else if (section_is_p (sectp->name, &names->types_dwo))
10887     {
10888       struct dwarf2_section_info type_section;
10889
10890       memset (&type_section, 0, sizeof (type_section));
10891       type_section.s.section = sectp;
10892       type_section.size = bfd_get_section_size (sectp);
10893       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10894                      &type_section);
10895     }
10896 }
10897
10898 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10899    by PER_CU.  This is for the non-DWP case.
10900    The result is NULL if DWO_NAME can't be found.  */
10901
10902 static struct dwo_file *
10903 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10904                         const char *dwo_name, const char *comp_dir)
10905 {
10906   struct objfile *objfile = dwarf2_per_objfile->objfile;
10907   struct dwo_file *dwo_file;
10908   struct cleanup *cleanups;
10909
10910   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10911   if (dbfd == NULL)
10912     {
10913       if (dwarf_read_debug)
10914         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10915       return NULL;
10916     }
10917   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10918   dwo_file->dwo_name = dwo_name;
10919   dwo_file->comp_dir = comp_dir;
10920   dwo_file->dbfd = dbfd.release ();
10921
10922   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10923
10924   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10925                          &dwo_file->sections);
10926
10927   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10928
10929   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10930                                  dwo_file->tus);
10931
10932   discard_cleanups (cleanups);
10933
10934   if (dwarf_read_debug)
10935     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10936
10937   return dwo_file;
10938 }
10939
10940 /* This function is mapped across the sections and remembers the offset and
10941    size of each of the DWP debugging sections common to version 1 and 2 that
10942    we are interested in.  */
10943
10944 static void
10945 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10946                                    void *dwp_file_ptr)
10947 {
10948   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10949   const struct dwop_section_names *names = &dwop_section_names;
10950   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10951
10952   /* Record the ELF section number for later lookup: this is what the
10953      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10954   gdb_assert (elf_section_nr < dwp_file->num_sections);
10955   dwp_file->elf_sections[elf_section_nr] = sectp;
10956
10957   /* Look for specific sections that we need.  */
10958   if (section_is_p (sectp->name, &names->str_dwo))
10959     {
10960       dwp_file->sections.str.s.section = sectp;
10961       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10962     }
10963   else if (section_is_p (sectp->name, &names->cu_index))
10964     {
10965       dwp_file->sections.cu_index.s.section = sectp;
10966       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10967     }
10968   else if (section_is_p (sectp->name, &names->tu_index))
10969     {
10970       dwp_file->sections.tu_index.s.section = sectp;
10971       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10972     }
10973 }
10974
10975 /* This function is mapped across the sections and remembers the offset and
10976    size of each of the DWP version 2 debugging sections that we are interested
10977    in.  This is split into a separate function because we don't know if we
10978    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10979
10980 static void
10981 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10982 {
10983   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10984   const struct dwop_section_names *names = &dwop_section_names;
10985   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10986
10987   /* Record the ELF section number for later lookup: this is what the
10988      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10989   gdb_assert (elf_section_nr < dwp_file->num_sections);
10990   dwp_file->elf_sections[elf_section_nr] = sectp;
10991
10992   /* Look for specific sections that we need.  */
10993   if (section_is_p (sectp->name, &names->abbrev_dwo))
10994     {
10995       dwp_file->sections.abbrev.s.section = sectp;
10996       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10997     }
10998   else if (section_is_p (sectp->name, &names->info_dwo))
10999     {
11000       dwp_file->sections.info.s.section = sectp;
11001       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11002     }
11003   else if (section_is_p (sectp->name, &names->line_dwo))
11004     {
11005       dwp_file->sections.line.s.section = sectp;
11006       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11007     }
11008   else if (section_is_p (sectp->name, &names->loc_dwo))
11009     {
11010       dwp_file->sections.loc.s.section = sectp;
11011       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11012     }
11013   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11014     {
11015       dwp_file->sections.macinfo.s.section = sectp;
11016       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11017     }
11018   else if (section_is_p (sectp->name, &names->macro_dwo))
11019     {
11020       dwp_file->sections.macro.s.section = sectp;
11021       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11022     }
11023   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11024     {
11025       dwp_file->sections.str_offsets.s.section = sectp;
11026       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11027     }
11028   else if (section_is_p (sectp->name, &names->types_dwo))
11029     {
11030       dwp_file->sections.types.s.section = sectp;
11031       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11032     }
11033 }
11034
11035 /* Hash function for dwp_file loaded CUs/TUs.  */
11036
11037 static hashval_t
11038 hash_dwp_loaded_cutus (const void *item)
11039 {
11040   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11041
11042   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11043   return dwo_unit->signature;
11044 }
11045
11046 /* Equality function for dwp_file loaded CUs/TUs.  */
11047
11048 static int
11049 eq_dwp_loaded_cutus (const void *a, const void *b)
11050 {
11051   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11052   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11053
11054   return dua->signature == dub->signature;
11055 }
11056
11057 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11058
11059 static htab_t
11060 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11061 {
11062   return htab_create_alloc_ex (3,
11063                                hash_dwp_loaded_cutus,
11064                                eq_dwp_loaded_cutus,
11065                                NULL,
11066                                &objfile->objfile_obstack,
11067                                hashtab_obstack_allocate,
11068                                dummy_obstack_deallocate);
11069 }
11070
11071 /* Try to open DWP file FILE_NAME.
11072    The result is the bfd handle of the file.
11073    If there is a problem finding or opening the file, return NULL.
11074    Upon success, the canonicalized path of the file is stored in the bfd,
11075    same as symfile_bfd_open.  */
11076
11077 static gdb_bfd_ref_ptr
11078 open_dwp_file (const char *file_name)
11079 {
11080   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11081                                             1 /*search_cwd*/));
11082   if (abfd != NULL)
11083     return abfd;
11084
11085   /* Work around upstream bug 15652.
11086      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11087      [Whether that's a "bug" is debatable, but it is getting in our way.]
11088      We have no real idea where the dwp file is, because gdb's realpath-ing
11089      of the executable's path may have discarded the needed info.
11090      [IWBN if the dwp file name was recorded in the executable, akin to
11091      .gnu_debuglink, but that doesn't exist yet.]
11092      Strip the directory from FILE_NAME and search again.  */
11093   if (*debug_file_directory != '\0')
11094     {
11095       /* Don't implicitly search the current directory here.
11096          If the user wants to search "." to handle this case,
11097          it must be added to debug-file-directory.  */
11098       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11099                                  0 /*search_cwd*/);
11100     }
11101
11102   return NULL;
11103 }
11104
11105 /* Initialize the use of the DWP file for the current objfile.
11106    By convention the name of the DWP file is ${objfile}.dwp.
11107    The result is NULL if it can't be found.  */
11108
11109 static struct dwp_file *
11110 open_and_init_dwp_file (void)
11111 {
11112   struct objfile *objfile = dwarf2_per_objfile->objfile;
11113   struct dwp_file *dwp_file;
11114
11115   /* Try to find first .dwp for the binary file before any symbolic links
11116      resolving.  */
11117
11118   /* If the objfile is a debug file, find the name of the real binary
11119      file and get the name of dwp file from there.  */
11120   std::string dwp_name;
11121   if (objfile->separate_debug_objfile_backlink != NULL)
11122     {
11123       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11124       const char *backlink_basename = lbasename (backlink->original_name);
11125
11126       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11127     }
11128   else
11129     dwp_name = objfile->original_name;
11130
11131   dwp_name += ".dwp";
11132
11133   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11134   if (dbfd == NULL
11135       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11136     {
11137       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11138       dwp_name = objfile_name (objfile);
11139       dwp_name += ".dwp";
11140       dbfd = open_dwp_file (dwp_name.c_str ());
11141     }
11142
11143   if (dbfd == NULL)
11144     {
11145       if (dwarf_read_debug)
11146         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11147       return NULL;
11148     }
11149   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11150   dwp_file->name = bfd_get_filename (dbfd.get ());
11151   dwp_file->dbfd = dbfd.release ();
11152
11153   /* +1: section 0 is unused */
11154   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11155   dwp_file->elf_sections =
11156     OBSTACK_CALLOC (&objfile->objfile_obstack,
11157                     dwp_file->num_sections, asection *);
11158
11159   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11160                          dwp_file);
11161
11162   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11163
11164   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11165
11166   /* The DWP file version is stored in the hash table.  Oh well.  */
11167   if (dwp_file->cus && dwp_file->tus
11168       && dwp_file->cus->version != dwp_file->tus->version)
11169     {
11170       /* Technically speaking, we should try to limp along, but this is
11171          pretty bizarre.  We use pulongest here because that's the established
11172          portability solution (e.g, we cannot use %u for uint32_t).  */
11173       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11174                " TU version %s [in DWP file %s]"),
11175              pulongest (dwp_file->cus->version),
11176              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11177     }
11178
11179   if (dwp_file->cus)
11180     dwp_file->version = dwp_file->cus->version;
11181   else if (dwp_file->tus)
11182     dwp_file->version = dwp_file->tus->version;
11183   else
11184     dwp_file->version = 2;
11185
11186   if (dwp_file->version == 2)
11187     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11188                            dwp_file);
11189
11190   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11191   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11192
11193   if (dwarf_read_debug)
11194     {
11195       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11196       fprintf_unfiltered (gdb_stdlog,
11197                           "    %s CUs, %s TUs\n",
11198                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11199                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11200     }
11201
11202   return dwp_file;
11203 }
11204
11205 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11206
11207 static struct dwp_file *
11208 get_dwp_file (void)
11209 {
11210   if (! dwarf2_per_objfile->dwp_checked)
11211     {
11212       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11213       dwarf2_per_objfile->dwp_checked = 1;
11214     }
11215   return dwarf2_per_objfile->dwp_file;
11216 }
11217
11218 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11219    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11220    or in the DWP file for the objfile, referenced by THIS_UNIT.
11221    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11222    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11223
11224    This is called, for example, when wanting to read a variable with a
11225    complex location.  Therefore we don't want to do file i/o for every call.
11226    Therefore we don't want to look for a DWO file on every call.
11227    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11228    then we check if we've already seen DWO_NAME, and only THEN do we check
11229    for a DWO file.
11230
11231    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11232    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11233
11234 static struct dwo_unit *
11235 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11236                  const char *dwo_name, const char *comp_dir,
11237                  ULONGEST signature, int is_debug_types)
11238 {
11239   struct objfile *objfile = dwarf2_per_objfile->objfile;
11240   const char *kind = is_debug_types ? "TU" : "CU";
11241   void **dwo_file_slot;
11242   struct dwo_file *dwo_file;
11243   struct dwp_file *dwp_file;
11244
11245   /* First see if there's a DWP file.
11246      If we have a DWP file but didn't find the DWO inside it, don't
11247      look for the original DWO file.  It makes gdb behave differently
11248      depending on whether one is debugging in the build tree.  */
11249
11250   dwp_file = get_dwp_file ();
11251   if (dwp_file != NULL)
11252     {
11253       const struct dwp_hash_table *dwp_htab =
11254         is_debug_types ? dwp_file->tus : dwp_file->cus;
11255
11256       if (dwp_htab != NULL)
11257         {
11258           struct dwo_unit *dwo_cutu =
11259             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11260                                     signature, is_debug_types);
11261
11262           if (dwo_cutu != NULL)
11263             {
11264               if (dwarf_read_debug)
11265                 {
11266                   fprintf_unfiltered (gdb_stdlog,
11267                                       "Virtual DWO %s %s found: @%s\n",
11268                                       kind, hex_string (signature),
11269                                       host_address_to_string (dwo_cutu));
11270                 }
11271               return dwo_cutu;
11272             }
11273         }
11274     }
11275   else
11276     {
11277       /* No DWP file, look for the DWO file.  */
11278
11279       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11280       if (*dwo_file_slot == NULL)
11281         {
11282           /* Read in the file and build a table of the CUs/TUs it contains.  */
11283           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11284         }
11285       /* NOTE: This will be NULL if unable to open the file.  */
11286       dwo_file = (struct dwo_file *) *dwo_file_slot;
11287
11288       if (dwo_file != NULL)
11289         {
11290           struct dwo_unit *dwo_cutu = NULL;
11291
11292           if (is_debug_types && dwo_file->tus)
11293             {
11294               struct dwo_unit find_dwo_cutu;
11295
11296               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11297               find_dwo_cutu.signature = signature;
11298               dwo_cutu
11299                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11300             }
11301           else if (!is_debug_types && dwo_file->cus)
11302             {
11303               struct dwo_unit find_dwo_cutu;
11304
11305               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11306               find_dwo_cutu.signature = signature;
11307               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11308                                                        &find_dwo_cutu);
11309             }
11310
11311           if (dwo_cutu != NULL)
11312             {
11313               if (dwarf_read_debug)
11314                 {
11315                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11316                                       kind, dwo_name, hex_string (signature),
11317                                       host_address_to_string (dwo_cutu));
11318                 }
11319               return dwo_cutu;
11320             }
11321         }
11322     }
11323
11324   /* We didn't find it.  This could mean a dwo_id mismatch, or
11325      someone deleted the DWO/DWP file, or the search path isn't set up
11326      correctly to find the file.  */
11327
11328   if (dwarf_read_debug)
11329     {
11330       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11331                           kind, dwo_name, hex_string (signature));
11332     }
11333
11334   /* This is a warning and not a complaint because it can be caused by
11335      pilot error (e.g., user accidentally deleting the DWO).  */
11336   {
11337     /* Print the name of the DWP file if we looked there, helps the user
11338        better diagnose the problem.  */
11339     std::string dwp_text;
11340
11341     if (dwp_file != NULL)
11342       dwp_text = string_printf (" [in DWP file %s]",
11343                                 lbasename (dwp_file->name));
11344
11345     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11346                " [in module %s]"),
11347              kind, dwo_name, hex_string (signature),
11348              dwp_text.c_str (),
11349              this_unit->is_debug_types ? "TU" : "CU",
11350              to_underlying (this_unit->sect_off), objfile_name (objfile));
11351   }
11352   return NULL;
11353 }
11354
11355 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11356    See lookup_dwo_cutu_unit for details.  */
11357
11358 static struct dwo_unit *
11359 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11360                       const char *dwo_name, const char *comp_dir,
11361                       ULONGEST signature)
11362 {
11363   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11364 }
11365
11366 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11367    See lookup_dwo_cutu_unit for details.  */
11368
11369 static struct dwo_unit *
11370 lookup_dwo_type_unit (struct signatured_type *this_tu,
11371                       const char *dwo_name, const char *comp_dir)
11372 {
11373   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11374 }
11375
11376 /* Traversal function for queue_and_load_all_dwo_tus.  */
11377
11378 static int
11379 queue_and_load_dwo_tu (void **slot, void *info)
11380 {
11381   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11382   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11383   ULONGEST signature = dwo_unit->signature;
11384   struct signatured_type *sig_type =
11385     lookup_dwo_signatured_type (per_cu->cu, signature);
11386
11387   if (sig_type != NULL)
11388     {
11389       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11390
11391       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11392          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11393          while processing PER_CU.  */
11394       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11395         load_full_type_unit (sig_cu);
11396       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11397     }
11398
11399   return 1;
11400 }
11401
11402 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11403    The DWO may have the only definition of the type, though it may not be
11404    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11405    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11406
11407 static void
11408 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11409 {
11410   struct dwo_unit *dwo_unit;
11411   struct dwo_file *dwo_file;
11412
11413   gdb_assert (!per_cu->is_debug_types);
11414   gdb_assert (get_dwp_file () == NULL);
11415   gdb_assert (per_cu->cu != NULL);
11416
11417   dwo_unit = per_cu->cu->dwo_unit;
11418   gdb_assert (dwo_unit != NULL);
11419
11420   dwo_file = dwo_unit->dwo_file;
11421   if (dwo_file->tus != NULL)
11422     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11423 }
11424
11425 /* Free all resources associated with DWO_FILE.
11426    Close the DWO file and munmap the sections.
11427    All memory should be on the objfile obstack.  */
11428
11429 static void
11430 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11431 {
11432
11433   /* Note: dbfd is NULL for virtual DWO files.  */
11434   gdb_bfd_unref (dwo_file->dbfd);
11435
11436   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11437 }
11438
11439 /* Wrapper for free_dwo_file for use in cleanups.  */
11440
11441 static void
11442 free_dwo_file_cleanup (void *arg)
11443 {
11444   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11445   struct objfile *objfile = dwarf2_per_objfile->objfile;
11446
11447   free_dwo_file (dwo_file, objfile);
11448 }
11449
11450 /* Traversal function for free_dwo_files.  */
11451
11452 static int
11453 free_dwo_file_from_slot (void **slot, void *info)
11454 {
11455   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11456   struct objfile *objfile = (struct objfile *) info;
11457
11458   free_dwo_file (dwo_file, objfile);
11459
11460   return 1;
11461 }
11462
11463 /* Free all resources associated with DWO_FILES.  */
11464
11465 static void
11466 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11467 {
11468   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11469 }
11470 \f
11471 /* Read in various DIEs.  */
11472
11473 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11474    Inherit only the children of the DW_AT_abstract_origin DIE not being
11475    already referenced by DW_AT_abstract_origin from the children of the
11476    current DIE.  */
11477
11478 static void
11479 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11480 {
11481   struct die_info *child_die;
11482   sect_offset *offsetp;
11483   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11484   struct die_info *origin_die;
11485   /* Iterator of the ORIGIN_DIE children.  */
11486   struct die_info *origin_child_die;
11487   struct attribute *attr;
11488   struct dwarf2_cu *origin_cu;
11489   struct pending **origin_previous_list_in_scope;
11490
11491   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11492   if (!attr)
11493     return;
11494
11495   /* Note that following die references may follow to a die in a
11496      different cu.  */
11497
11498   origin_cu = cu;
11499   origin_die = follow_die_ref (die, attr, &origin_cu);
11500
11501   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11502      symbols in.  */
11503   origin_previous_list_in_scope = origin_cu->list_in_scope;
11504   origin_cu->list_in_scope = cu->list_in_scope;
11505
11506   if (die->tag != origin_die->tag
11507       && !(die->tag == DW_TAG_inlined_subroutine
11508            && origin_die->tag == DW_TAG_subprogram))
11509     complaint (&symfile_complaints,
11510                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11511                to_underlying (die->sect_off),
11512                to_underlying (origin_die->sect_off));
11513
11514   std::vector<sect_offset> offsets;
11515
11516   for (child_die = die->child;
11517        child_die && child_die->tag;
11518        child_die = sibling_die (child_die))
11519     {
11520       struct die_info *child_origin_die;
11521       struct dwarf2_cu *child_origin_cu;
11522
11523       /* We are trying to process concrete instance entries:
11524          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11525          it's not relevant to our analysis here. i.e. detecting DIEs that are
11526          present in the abstract instance but not referenced in the concrete
11527          one.  */
11528       if (child_die->tag == DW_TAG_call_site
11529           || child_die->tag == DW_TAG_GNU_call_site)
11530         continue;
11531
11532       /* For each CHILD_DIE, find the corresponding child of
11533          ORIGIN_DIE.  If there is more than one layer of
11534          DW_AT_abstract_origin, follow them all; there shouldn't be,
11535          but GCC versions at least through 4.4 generate this (GCC PR
11536          40573).  */
11537       child_origin_die = child_die;
11538       child_origin_cu = cu;
11539       while (1)
11540         {
11541           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11542                               child_origin_cu);
11543           if (attr == NULL)
11544             break;
11545           child_origin_die = follow_die_ref (child_origin_die, attr,
11546                                              &child_origin_cu);
11547         }
11548
11549       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11550          counterpart may exist.  */
11551       if (child_origin_die != child_die)
11552         {
11553           if (child_die->tag != child_origin_die->tag
11554               && !(child_die->tag == DW_TAG_inlined_subroutine
11555                    && child_origin_die->tag == DW_TAG_subprogram))
11556             complaint (&symfile_complaints,
11557                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11558                          "different tags"),
11559                        to_underlying (child_die->sect_off),
11560                        to_underlying (child_origin_die->sect_off));
11561           if (child_origin_die->parent != origin_die)
11562             complaint (&symfile_complaints,
11563                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11564                          "different parents"),
11565                        to_underlying (child_die->sect_off),
11566                        to_underlying (child_origin_die->sect_off));
11567           else
11568             offsets.push_back (child_origin_die->sect_off);
11569         }
11570     }
11571   std::sort (offsets.begin (), offsets.end ());
11572   sect_offset *offsets_end = offsets.data () + offsets.size ();
11573   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
11574     if (offsetp[-1] == *offsetp)
11575       complaint (&symfile_complaints,
11576                  _("Multiple children of DIE 0x%x refer "
11577                    "to DIE 0x%x as their abstract origin"),
11578                  to_underlying (die->sect_off), to_underlying (*offsetp));
11579
11580   offsetp = offsets.data ();
11581   origin_child_die = origin_die->child;
11582   while (origin_child_die && origin_child_die->tag)
11583     {
11584       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11585       while (offsetp < offsets_end
11586              && *offsetp < origin_child_die->sect_off)
11587         offsetp++;
11588       if (offsetp >= offsets_end
11589           || *offsetp > origin_child_die->sect_off)
11590         {
11591           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11592              Check whether we're already processing ORIGIN_CHILD_DIE.
11593              This can happen with mutually referenced abstract_origins.
11594              PR 16581.  */
11595           if (!origin_child_die->in_process)
11596             process_die (origin_child_die, origin_cu);
11597         }
11598       origin_child_die = sibling_die (origin_child_die);
11599     }
11600   origin_cu->list_in_scope = origin_previous_list_in_scope;
11601 }
11602
11603 static void
11604 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11605 {
11606   struct objfile *objfile = cu->objfile;
11607   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11608   struct context_stack *newobj;
11609   CORE_ADDR lowpc;
11610   CORE_ADDR highpc;
11611   struct die_info *child_die;
11612   struct attribute *attr, *call_line, *call_file;
11613   const char *name;
11614   CORE_ADDR baseaddr;
11615   struct block *block;
11616   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11617   VEC (symbolp) *template_args = NULL;
11618   struct template_symbol *templ_func = NULL;
11619
11620   if (inlined_func)
11621     {
11622       /* If we do not have call site information, we can't show the
11623          caller of this inlined function.  That's too confusing, so
11624          only use the scope for local variables.  */
11625       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11626       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11627       if (call_line == NULL || call_file == NULL)
11628         {
11629           read_lexical_block_scope (die, cu);
11630           return;
11631         }
11632     }
11633
11634   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11635
11636   name = dwarf2_name (die, cu);
11637
11638   /* Ignore functions with missing or empty names.  These are actually
11639      illegal according to the DWARF standard.  */
11640   if (name == NULL)
11641     {
11642       complaint (&symfile_complaints,
11643                  _("missing name for subprogram DIE at %d"),
11644                  to_underlying (die->sect_off));
11645       return;
11646     }
11647
11648   /* Ignore functions with missing or invalid low and high pc attributes.  */
11649   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11650       <= PC_BOUNDS_INVALID)
11651     {
11652       attr = dwarf2_attr (die, DW_AT_external, cu);
11653       if (!attr || !DW_UNSND (attr))
11654         complaint (&symfile_complaints,
11655                    _("cannot get low and high bounds "
11656                      "for subprogram DIE at %d"),
11657                    to_underlying (die->sect_off));
11658       return;
11659     }
11660
11661   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11662   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11663
11664   /* If we have any template arguments, then we must allocate a
11665      different sort of symbol.  */
11666   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11667     {
11668       if (child_die->tag == DW_TAG_template_type_param
11669           || child_die->tag == DW_TAG_template_value_param)
11670         {
11671           templ_func = allocate_template_symbol (objfile);
11672           templ_func->base.is_cplus_template_function = 1;
11673           break;
11674         }
11675     }
11676
11677   newobj = push_context (0, lowpc);
11678   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11679                                (struct symbol *) templ_func);
11680
11681   /* If there is a location expression for DW_AT_frame_base, record
11682      it.  */
11683   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11684   if (attr)
11685     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11686
11687   /* If there is a location for the static link, record it.  */
11688   newobj->static_link = NULL;
11689   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11690   if (attr)
11691     {
11692       newobj->static_link
11693         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11694       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11695     }
11696
11697   cu->list_in_scope = &local_symbols;
11698
11699   if (die->child != NULL)
11700     {
11701       child_die = die->child;
11702       while (child_die && child_die->tag)
11703         {
11704           if (child_die->tag == DW_TAG_template_type_param
11705               || child_die->tag == DW_TAG_template_value_param)
11706             {
11707               struct symbol *arg = new_symbol (child_die, NULL, cu);
11708
11709               if (arg != NULL)
11710                 VEC_safe_push (symbolp, template_args, arg);
11711             }
11712           else
11713             process_die (child_die, cu);
11714           child_die = sibling_die (child_die);
11715         }
11716     }
11717
11718   inherit_abstract_dies (die, cu);
11719
11720   /* If we have a DW_AT_specification, we might need to import using
11721      directives from the context of the specification DIE.  See the
11722      comment in determine_prefix.  */
11723   if (cu->language == language_cplus
11724       && dwarf2_attr (die, DW_AT_specification, cu))
11725     {
11726       struct dwarf2_cu *spec_cu = cu;
11727       struct die_info *spec_die = die_specification (die, &spec_cu);
11728
11729       while (spec_die)
11730         {
11731           child_die = spec_die->child;
11732           while (child_die && child_die->tag)
11733             {
11734               if (child_die->tag == DW_TAG_imported_module)
11735                 process_die (child_die, spec_cu);
11736               child_die = sibling_die (child_die);
11737             }
11738
11739           /* In some cases, GCC generates specification DIEs that
11740              themselves contain DW_AT_specification attributes.  */
11741           spec_die = die_specification (spec_die, &spec_cu);
11742         }
11743     }
11744
11745   newobj = pop_context ();
11746   /* Make a block for the local symbols within.  */
11747   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11748                         newobj->static_link, lowpc, highpc);
11749
11750   /* For C++, set the block's scope.  */
11751   if ((cu->language == language_cplus
11752        || cu->language == language_fortran
11753        || cu->language == language_d
11754        || cu->language == language_rust)
11755       && cu->processing_has_namespace_info)
11756     block_set_scope (block, determine_prefix (die, cu),
11757                      &objfile->objfile_obstack);
11758
11759   /* If we have address ranges, record them.  */
11760   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11761
11762   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11763
11764   /* Attach template arguments to function.  */
11765   if (! VEC_empty (symbolp, template_args))
11766     {
11767       gdb_assert (templ_func != NULL);
11768
11769       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11770       templ_func->template_arguments
11771         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11772                      templ_func->n_template_arguments);
11773       memcpy (templ_func->template_arguments,
11774               VEC_address (symbolp, template_args),
11775               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11776       VEC_free (symbolp, template_args);
11777     }
11778
11779   /* In C++, we can have functions nested inside functions (e.g., when
11780      a function declares a class that has methods).  This means that
11781      when we finish processing a function scope, we may need to go
11782      back to building a containing block's symbol lists.  */
11783   local_symbols = newobj->locals;
11784   local_using_directives = newobj->local_using_directives;
11785
11786   /* If we've finished processing a top-level function, subsequent
11787      symbols go in the file symbol list.  */
11788   if (outermost_context_p ())
11789     cu->list_in_scope = &file_symbols;
11790 }
11791
11792 /* Process all the DIES contained within a lexical block scope.  Start
11793    a new scope, process the dies, and then close the scope.  */
11794
11795 static void
11796 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11797 {
11798   struct objfile *objfile = cu->objfile;
11799   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11800   struct context_stack *newobj;
11801   CORE_ADDR lowpc, highpc;
11802   struct die_info *child_die;
11803   CORE_ADDR baseaddr;
11804
11805   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11806
11807   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11808   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11809      as multiple lexical blocks?  Handling children in a sane way would
11810      be nasty.  Might be easier to properly extend generic blocks to
11811      describe ranges.  */
11812   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11813     {
11814     case PC_BOUNDS_NOT_PRESENT:
11815       /* DW_TAG_lexical_block has no attributes, process its children as if
11816          there was no wrapping by that DW_TAG_lexical_block.
11817          GCC does no longer produces such DWARF since GCC r224161.  */
11818       for (child_die = die->child;
11819            child_die != NULL && child_die->tag;
11820            child_die = sibling_die (child_die))
11821         process_die (child_die, cu);
11822       return;
11823     case PC_BOUNDS_INVALID:
11824       return;
11825     }
11826   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11827   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11828
11829   push_context (0, lowpc);
11830   if (die->child != NULL)
11831     {
11832       child_die = die->child;
11833       while (child_die && child_die->tag)
11834         {
11835           process_die (child_die, cu);
11836           child_die = sibling_die (child_die);
11837         }
11838     }
11839   inherit_abstract_dies (die, cu);
11840   newobj = pop_context ();
11841
11842   if (local_symbols != NULL || local_using_directives != NULL)
11843     {
11844       struct block *block
11845         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11846                         newobj->start_addr, highpc);
11847
11848       /* Note that recording ranges after traversing children, as we
11849          do here, means that recording a parent's ranges entails
11850          walking across all its children's ranges as they appear in
11851          the address map, which is quadratic behavior.
11852
11853          It would be nicer to record the parent's ranges before
11854          traversing its children, simply overriding whatever you find
11855          there.  But since we don't even decide whether to create a
11856          block until after we've traversed its children, that's hard
11857          to do.  */
11858       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11859     }
11860   local_symbols = newobj->locals;
11861   local_using_directives = newobj->local_using_directives;
11862 }
11863
11864 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11865
11866 static void
11867 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11868 {
11869   struct objfile *objfile = cu->objfile;
11870   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11871   CORE_ADDR pc, baseaddr;
11872   struct attribute *attr;
11873   struct call_site *call_site, call_site_local;
11874   void **slot;
11875   int nparams;
11876   struct die_info *child_die;
11877
11878   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11879
11880   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11881   if (attr == NULL)
11882     {
11883       /* This was a pre-DWARF-5 GNU extension alias
11884          for DW_AT_call_return_pc.  */
11885       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11886     }
11887   if (!attr)
11888     {
11889       complaint (&symfile_complaints,
11890                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11891                    "DIE 0x%x [in module %s]"),
11892                  to_underlying (die->sect_off), objfile_name (objfile));
11893       return;
11894     }
11895   pc = attr_value_as_address (attr) + baseaddr;
11896   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11897
11898   if (cu->call_site_htab == NULL)
11899     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11900                                                NULL, &objfile->objfile_obstack,
11901                                                hashtab_obstack_allocate, NULL);
11902   call_site_local.pc = pc;
11903   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11904   if (*slot != NULL)
11905     {
11906       complaint (&symfile_complaints,
11907                  _("Duplicate PC %s for DW_TAG_call_site "
11908                    "DIE 0x%x [in module %s]"),
11909                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11910                  objfile_name (objfile));
11911       return;
11912     }
11913
11914   /* Count parameters at the caller.  */
11915
11916   nparams = 0;
11917   for (child_die = die->child; child_die && child_die->tag;
11918        child_die = sibling_die (child_die))
11919     {
11920       if (child_die->tag != DW_TAG_call_site_parameter
11921           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11922         {
11923           complaint (&symfile_complaints,
11924                      _("Tag %d is not DW_TAG_call_site_parameter in "
11925                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11926                      child_die->tag, to_underlying (child_die->sect_off),
11927                      objfile_name (objfile));
11928           continue;
11929         }
11930
11931       nparams++;
11932     }
11933
11934   call_site
11935     = ((struct call_site *)
11936        obstack_alloc (&objfile->objfile_obstack,
11937                       sizeof (*call_site)
11938                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11939   *slot = call_site;
11940   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11941   call_site->pc = pc;
11942
11943   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11944       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11945     {
11946       struct die_info *func_die;
11947
11948       /* Skip also over DW_TAG_inlined_subroutine.  */
11949       for (func_die = die->parent;
11950            func_die && func_die->tag != DW_TAG_subprogram
11951            && func_die->tag != DW_TAG_subroutine_type;
11952            func_die = func_die->parent);
11953
11954       /* DW_AT_call_all_calls is a superset
11955          of DW_AT_call_all_tail_calls.  */
11956       if (func_die
11957           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11958           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11959           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11960           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11961         {
11962           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11963              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11964              both the initial caller containing the real return address PC and
11965              the final callee containing the current PC of a chain of tail
11966              calls do not need to have the tail call list complete.  But any
11967              function candidate for a virtual tail call frame searched via
11968              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11969              determined unambiguously.  */
11970         }
11971       else
11972         {
11973           struct type *func_type = NULL;
11974
11975           if (func_die)
11976             func_type = get_die_type (func_die, cu);
11977           if (func_type != NULL)
11978             {
11979               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11980
11981               /* Enlist this call site to the function.  */
11982               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11983               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11984             }
11985           else
11986             complaint (&symfile_complaints,
11987                        _("Cannot find function owning DW_TAG_call_site "
11988                          "DIE 0x%x [in module %s]"),
11989                        to_underlying (die->sect_off), objfile_name (objfile));
11990         }
11991     }
11992
11993   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11994   if (attr == NULL)
11995     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11996   if (attr == NULL)
11997     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11998   if (attr == NULL)
11999     {
12000       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12001       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12002     }
12003   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12004   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12005     /* Keep NULL DWARF_BLOCK.  */;
12006   else if (attr_form_is_block (attr))
12007     {
12008       struct dwarf2_locexpr_baton *dlbaton;
12009
12010       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12011       dlbaton->data = DW_BLOCK (attr)->data;
12012       dlbaton->size = DW_BLOCK (attr)->size;
12013       dlbaton->per_cu = cu->per_cu;
12014
12015       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12016     }
12017   else if (attr_form_is_ref (attr))
12018     {
12019       struct dwarf2_cu *target_cu = cu;
12020       struct die_info *target_die;
12021
12022       target_die = follow_die_ref (die, attr, &target_cu);
12023       gdb_assert (target_cu->objfile == objfile);
12024       if (die_is_declaration (target_die, target_cu))
12025         {
12026           const char *target_physname;
12027
12028           /* Prefer the mangled name; otherwise compute the demangled one.  */
12029           target_physname = dw2_linkage_name (target_die, target_cu);
12030           if (target_physname == NULL)
12031             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12032           if (target_physname == NULL)
12033             complaint (&symfile_complaints,
12034                        _("DW_AT_call_target target DIE has invalid "
12035                          "physname, for referencing DIE 0x%x [in module %s]"),
12036                        to_underlying (die->sect_off), objfile_name (objfile));
12037           else
12038             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12039         }
12040       else
12041         {
12042           CORE_ADDR lowpc;
12043
12044           /* DW_AT_entry_pc should be preferred.  */
12045           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12046               <= PC_BOUNDS_INVALID)
12047             complaint (&symfile_complaints,
12048                        _("DW_AT_call_target target DIE has invalid "
12049                          "low pc, for referencing DIE 0x%x [in module %s]"),
12050                        to_underlying (die->sect_off), objfile_name (objfile));
12051           else
12052             {
12053               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12054               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12055             }
12056         }
12057     }
12058   else
12059     complaint (&symfile_complaints,
12060                _("DW_TAG_call_site DW_AT_call_target is neither "
12061                  "block nor reference, for DIE 0x%x [in module %s]"),
12062                to_underlying (die->sect_off), objfile_name (objfile));
12063
12064   call_site->per_cu = cu->per_cu;
12065
12066   for (child_die = die->child;
12067        child_die && child_die->tag;
12068        child_die = sibling_die (child_die))
12069     {
12070       struct call_site_parameter *parameter;
12071       struct attribute *loc, *origin;
12072
12073       if (child_die->tag != DW_TAG_call_site_parameter
12074           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12075         {
12076           /* Already printed the complaint above.  */
12077           continue;
12078         }
12079
12080       gdb_assert (call_site->parameter_count < nparams);
12081       parameter = &call_site->parameter[call_site->parameter_count];
12082
12083       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12084          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12085          register is contained in DW_AT_call_value.  */
12086
12087       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12088       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12089       if (origin == NULL)
12090         {
12091           /* This was a pre-DWARF-5 GNU extension alias
12092              for DW_AT_call_parameter.  */
12093           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12094         }
12095       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12096         {
12097           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12098
12099           sect_offset sect_off
12100             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12101           if (!offset_in_cu_p (&cu->header, sect_off))
12102             {
12103               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12104                  binding can be done only inside one CU.  Such referenced DIE
12105                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12106               complaint (&symfile_complaints,
12107                          _("DW_AT_call_parameter offset is not in CU for "
12108                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12109                          to_underlying (child_die->sect_off),
12110                          objfile_name (objfile));
12111               continue;
12112             }
12113           parameter->u.param_cu_off
12114             = (cu_offset) (sect_off - cu->header.sect_off);
12115         }
12116       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12117         {
12118           complaint (&symfile_complaints,
12119                      _("No DW_FORM_block* DW_AT_location for "
12120                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12121                      to_underlying (child_die->sect_off), objfile_name (objfile));
12122           continue;
12123         }
12124       else
12125         {
12126           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12127             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12128           if (parameter->u.dwarf_reg != -1)
12129             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12130           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12131                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12132                                              &parameter->u.fb_offset))
12133             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12134           else
12135             {
12136               complaint (&symfile_complaints,
12137                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12138                            "for DW_FORM_block* DW_AT_location is supported for "
12139                            "DW_TAG_call_site child DIE 0x%x "
12140                            "[in module %s]"),
12141                          to_underlying (child_die->sect_off),
12142                          objfile_name (objfile));
12143               continue;
12144             }
12145         }
12146
12147       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12148       if (attr == NULL)
12149         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12150       if (!attr_form_is_block (attr))
12151         {
12152           complaint (&symfile_complaints,
12153                      _("No DW_FORM_block* DW_AT_call_value for "
12154                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12155                      to_underlying (child_die->sect_off),
12156                      objfile_name (objfile));
12157           continue;
12158         }
12159       parameter->value = DW_BLOCK (attr)->data;
12160       parameter->value_size = DW_BLOCK (attr)->size;
12161
12162       /* Parameters are not pre-cleared by memset above.  */
12163       parameter->data_value = NULL;
12164       parameter->data_value_size = 0;
12165       call_site->parameter_count++;
12166
12167       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12168       if (attr == NULL)
12169         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12170       if (attr)
12171         {
12172           if (!attr_form_is_block (attr))
12173             complaint (&symfile_complaints,
12174                        _("No DW_FORM_block* DW_AT_call_data_value for "
12175                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12176                        to_underlying (child_die->sect_off),
12177                        objfile_name (objfile));
12178           else
12179             {
12180               parameter->data_value = DW_BLOCK (attr)->data;
12181               parameter->data_value_size = DW_BLOCK (attr)->size;
12182             }
12183         }
12184     }
12185 }
12186
12187 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12188    reading .debug_rnglists.
12189    Callback's type should be:
12190     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12191    Return true if the attributes are present and valid, otherwise,
12192    return false.  */
12193
12194 template <typename Callback>
12195 static bool
12196 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12197                          Callback &&callback)
12198 {
12199   struct objfile *objfile = cu->objfile;
12200   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12201   struct comp_unit_head *cu_header = &cu->header;
12202   bfd *obfd = objfile->obfd;
12203   unsigned int addr_size = cu_header->addr_size;
12204   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12205   /* Base address selection entry.  */
12206   CORE_ADDR base;
12207   int found_base;
12208   unsigned int dummy;
12209   const gdb_byte *buffer;
12210   CORE_ADDR low = 0;
12211   CORE_ADDR high = 0;
12212   CORE_ADDR baseaddr;
12213   bool overflow = false;
12214
12215   found_base = cu->base_known;
12216   base = cu->base_address;
12217
12218   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12219   if (offset >= dwarf2_per_objfile->rnglists.size)
12220     {
12221       complaint (&symfile_complaints,
12222                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12223                  offset);
12224       return false;
12225     }
12226   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12227
12228   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12229
12230   while (1)
12231     {
12232       /* Initialize it due to a false compiler warning.  */
12233       CORE_ADDR range_beginning = 0, range_end = 0;
12234       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12235                                  + dwarf2_per_objfile->rnglists.size);
12236       unsigned int bytes_read;
12237
12238       if (buffer == buf_end)
12239         {
12240           overflow = true;
12241           break;
12242         }
12243       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12244       switch (rlet)
12245         {
12246         case DW_RLE_end_of_list:
12247           break;
12248         case DW_RLE_base_address:
12249           if (buffer + cu->header.addr_size > buf_end)
12250             {
12251               overflow = true;
12252               break;
12253             }
12254           base = read_address (obfd, buffer, cu, &bytes_read);
12255           found_base = 1;
12256           buffer += bytes_read;
12257           break;
12258         case DW_RLE_start_length:
12259           if (buffer + cu->header.addr_size > buf_end)
12260             {
12261               overflow = true;
12262               break;
12263             }
12264           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12265           buffer += bytes_read;
12266           range_end = (range_beginning
12267                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12268           buffer += bytes_read;
12269           if (buffer > buf_end)
12270             {
12271               overflow = true;
12272               break;
12273             }
12274           break;
12275         case DW_RLE_offset_pair:
12276           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12277           buffer += bytes_read;
12278           if (buffer > buf_end)
12279             {
12280               overflow = true;
12281               break;
12282             }
12283           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12284           buffer += bytes_read;
12285           if (buffer > buf_end)
12286             {
12287               overflow = true;
12288               break;
12289             }
12290           break;
12291         case DW_RLE_start_end:
12292           if (buffer + 2 * cu->header.addr_size > buf_end)
12293             {
12294               overflow = true;
12295               break;
12296             }
12297           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12298           buffer += bytes_read;
12299           range_end = read_address (obfd, buffer, cu, &bytes_read);
12300           buffer += bytes_read;
12301           break;
12302         default:
12303           complaint (&symfile_complaints,
12304                      _("Invalid .debug_rnglists data (no base address)"));
12305           return false;
12306         }
12307       if (rlet == DW_RLE_end_of_list || overflow)
12308         break;
12309       if (rlet == DW_RLE_base_address)
12310         continue;
12311
12312       if (!found_base)
12313         {
12314           /* We have no valid base address for the ranges
12315              data.  */
12316           complaint (&symfile_complaints,
12317                      _("Invalid .debug_rnglists data (no base address)"));
12318           return false;
12319         }
12320
12321       if (range_beginning > range_end)
12322         {
12323           /* Inverted range entries are invalid.  */
12324           complaint (&symfile_complaints,
12325                      _("Invalid .debug_rnglists data (inverted range)"));
12326           return false;
12327         }
12328
12329       /* Empty range entries have no effect.  */
12330       if (range_beginning == range_end)
12331         continue;
12332
12333       range_beginning += base;
12334       range_end += base;
12335
12336       /* A not-uncommon case of bad debug info.
12337          Don't pollute the addrmap with bad data.  */
12338       if (range_beginning + baseaddr == 0
12339           && !dwarf2_per_objfile->has_section_at_zero)
12340         {
12341           complaint (&symfile_complaints,
12342                      _(".debug_rnglists entry has start address of zero"
12343                        " [in module %s]"), objfile_name (objfile));
12344           continue;
12345         }
12346
12347       callback (range_beginning, range_end);
12348     }
12349
12350   if (overflow)
12351     {
12352       complaint (&symfile_complaints,
12353                  _("Offset %d is not terminated "
12354                    "for DW_AT_ranges attribute"),
12355                  offset);
12356       return false;
12357     }
12358
12359   return true;
12360 }
12361
12362 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12363    Callback's type should be:
12364     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12365    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12366
12367 template <typename Callback>
12368 static int
12369 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12370                        Callback &&callback)
12371 {
12372   struct objfile *objfile = cu->objfile;
12373   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12374   struct comp_unit_head *cu_header = &cu->header;
12375   bfd *obfd = objfile->obfd;
12376   unsigned int addr_size = cu_header->addr_size;
12377   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12378   /* Base address selection entry.  */
12379   CORE_ADDR base;
12380   int found_base;
12381   unsigned int dummy;
12382   const gdb_byte *buffer;
12383   CORE_ADDR baseaddr;
12384
12385   if (cu_header->version >= 5)
12386     return dwarf2_rnglists_process (offset, cu, callback);
12387
12388   found_base = cu->base_known;
12389   base = cu->base_address;
12390
12391   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12392   if (offset >= dwarf2_per_objfile->ranges.size)
12393     {
12394       complaint (&symfile_complaints,
12395                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12396                  offset);
12397       return 0;
12398     }
12399   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12400
12401   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12402
12403   while (1)
12404     {
12405       CORE_ADDR range_beginning, range_end;
12406
12407       range_beginning = read_address (obfd, buffer, cu, &dummy);
12408       buffer += addr_size;
12409       range_end = read_address (obfd, buffer, cu, &dummy);
12410       buffer += addr_size;
12411       offset += 2 * addr_size;
12412
12413       /* An end of list marker is a pair of zero addresses.  */
12414       if (range_beginning == 0 && range_end == 0)
12415         /* Found the end of list entry.  */
12416         break;
12417
12418       /* Each base address selection entry is a pair of 2 values.
12419          The first is the largest possible address, the second is
12420          the base address.  Check for a base address here.  */
12421       if ((range_beginning & mask) == mask)
12422         {
12423           /* If we found the largest possible address, then we already
12424              have the base address in range_end.  */
12425           base = range_end;
12426           found_base = 1;
12427           continue;
12428         }
12429
12430       if (!found_base)
12431         {
12432           /* We have no valid base address for the ranges
12433              data.  */
12434           complaint (&symfile_complaints,
12435                      _("Invalid .debug_ranges data (no base address)"));
12436           return 0;
12437         }
12438
12439       if (range_beginning > range_end)
12440         {
12441           /* Inverted range entries are invalid.  */
12442           complaint (&symfile_complaints,
12443                      _("Invalid .debug_ranges data (inverted range)"));
12444           return 0;
12445         }
12446
12447       /* Empty range entries have no effect.  */
12448       if (range_beginning == range_end)
12449         continue;
12450
12451       range_beginning += base;
12452       range_end += base;
12453
12454       /* A not-uncommon case of bad debug info.
12455          Don't pollute the addrmap with bad data.  */
12456       if (range_beginning + baseaddr == 0
12457           && !dwarf2_per_objfile->has_section_at_zero)
12458         {
12459           complaint (&symfile_complaints,
12460                      _(".debug_ranges entry has start address of zero"
12461                        " [in module %s]"), objfile_name (objfile));
12462           continue;
12463         }
12464
12465       callback (range_beginning, range_end);
12466     }
12467
12468   return 1;
12469 }
12470
12471 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12472    Return 1 if the attributes are present and valid, otherwise, return 0.
12473    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12474
12475 static int
12476 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12477                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12478                     struct partial_symtab *ranges_pst)
12479 {
12480   struct objfile *objfile = cu->objfile;
12481   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12482   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12483                                        SECT_OFF_TEXT (objfile));
12484   int low_set = 0;
12485   CORE_ADDR low = 0;
12486   CORE_ADDR high = 0;
12487   int retval;
12488
12489   retval = dwarf2_ranges_process (offset, cu,
12490     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12491     {
12492       if (ranges_pst != NULL)
12493         {
12494           CORE_ADDR lowpc;
12495           CORE_ADDR highpc;
12496
12497           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12498                                               range_beginning + baseaddr);
12499           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12500                                                range_end + baseaddr);
12501           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12502                              ranges_pst);
12503         }
12504
12505       /* FIXME: This is recording everything as a low-high
12506          segment of consecutive addresses.  We should have a
12507          data structure for discontiguous block ranges
12508          instead.  */
12509       if (! low_set)
12510         {
12511           low = range_beginning;
12512           high = range_end;
12513           low_set = 1;
12514         }
12515       else
12516         {
12517           if (range_beginning < low)
12518             low = range_beginning;
12519           if (range_end > high)
12520             high = range_end;
12521         }
12522     });
12523   if (!retval)
12524     return 0;
12525
12526   if (! low_set)
12527     /* If the first entry is an end-of-list marker, the range
12528        describes an empty scope, i.e. no instructions.  */
12529     return 0;
12530
12531   if (low_return)
12532     *low_return = low;
12533   if (high_return)
12534     *high_return = high;
12535   return 1;
12536 }
12537
12538 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12539    definition for the return value.  *LOWPC and *HIGHPC are set iff
12540    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12541
12542 static enum pc_bounds_kind
12543 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12544                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12545                       struct partial_symtab *pst)
12546 {
12547   struct attribute *attr;
12548   struct attribute *attr_high;
12549   CORE_ADDR low = 0;
12550   CORE_ADDR high = 0;
12551   enum pc_bounds_kind ret;
12552
12553   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12554   if (attr_high)
12555     {
12556       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12557       if (attr)
12558         {
12559           low = attr_value_as_address (attr);
12560           high = attr_value_as_address (attr_high);
12561           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12562             high += low;
12563         }
12564       else
12565         /* Found high w/o low attribute.  */
12566         return PC_BOUNDS_INVALID;
12567
12568       /* Found consecutive range of addresses.  */
12569       ret = PC_BOUNDS_HIGH_LOW;
12570     }
12571   else
12572     {
12573       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12574       if (attr != NULL)
12575         {
12576           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12577              We take advantage of the fact that DW_AT_ranges does not appear
12578              in DW_TAG_compile_unit of DWO files.  */
12579           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12580           unsigned int ranges_offset = (DW_UNSND (attr)
12581                                         + (need_ranges_base
12582                                            ? cu->ranges_base
12583                                            : 0));
12584
12585           /* Value of the DW_AT_ranges attribute is the offset in the
12586              .debug_ranges section.  */
12587           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12588             return PC_BOUNDS_INVALID;
12589           /* Found discontinuous range of addresses.  */
12590           ret = PC_BOUNDS_RANGES;
12591         }
12592       else
12593         return PC_BOUNDS_NOT_PRESENT;
12594     }
12595
12596   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12597   if (high <= low)
12598     return PC_BOUNDS_INVALID;
12599
12600   /* When using the GNU linker, .gnu.linkonce. sections are used to
12601      eliminate duplicate copies of functions and vtables and such.
12602      The linker will arbitrarily choose one and discard the others.
12603      The AT_*_pc values for such functions refer to local labels in
12604      these sections.  If the section from that file was discarded, the
12605      labels are not in the output, so the relocs get a value of 0.
12606      If this is a discarded function, mark the pc bounds as invalid,
12607      so that GDB will ignore it.  */
12608   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12609     return PC_BOUNDS_INVALID;
12610
12611   *lowpc = low;
12612   if (highpc)
12613     *highpc = high;
12614   return ret;
12615 }
12616
12617 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12618    its low and high PC addresses.  Do nothing if these addresses could not
12619    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12620    and HIGHPC to the high address if greater than HIGHPC.  */
12621
12622 static void
12623 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12624                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12625                                  struct dwarf2_cu *cu)
12626 {
12627   CORE_ADDR low, high;
12628   struct die_info *child = die->child;
12629
12630   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12631     {
12632       *lowpc = std::min (*lowpc, low);
12633       *highpc = std::max (*highpc, high);
12634     }
12635
12636   /* If the language does not allow nested subprograms (either inside
12637      subprograms or lexical blocks), we're done.  */
12638   if (cu->language != language_ada)
12639     return;
12640
12641   /* Check all the children of the given DIE.  If it contains nested
12642      subprograms, then check their pc bounds.  Likewise, we need to
12643      check lexical blocks as well, as they may also contain subprogram
12644      definitions.  */
12645   while (child && child->tag)
12646     {
12647       if (child->tag == DW_TAG_subprogram
12648           || child->tag == DW_TAG_lexical_block)
12649         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12650       child = sibling_die (child);
12651     }
12652 }
12653
12654 /* Get the low and high pc's represented by the scope DIE, and store
12655    them in *LOWPC and *HIGHPC.  If the correct values can't be
12656    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12657
12658 static void
12659 get_scope_pc_bounds (struct die_info *die,
12660                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12661                      struct dwarf2_cu *cu)
12662 {
12663   CORE_ADDR best_low = (CORE_ADDR) -1;
12664   CORE_ADDR best_high = (CORE_ADDR) 0;
12665   CORE_ADDR current_low, current_high;
12666
12667   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12668       >= PC_BOUNDS_RANGES)
12669     {
12670       best_low = current_low;
12671       best_high = current_high;
12672     }
12673   else
12674     {
12675       struct die_info *child = die->child;
12676
12677       while (child && child->tag)
12678         {
12679           switch (child->tag) {
12680           case DW_TAG_subprogram:
12681             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12682             break;
12683           case DW_TAG_namespace:
12684           case DW_TAG_module:
12685             /* FIXME: carlton/2004-01-16: Should we do this for
12686                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12687                that current GCC's always emit the DIEs corresponding
12688                to definitions of methods of classes as children of a
12689                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12690                the DIEs giving the declarations, which could be
12691                anywhere).  But I don't see any reason why the
12692                standards says that they have to be there.  */
12693             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12694
12695             if (current_low != ((CORE_ADDR) -1))
12696               {
12697                 best_low = std::min (best_low, current_low);
12698                 best_high = std::max (best_high, current_high);
12699               }
12700             break;
12701           default:
12702             /* Ignore.  */
12703             break;
12704           }
12705
12706           child = sibling_die (child);
12707         }
12708     }
12709
12710   *lowpc = best_low;
12711   *highpc = best_high;
12712 }
12713
12714 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12715    in DIE.  */
12716
12717 static void
12718 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12719                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12720 {
12721   struct objfile *objfile = cu->objfile;
12722   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12723   struct attribute *attr;
12724   struct attribute *attr_high;
12725
12726   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12727   if (attr_high)
12728     {
12729       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12730       if (attr)
12731         {
12732           CORE_ADDR low = attr_value_as_address (attr);
12733           CORE_ADDR high = attr_value_as_address (attr_high);
12734
12735           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12736             high += low;
12737
12738           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12739           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12740           record_block_range (block, low, high - 1);
12741         }
12742     }
12743
12744   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12745   if (attr)
12746     {
12747       bfd *obfd = objfile->obfd;
12748       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12749          We take advantage of the fact that DW_AT_ranges does not appear
12750          in DW_TAG_compile_unit of DWO files.  */
12751       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12752
12753       /* The value of the DW_AT_ranges attribute is the offset of the
12754          address range list in the .debug_ranges section.  */
12755       unsigned long offset = (DW_UNSND (attr)
12756                               + (need_ranges_base ? cu->ranges_base : 0));
12757       const gdb_byte *buffer;
12758
12759       /* For some target architectures, but not others, the
12760          read_address function sign-extends the addresses it returns.
12761          To recognize base address selection entries, we need a
12762          mask.  */
12763       unsigned int addr_size = cu->header.addr_size;
12764       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12765
12766       /* The base address, to which the next pair is relative.  Note
12767          that this 'base' is a DWARF concept: most entries in a range
12768          list are relative, to reduce the number of relocs against the
12769          debugging information.  This is separate from this function's
12770          'baseaddr' argument, which GDB uses to relocate debugging
12771          information from a shared library based on the address at
12772          which the library was loaded.  */
12773       CORE_ADDR base = cu->base_address;
12774       int base_known = cu->base_known;
12775
12776       dwarf2_ranges_process (offset, cu,
12777         [&] (CORE_ADDR start, CORE_ADDR end)
12778         {
12779           start += baseaddr;
12780           end += baseaddr;
12781           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12782           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12783           record_block_range (block, start, end - 1);
12784         });
12785     }
12786 }
12787
12788 /* Check whether the producer field indicates either of GCC < 4.6, or the
12789    Intel C/C++ compiler, and cache the result in CU.  */
12790
12791 static void
12792 check_producer (struct dwarf2_cu *cu)
12793 {
12794   int major, minor;
12795
12796   if (cu->producer == NULL)
12797     {
12798       /* For unknown compilers expect their behavior is DWARF version
12799          compliant.
12800
12801          GCC started to support .debug_types sections by -gdwarf-4 since
12802          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12803          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12804          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12805          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12806     }
12807   else if (producer_is_gcc (cu->producer, &major, &minor))
12808     {
12809       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12810       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12811     }
12812   else if (producer_is_icc (cu->producer, &major, &minor))
12813     cu->producer_is_icc_lt_14 = major < 14;
12814   else
12815     {
12816       /* For other non-GCC compilers, expect their behavior is DWARF version
12817          compliant.  */
12818     }
12819
12820   cu->checked_producer = 1;
12821 }
12822
12823 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12824    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12825    during 4.6.0 experimental.  */
12826
12827 static int
12828 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12829 {
12830   if (!cu->checked_producer)
12831     check_producer (cu);
12832
12833   return cu->producer_is_gxx_lt_4_6;
12834 }
12835
12836 /* Return the default accessibility type if it is not overriden by
12837    DW_AT_accessibility.  */
12838
12839 static enum dwarf_access_attribute
12840 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12841 {
12842   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12843     {
12844       /* The default DWARF 2 accessibility for members is public, the default
12845          accessibility for inheritance is private.  */
12846
12847       if (die->tag != DW_TAG_inheritance)
12848         return DW_ACCESS_public;
12849       else
12850         return DW_ACCESS_private;
12851     }
12852   else
12853     {
12854       /* DWARF 3+ defines the default accessibility a different way.  The same
12855          rules apply now for DW_TAG_inheritance as for the members and it only
12856          depends on the container kind.  */
12857
12858       if (die->parent->tag == DW_TAG_class_type)
12859         return DW_ACCESS_private;
12860       else
12861         return DW_ACCESS_public;
12862     }
12863 }
12864
12865 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12866    offset.  If the attribute was not found return 0, otherwise return
12867    1.  If it was found but could not properly be handled, set *OFFSET
12868    to 0.  */
12869
12870 static int
12871 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12872                              LONGEST *offset)
12873 {
12874   struct attribute *attr;
12875
12876   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12877   if (attr != NULL)
12878     {
12879       *offset = 0;
12880
12881       /* Note that we do not check for a section offset first here.
12882          This is because DW_AT_data_member_location is new in DWARF 4,
12883          so if we see it, we can assume that a constant form is really
12884          a constant and not a section offset.  */
12885       if (attr_form_is_constant (attr))
12886         *offset = dwarf2_get_attr_constant_value (attr, 0);
12887       else if (attr_form_is_section_offset (attr))
12888         dwarf2_complex_location_expr_complaint ();
12889       else if (attr_form_is_block (attr))
12890         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12891       else
12892         dwarf2_complex_location_expr_complaint ();
12893
12894       return 1;
12895     }
12896
12897   return 0;
12898 }
12899
12900 /* Add an aggregate field to the field list.  */
12901
12902 static void
12903 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12904                   struct dwarf2_cu *cu)
12905 {
12906   struct objfile *objfile = cu->objfile;
12907   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12908   struct nextfield *new_field;
12909   struct attribute *attr;
12910   struct field *fp;
12911   const char *fieldname = "";
12912
12913   /* Allocate a new field list entry and link it in.  */
12914   new_field = XNEW (struct nextfield);
12915   make_cleanup (xfree, new_field);
12916   memset (new_field, 0, sizeof (struct nextfield));
12917
12918   if (die->tag == DW_TAG_inheritance)
12919     {
12920       new_field->next = fip->baseclasses;
12921       fip->baseclasses = new_field;
12922     }
12923   else
12924     {
12925       new_field->next = fip->fields;
12926       fip->fields = new_field;
12927     }
12928   fip->nfields++;
12929
12930   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12931   if (attr)
12932     new_field->accessibility = DW_UNSND (attr);
12933   else
12934     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12935   if (new_field->accessibility != DW_ACCESS_public)
12936     fip->non_public_fields = 1;
12937
12938   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12939   if (attr)
12940     new_field->virtuality = DW_UNSND (attr);
12941   else
12942     new_field->virtuality = DW_VIRTUALITY_none;
12943
12944   fp = &new_field->field;
12945
12946   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12947     {
12948       LONGEST offset;
12949
12950       /* Data member other than a C++ static data member.  */
12951
12952       /* Get type of field.  */
12953       fp->type = die_type (die, cu);
12954
12955       SET_FIELD_BITPOS (*fp, 0);
12956
12957       /* Get bit size of field (zero if none).  */
12958       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12959       if (attr)
12960         {
12961           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12962         }
12963       else
12964         {
12965           FIELD_BITSIZE (*fp) = 0;
12966         }
12967
12968       /* Get bit offset of field.  */
12969       if (handle_data_member_location (die, cu, &offset))
12970         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12971       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12972       if (attr)
12973         {
12974           if (gdbarch_bits_big_endian (gdbarch))
12975             {
12976               /* For big endian bits, the DW_AT_bit_offset gives the
12977                  additional bit offset from the MSB of the containing
12978                  anonymous object to the MSB of the field.  We don't
12979                  have to do anything special since we don't need to
12980                  know the size of the anonymous object.  */
12981               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12982             }
12983           else
12984             {
12985               /* For little endian bits, compute the bit offset to the
12986                  MSB of the anonymous object, subtract off the number of
12987                  bits from the MSB of the field to the MSB of the
12988                  object, and then subtract off the number of bits of
12989                  the field itself.  The result is the bit offset of
12990                  the LSB of the field.  */
12991               int anonymous_size;
12992               int bit_offset = DW_UNSND (attr);
12993
12994               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12995               if (attr)
12996                 {
12997                   /* The size of the anonymous object containing
12998                      the bit field is explicit, so use the
12999                      indicated size (in bytes).  */
13000                   anonymous_size = DW_UNSND (attr);
13001                 }
13002               else
13003                 {
13004                   /* The size of the anonymous object containing
13005                      the bit field must be inferred from the type
13006                      attribute of the data member containing the
13007                      bit field.  */
13008                   anonymous_size = TYPE_LENGTH (fp->type);
13009                 }
13010               SET_FIELD_BITPOS (*fp,
13011                                 (FIELD_BITPOS (*fp)
13012                                  + anonymous_size * bits_per_byte
13013                                  - bit_offset - FIELD_BITSIZE (*fp)));
13014             }
13015         }
13016       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13017       if (attr != NULL)
13018         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13019                                 + dwarf2_get_attr_constant_value (attr, 0)));
13020
13021       /* Get name of field.  */
13022       fieldname = dwarf2_name (die, cu);
13023       if (fieldname == NULL)
13024         fieldname = "";
13025
13026       /* The name is already allocated along with this objfile, so we don't
13027          need to duplicate it for the type.  */
13028       fp->name = fieldname;
13029
13030       /* Change accessibility for artificial fields (e.g. virtual table
13031          pointer or virtual base class pointer) to private.  */
13032       if (dwarf2_attr (die, DW_AT_artificial, cu))
13033         {
13034           FIELD_ARTIFICIAL (*fp) = 1;
13035           new_field->accessibility = DW_ACCESS_private;
13036           fip->non_public_fields = 1;
13037         }
13038     }
13039   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13040     {
13041       /* C++ static member.  */
13042
13043       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13044          is a declaration, but all versions of G++ as of this writing
13045          (so through at least 3.2.1) incorrectly generate
13046          DW_TAG_variable tags.  */
13047
13048       const char *physname;
13049
13050       /* Get name of field.  */
13051       fieldname = dwarf2_name (die, cu);
13052       if (fieldname == NULL)
13053         return;
13054
13055       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13056       if (attr
13057           /* Only create a symbol if this is an external value.
13058              new_symbol checks this and puts the value in the global symbol
13059              table, which we want.  If it is not external, new_symbol
13060              will try to put the value in cu->list_in_scope which is wrong.  */
13061           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13062         {
13063           /* A static const member, not much different than an enum as far as
13064              we're concerned, except that we can support more types.  */
13065           new_symbol (die, NULL, cu);
13066         }
13067
13068       /* Get physical name.  */
13069       physname = dwarf2_physname (fieldname, die, cu);
13070
13071       /* The name is already allocated along with this objfile, so we don't
13072          need to duplicate it for the type.  */
13073       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13074       FIELD_TYPE (*fp) = die_type (die, cu);
13075       FIELD_NAME (*fp) = fieldname;
13076     }
13077   else if (die->tag == DW_TAG_inheritance)
13078     {
13079       LONGEST offset;
13080
13081       /* C++ base class field.  */
13082       if (handle_data_member_location (die, cu, &offset))
13083         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13084       FIELD_BITSIZE (*fp) = 0;
13085       FIELD_TYPE (*fp) = die_type (die, cu);
13086       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13087       fip->nbaseclasses++;
13088     }
13089 }
13090
13091 /* Add a typedef defined in the scope of the FIP's class.  */
13092
13093 static void
13094 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13095                     struct dwarf2_cu *cu)
13096 {
13097   struct typedef_field_list *new_field;
13098   struct typedef_field *fp;
13099
13100   /* Allocate a new field list entry and link it in.  */
13101   new_field = XCNEW (struct typedef_field_list);
13102   make_cleanup (xfree, new_field);
13103
13104   gdb_assert (die->tag == DW_TAG_typedef);
13105
13106   fp = &new_field->field;
13107
13108   /* Get name of field.  */
13109   fp->name = dwarf2_name (die, cu);
13110   if (fp->name == NULL)
13111     return;
13112
13113   fp->type = read_type_die (die, cu);
13114
13115   /* Save accessibility.  */
13116   enum dwarf_access_attribute accessibility;
13117   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13118   if (attr != NULL)
13119     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13120   else
13121     accessibility = dwarf2_default_access_attribute (die, cu);
13122   switch (accessibility)
13123     {
13124     case DW_ACCESS_public:
13125       /* The assumed value if neither private nor protected.  */
13126       break;
13127     case DW_ACCESS_private:
13128       fp->is_private = 1;
13129       break;
13130     case DW_ACCESS_protected:
13131       fp->is_protected = 1;
13132       break;
13133     default:
13134       gdb_assert_not_reached ("unexpected accessibility attribute");
13135     }
13136
13137   new_field->next = fip->typedef_field_list;
13138   fip->typedef_field_list = new_field;
13139   fip->typedef_field_list_count++;
13140 }
13141
13142 /* Create the vector of fields, and attach it to the type.  */
13143
13144 static void
13145 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13146                               struct dwarf2_cu *cu)
13147 {
13148   int nfields = fip->nfields;
13149
13150   /* Record the field count, allocate space for the array of fields,
13151      and create blank accessibility bitfields if necessary.  */
13152   TYPE_NFIELDS (type) = nfields;
13153   TYPE_FIELDS (type) = (struct field *)
13154     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13155   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13156
13157   if (fip->non_public_fields && cu->language != language_ada)
13158     {
13159       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13160
13161       TYPE_FIELD_PRIVATE_BITS (type) =
13162         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13163       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13164
13165       TYPE_FIELD_PROTECTED_BITS (type) =
13166         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13167       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13168
13169       TYPE_FIELD_IGNORE_BITS (type) =
13170         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13171       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13172     }
13173
13174   /* If the type has baseclasses, allocate and clear a bit vector for
13175      TYPE_FIELD_VIRTUAL_BITS.  */
13176   if (fip->nbaseclasses && cu->language != language_ada)
13177     {
13178       int num_bytes = B_BYTES (fip->nbaseclasses);
13179       unsigned char *pointer;
13180
13181       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13182       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13183       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13184       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13185       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13186     }
13187
13188   /* Copy the saved-up fields into the field vector.  Start from the head of
13189      the list, adding to the tail of the field array, so that they end up in
13190      the same order in the array in which they were added to the list.  */
13191   while (nfields-- > 0)
13192     {
13193       struct nextfield *fieldp;
13194
13195       if (fip->fields)
13196         {
13197           fieldp = fip->fields;
13198           fip->fields = fieldp->next;
13199         }
13200       else
13201         {
13202           fieldp = fip->baseclasses;
13203           fip->baseclasses = fieldp->next;
13204         }
13205
13206       TYPE_FIELD (type, nfields) = fieldp->field;
13207       switch (fieldp->accessibility)
13208         {
13209         case DW_ACCESS_private:
13210           if (cu->language != language_ada)
13211             SET_TYPE_FIELD_PRIVATE (type, nfields);
13212           break;
13213
13214         case DW_ACCESS_protected:
13215           if (cu->language != language_ada)
13216             SET_TYPE_FIELD_PROTECTED (type, nfields);
13217           break;
13218
13219         case DW_ACCESS_public:
13220           break;
13221
13222         default:
13223           /* Unknown accessibility.  Complain and treat it as public.  */
13224           {
13225             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13226                        fieldp->accessibility);
13227           }
13228           break;
13229         }
13230       if (nfields < fip->nbaseclasses)
13231         {
13232           switch (fieldp->virtuality)
13233             {
13234             case DW_VIRTUALITY_virtual:
13235             case DW_VIRTUALITY_pure_virtual:
13236               if (cu->language == language_ada)
13237                 error (_("unexpected virtuality in component of Ada type"));
13238               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13239               break;
13240             }
13241         }
13242     }
13243 }
13244
13245 /* Return true if this member function is a constructor, false
13246    otherwise.  */
13247
13248 static int
13249 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13250 {
13251   const char *fieldname;
13252   const char *type_name;
13253   int len;
13254
13255   if (die->parent == NULL)
13256     return 0;
13257
13258   if (die->parent->tag != DW_TAG_structure_type
13259       && die->parent->tag != DW_TAG_union_type
13260       && die->parent->tag != DW_TAG_class_type)
13261     return 0;
13262
13263   fieldname = dwarf2_name (die, cu);
13264   type_name = dwarf2_name (die->parent, cu);
13265   if (fieldname == NULL || type_name == NULL)
13266     return 0;
13267
13268   len = strlen (fieldname);
13269   return (strncmp (fieldname, type_name, len) == 0
13270           && (type_name[len] == '\0' || type_name[len] == '<'));
13271 }
13272
13273 /* Add a member function to the proper fieldlist.  */
13274
13275 static void
13276 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13277                       struct type *type, struct dwarf2_cu *cu)
13278 {
13279   struct objfile *objfile = cu->objfile;
13280   struct attribute *attr;
13281   struct fnfieldlist *flp;
13282   int i;
13283   struct fn_field *fnp;
13284   const char *fieldname;
13285   struct nextfnfield *new_fnfield;
13286   struct type *this_type;
13287   enum dwarf_access_attribute accessibility;
13288
13289   if (cu->language == language_ada)
13290     error (_("unexpected member function in Ada type"));
13291
13292   /* Get name of member function.  */
13293   fieldname = dwarf2_name (die, cu);
13294   if (fieldname == NULL)
13295     return;
13296
13297   /* Look up member function name in fieldlist.  */
13298   for (i = 0; i < fip->nfnfields; i++)
13299     {
13300       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13301         break;
13302     }
13303
13304   /* Create new list element if necessary.  */
13305   if (i < fip->nfnfields)
13306     flp = &fip->fnfieldlists[i];
13307   else
13308     {
13309       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13310         {
13311           fip->fnfieldlists = (struct fnfieldlist *)
13312             xrealloc (fip->fnfieldlists,
13313                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13314                       * sizeof (struct fnfieldlist));
13315           if (fip->nfnfields == 0)
13316             make_cleanup (free_current_contents, &fip->fnfieldlists);
13317         }
13318       flp = &fip->fnfieldlists[fip->nfnfields];
13319       flp->name = fieldname;
13320       flp->length = 0;
13321       flp->head = NULL;
13322       i = fip->nfnfields++;
13323     }
13324
13325   /* Create a new member function field and chain it to the field list
13326      entry.  */
13327   new_fnfield = XNEW (struct nextfnfield);
13328   make_cleanup (xfree, new_fnfield);
13329   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13330   new_fnfield->next = flp->head;
13331   flp->head = new_fnfield;
13332   flp->length++;
13333
13334   /* Fill in the member function field info.  */
13335   fnp = &new_fnfield->fnfield;
13336
13337   /* Delay processing of the physname until later.  */
13338   if (cu->language == language_cplus)
13339     {
13340       add_to_method_list (type, i, flp->length - 1, fieldname,
13341                           die, cu);
13342     }
13343   else
13344     {
13345       const char *physname = dwarf2_physname (fieldname, die, cu);
13346       fnp->physname = physname ? physname : "";
13347     }
13348
13349   fnp->type = alloc_type (objfile);
13350   this_type = read_type_die (die, cu);
13351   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13352     {
13353       int nparams = TYPE_NFIELDS (this_type);
13354
13355       /* TYPE is the domain of this method, and THIS_TYPE is the type
13356            of the method itself (TYPE_CODE_METHOD).  */
13357       smash_to_method_type (fnp->type, type,
13358                             TYPE_TARGET_TYPE (this_type),
13359                             TYPE_FIELDS (this_type),
13360                             TYPE_NFIELDS (this_type),
13361                             TYPE_VARARGS (this_type));
13362
13363       /* Handle static member functions.
13364          Dwarf2 has no clean way to discern C++ static and non-static
13365          member functions.  G++ helps GDB by marking the first
13366          parameter for non-static member functions (which is the this
13367          pointer) as artificial.  We obtain this information from
13368          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13369       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13370         fnp->voffset = VOFFSET_STATIC;
13371     }
13372   else
13373     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13374                dwarf2_full_name (fieldname, die, cu));
13375
13376   /* Get fcontext from DW_AT_containing_type if present.  */
13377   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13378     fnp->fcontext = die_containing_type (die, cu);
13379
13380   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13381      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13382
13383   /* Get accessibility.  */
13384   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13385   if (attr)
13386     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13387   else
13388     accessibility = dwarf2_default_access_attribute (die, cu);
13389   switch (accessibility)
13390     {
13391     case DW_ACCESS_private:
13392       fnp->is_private = 1;
13393       break;
13394     case DW_ACCESS_protected:
13395       fnp->is_protected = 1;
13396       break;
13397     }
13398
13399   /* Check for artificial methods.  */
13400   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13401   if (attr && DW_UNSND (attr) != 0)
13402     fnp->is_artificial = 1;
13403
13404   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13405
13406   /* Get index in virtual function table if it is a virtual member
13407      function.  For older versions of GCC, this is an offset in the
13408      appropriate virtual table, as specified by DW_AT_containing_type.
13409      For everyone else, it is an expression to be evaluated relative
13410      to the object address.  */
13411
13412   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13413   if (attr)
13414     {
13415       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13416         {
13417           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13418             {
13419               /* Old-style GCC.  */
13420               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13421             }
13422           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13423                    || (DW_BLOCK (attr)->size > 1
13424                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13425                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13426             {
13427               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13428               if ((fnp->voffset % cu->header.addr_size) != 0)
13429                 dwarf2_complex_location_expr_complaint ();
13430               else
13431                 fnp->voffset /= cu->header.addr_size;
13432               fnp->voffset += 2;
13433             }
13434           else
13435             dwarf2_complex_location_expr_complaint ();
13436
13437           if (!fnp->fcontext)
13438             {
13439               /* If there is no `this' field and no DW_AT_containing_type,
13440                  we cannot actually find a base class context for the
13441                  vtable!  */
13442               if (TYPE_NFIELDS (this_type) == 0
13443                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13444                 {
13445                   complaint (&symfile_complaints,
13446                              _("cannot determine context for virtual member "
13447                                "function \"%s\" (offset %d)"),
13448                              fieldname, to_underlying (die->sect_off));
13449                 }
13450               else
13451                 {
13452                   fnp->fcontext
13453                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13454                 }
13455             }
13456         }
13457       else if (attr_form_is_section_offset (attr))
13458         {
13459           dwarf2_complex_location_expr_complaint ();
13460         }
13461       else
13462         {
13463           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13464                                                  fieldname);
13465         }
13466     }
13467   else
13468     {
13469       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13470       if (attr && DW_UNSND (attr))
13471         {
13472           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13473           complaint (&symfile_complaints,
13474                      _("Member function \"%s\" (offset %d) is virtual "
13475                        "but the vtable offset is not specified"),
13476                      fieldname, to_underlying (die->sect_off));
13477           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13478           TYPE_CPLUS_DYNAMIC (type) = 1;
13479         }
13480     }
13481 }
13482
13483 /* Create the vector of member function fields, and attach it to the type.  */
13484
13485 static void
13486 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13487                                  struct dwarf2_cu *cu)
13488 {
13489   struct fnfieldlist *flp;
13490   int i;
13491
13492   if (cu->language == language_ada)
13493     error (_("unexpected member functions in Ada type"));
13494
13495   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13496   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13497     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13498
13499   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13500     {
13501       struct nextfnfield *nfp = flp->head;
13502       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13503       int k;
13504
13505       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13506       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13507       fn_flp->fn_fields = (struct fn_field *)
13508         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13509       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13510         fn_flp->fn_fields[k] = nfp->fnfield;
13511     }
13512
13513   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13514 }
13515
13516 /* Returns non-zero if NAME is the name of a vtable member in CU's
13517    language, zero otherwise.  */
13518 static int
13519 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13520 {
13521   static const char vptr[] = "_vptr";
13522   static const char vtable[] = "vtable";
13523
13524   /* Look for the C++ form of the vtable.  */
13525   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13526     return 1;
13527
13528   return 0;
13529 }
13530
13531 /* GCC outputs unnamed structures that are really pointers to member
13532    functions, with the ABI-specified layout.  If TYPE describes
13533    such a structure, smash it into a member function type.
13534
13535    GCC shouldn't do this; it should just output pointer to member DIEs.
13536    This is GCC PR debug/28767.  */
13537
13538 static void
13539 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13540 {
13541   struct type *pfn_type, *self_type, *new_type;
13542
13543   /* Check for a structure with no name and two children.  */
13544   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13545     return;
13546
13547   /* Check for __pfn and __delta members.  */
13548   if (TYPE_FIELD_NAME (type, 0) == NULL
13549       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13550       || TYPE_FIELD_NAME (type, 1) == NULL
13551       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13552     return;
13553
13554   /* Find the type of the method.  */
13555   pfn_type = TYPE_FIELD_TYPE (type, 0);
13556   if (pfn_type == NULL
13557       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13558       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13559     return;
13560
13561   /* Look for the "this" argument.  */
13562   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13563   if (TYPE_NFIELDS (pfn_type) == 0
13564       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13565       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13566     return;
13567
13568   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13569   new_type = alloc_type (objfile);
13570   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13571                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13572                         TYPE_VARARGS (pfn_type));
13573   smash_to_methodptr_type (type, new_type);
13574 }
13575
13576
13577 /* Called when we find the DIE that starts a structure or union scope
13578    (definition) to create a type for the structure or union.  Fill in
13579    the type's name and general properties; the members will not be
13580    processed until process_structure_scope.  A symbol table entry for
13581    the type will also not be done until process_structure_scope (assuming
13582    the type has a name).
13583
13584    NOTE: we need to call these functions regardless of whether or not the
13585    DIE has a DW_AT_name attribute, since it might be an anonymous
13586    structure or union.  This gets the type entered into our set of
13587    user defined types.  */
13588
13589 static struct type *
13590 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13591 {
13592   struct objfile *objfile = cu->objfile;
13593   struct type *type;
13594   struct attribute *attr;
13595   const char *name;
13596
13597   /* If the definition of this type lives in .debug_types, read that type.
13598      Don't follow DW_AT_specification though, that will take us back up
13599      the chain and we want to go down.  */
13600   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13601   if (attr)
13602     {
13603       type = get_DW_AT_signature_type (die, attr, cu);
13604
13605       /* The type's CU may not be the same as CU.
13606          Ensure TYPE is recorded with CU in die_type_hash.  */
13607       return set_die_type (die, type, cu);
13608     }
13609
13610   type = alloc_type (objfile);
13611   INIT_CPLUS_SPECIFIC (type);
13612
13613   name = dwarf2_name (die, cu);
13614   if (name != NULL)
13615     {
13616       if (cu->language == language_cplus
13617           || cu->language == language_d
13618           || cu->language == language_rust)
13619         {
13620           const char *full_name = dwarf2_full_name (name, die, cu);
13621
13622           /* dwarf2_full_name might have already finished building the DIE's
13623              type.  If so, there is no need to continue.  */
13624           if (get_die_type (die, cu) != NULL)
13625             return get_die_type (die, cu);
13626
13627           TYPE_TAG_NAME (type) = full_name;
13628           if (die->tag == DW_TAG_structure_type
13629               || die->tag == DW_TAG_class_type)
13630             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13631         }
13632       else
13633         {
13634           /* The name is already allocated along with this objfile, so
13635              we don't need to duplicate it for the type.  */
13636           TYPE_TAG_NAME (type) = name;
13637           if (die->tag == DW_TAG_class_type)
13638             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13639         }
13640     }
13641
13642   if (die->tag == DW_TAG_structure_type)
13643     {
13644       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13645     }
13646   else if (die->tag == DW_TAG_union_type)
13647     {
13648       TYPE_CODE (type) = TYPE_CODE_UNION;
13649     }
13650   else
13651     {
13652       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13653     }
13654
13655   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13656     TYPE_DECLARED_CLASS (type) = 1;
13657
13658   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13659   if (attr)
13660     {
13661       if (attr_form_is_constant (attr))
13662         TYPE_LENGTH (type) = DW_UNSND (attr);
13663       else
13664         {
13665           /* For the moment, dynamic type sizes are not supported
13666              by GDB's struct type.  The actual size is determined
13667              on-demand when resolving the type of a given object,
13668              so set the type's length to zero for now.  Otherwise,
13669              we record an expression as the length, and that expression
13670              could lead to a very large value, which could eventually
13671              lead to us trying to allocate that much memory when creating
13672              a value of that type.  */
13673           TYPE_LENGTH (type) = 0;
13674         }
13675     }
13676   else
13677     {
13678       TYPE_LENGTH (type) = 0;
13679     }
13680
13681   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
13682     {
13683       /* ICC<14 does not output the required DW_AT_declaration on
13684          incomplete types, but gives them a size of zero.  */
13685       TYPE_STUB (type) = 1;
13686     }
13687   else
13688     TYPE_STUB_SUPPORTED (type) = 1;
13689
13690   if (die_is_declaration (die, cu))
13691     TYPE_STUB (type) = 1;
13692   else if (attr == NULL && die->child == NULL
13693            && producer_is_realview (cu->producer))
13694     /* RealView does not output the required DW_AT_declaration
13695        on incomplete types.  */
13696     TYPE_STUB (type) = 1;
13697
13698   /* We need to add the type field to the die immediately so we don't
13699      infinitely recurse when dealing with pointers to the structure
13700      type within the structure itself.  */
13701   set_die_type (die, type, cu);
13702
13703   /* set_die_type should be already done.  */
13704   set_descriptive_type (type, die, cu);
13705
13706   return type;
13707 }
13708
13709 /* Finish creating a structure or union type, including filling in
13710    its members and creating a symbol for it.  */
13711
13712 static void
13713 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13714 {
13715   struct objfile *objfile = cu->objfile;
13716   struct die_info *child_die;
13717   struct type *type;
13718
13719   type = get_die_type (die, cu);
13720   if (type == NULL)
13721     type = read_structure_type (die, cu);
13722
13723   if (die->child != NULL && ! die_is_declaration (die, cu))
13724     {
13725       struct field_info fi;
13726       VEC (symbolp) *template_args = NULL;
13727       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13728
13729       memset (&fi, 0, sizeof (struct field_info));
13730
13731       child_die = die->child;
13732
13733       while (child_die && child_die->tag)
13734         {
13735           if (child_die->tag == DW_TAG_member
13736               || child_die->tag == DW_TAG_variable)
13737             {
13738               /* NOTE: carlton/2002-11-05: A C++ static data member
13739                  should be a DW_TAG_member that is a declaration, but
13740                  all versions of G++ as of this writing (so through at
13741                  least 3.2.1) incorrectly generate DW_TAG_variable
13742                  tags for them instead.  */
13743               dwarf2_add_field (&fi, child_die, cu);
13744             }
13745           else if (child_die->tag == DW_TAG_subprogram)
13746             {
13747               /* Rust doesn't have member functions in the C++ sense.
13748                  However, it does emit ordinary functions as children
13749                  of a struct DIE.  */
13750               if (cu->language == language_rust)
13751                 read_func_scope (child_die, cu);
13752               else
13753                 {
13754                   /* C++ member function.  */
13755                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13756                 }
13757             }
13758           else if (child_die->tag == DW_TAG_inheritance)
13759             {
13760               /* C++ base class field.  */
13761               dwarf2_add_field (&fi, child_die, cu);
13762             }
13763           else if (child_die->tag == DW_TAG_typedef)
13764             dwarf2_add_typedef (&fi, child_die, cu);
13765           else if (child_die->tag == DW_TAG_template_type_param
13766                    || child_die->tag == DW_TAG_template_value_param)
13767             {
13768               struct symbol *arg = new_symbol (child_die, NULL, cu);
13769
13770               if (arg != NULL)
13771                 VEC_safe_push (symbolp, template_args, arg);
13772             }
13773
13774           child_die = sibling_die (child_die);
13775         }
13776
13777       /* Attach template arguments to type.  */
13778       if (! VEC_empty (symbolp, template_args))
13779         {
13780           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13781           TYPE_N_TEMPLATE_ARGUMENTS (type)
13782             = VEC_length (symbolp, template_args);
13783           TYPE_TEMPLATE_ARGUMENTS (type)
13784             = XOBNEWVEC (&objfile->objfile_obstack,
13785                          struct symbol *,
13786                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13787           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13788                   VEC_address (symbolp, template_args),
13789                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13790                    * sizeof (struct symbol *)));
13791           VEC_free (symbolp, template_args);
13792         }
13793
13794       /* Attach fields and member functions to the type.  */
13795       if (fi.nfields)
13796         dwarf2_attach_fields_to_type (&fi, type, cu);
13797       if (fi.nfnfields)
13798         {
13799           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13800
13801           /* Get the type which refers to the base class (possibly this
13802              class itself) which contains the vtable pointer for the current
13803              class from the DW_AT_containing_type attribute.  This use of
13804              DW_AT_containing_type is a GNU extension.  */
13805
13806           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13807             {
13808               struct type *t = die_containing_type (die, cu);
13809
13810               set_type_vptr_basetype (type, t);
13811               if (type == t)
13812                 {
13813                   int i;
13814
13815                   /* Our own class provides vtbl ptr.  */
13816                   for (i = TYPE_NFIELDS (t) - 1;
13817                        i >= TYPE_N_BASECLASSES (t);
13818                        --i)
13819                     {
13820                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13821
13822                       if (is_vtable_name (fieldname, cu))
13823                         {
13824                           set_type_vptr_fieldno (type, i);
13825                           break;
13826                         }
13827                     }
13828
13829                   /* Complain if virtual function table field not found.  */
13830                   if (i < TYPE_N_BASECLASSES (t))
13831                     complaint (&symfile_complaints,
13832                                _("virtual function table pointer "
13833                                  "not found when defining class '%s'"),
13834                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13835                                "");
13836                 }
13837               else
13838                 {
13839                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13840                 }
13841             }
13842           else if (cu->producer
13843                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13844             {
13845               /* The IBM XLC compiler does not provide direct indication
13846                  of the containing type, but the vtable pointer is
13847                  always named __vfp.  */
13848
13849               int i;
13850
13851               for (i = TYPE_NFIELDS (type) - 1;
13852                    i >= TYPE_N_BASECLASSES (type);
13853                    --i)
13854                 {
13855                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13856                     {
13857                       set_type_vptr_fieldno (type, i);
13858                       set_type_vptr_basetype (type, type);
13859                       break;
13860                     }
13861                 }
13862             }
13863         }
13864
13865       /* Copy fi.typedef_field_list linked list elements content into the
13866          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13867       if (fi.typedef_field_list)
13868         {
13869           int i = fi.typedef_field_list_count;
13870
13871           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13872           TYPE_TYPEDEF_FIELD_ARRAY (type)
13873             = ((struct typedef_field *)
13874                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13875           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13876
13877           /* Reverse the list order to keep the debug info elements order.  */
13878           while (--i >= 0)
13879             {
13880               struct typedef_field *dest, *src;
13881
13882               dest = &TYPE_TYPEDEF_FIELD (type, i);
13883               src = &fi.typedef_field_list->field;
13884               fi.typedef_field_list = fi.typedef_field_list->next;
13885               *dest = *src;
13886             }
13887         }
13888
13889       do_cleanups (back_to);
13890     }
13891
13892   quirk_gcc_member_function_pointer (type, objfile);
13893
13894   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13895      snapshots) has been known to create a die giving a declaration
13896      for a class that has, as a child, a die giving a definition for a
13897      nested class.  So we have to process our children even if the
13898      current die is a declaration.  Normally, of course, a declaration
13899      won't have any children at all.  */
13900
13901   child_die = die->child;
13902
13903   while (child_die != NULL && child_die->tag)
13904     {
13905       if (child_die->tag == DW_TAG_member
13906           || child_die->tag == DW_TAG_variable
13907           || child_die->tag == DW_TAG_inheritance
13908           || child_die->tag == DW_TAG_template_value_param
13909           || child_die->tag == DW_TAG_template_type_param)
13910         {
13911           /* Do nothing.  */
13912         }
13913       else
13914         process_die (child_die, cu);
13915
13916       child_die = sibling_die (child_die);
13917     }
13918
13919   /* Do not consider external references.  According to the DWARF standard,
13920      these DIEs are identified by the fact that they have no byte_size
13921      attribute, and a declaration attribute.  */
13922   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13923       || !die_is_declaration (die, cu))
13924     new_symbol (die, type, cu);
13925 }
13926
13927 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13928    update TYPE using some information only available in DIE's children.  */
13929
13930 static void
13931 update_enumeration_type_from_children (struct die_info *die,
13932                                        struct type *type,
13933                                        struct dwarf2_cu *cu)
13934 {
13935   struct die_info *child_die;
13936   int unsigned_enum = 1;
13937   int flag_enum = 1;
13938   ULONGEST mask = 0;
13939
13940   auto_obstack obstack;
13941
13942   for (child_die = die->child;
13943        child_die != NULL && child_die->tag;
13944        child_die = sibling_die (child_die))
13945     {
13946       struct attribute *attr;
13947       LONGEST value;
13948       const gdb_byte *bytes;
13949       struct dwarf2_locexpr_baton *baton;
13950       const char *name;
13951
13952       if (child_die->tag != DW_TAG_enumerator)
13953         continue;
13954
13955       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13956       if (attr == NULL)
13957         continue;
13958
13959       name = dwarf2_name (child_die, cu);
13960       if (name == NULL)
13961         name = "<anonymous enumerator>";
13962
13963       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13964                                &value, &bytes, &baton);
13965       if (value < 0)
13966         {
13967           unsigned_enum = 0;
13968           flag_enum = 0;
13969         }
13970       else if ((mask & value) != 0)
13971         flag_enum = 0;
13972       else
13973         mask |= value;
13974
13975       /* If we already know that the enum type is neither unsigned, nor
13976          a flag type, no need to look at the rest of the enumerates.  */
13977       if (!unsigned_enum && !flag_enum)
13978         break;
13979     }
13980
13981   if (unsigned_enum)
13982     TYPE_UNSIGNED (type) = 1;
13983   if (flag_enum)
13984     TYPE_FLAG_ENUM (type) = 1;
13985 }
13986
13987 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13988    complete the type's fields yet, or create any symbols.  */
13989
13990 static struct type *
13991 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13992 {
13993   struct objfile *objfile = cu->objfile;
13994   struct type *type;
13995   struct attribute *attr;
13996   const char *name;
13997
13998   /* If the definition of this type lives in .debug_types, read that type.
13999      Don't follow DW_AT_specification though, that will take us back up
14000      the chain and we want to go down.  */
14001   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14002   if (attr)
14003     {
14004       type = get_DW_AT_signature_type (die, attr, cu);
14005
14006       /* The type's CU may not be the same as CU.
14007          Ensure TYPE is recorded with CU in die_type_hash.  */
14008       return set_die_type (die, type, cu);
14009     }
14010
14011   type = alloc_type (objfile);
14012
14013   TYPE_CODE (type) = TYPE_CODE_ENUM;
14014   name = dwarf2_full_name (NULL, die, cu);
14015   if (name != NULL)
14016     TYPE_TAG_NAME (type) = name;
14017
14018   attr = dwarf2_attr (die, DW_AT_type, cu);
14019   if (attr != NULL)
14020     {
14021       struct type *underlying_type = die_type (die, cu);
14022
14023       TYPE_TARGET_TYPE (type) = underlying_type;
14024     }
14025
14026   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14027   if (attr)
14028     {
14029       TYPE_LENGTH (type) = DW_UNSND (attr);
14030     }
14031   else
14032     {
14033       TYPE_LENGTH (type) = 0;
14034     }
14035
14036   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14037      declared as private in the package spec, and then defined only
14038      inside the package body.  Such types are known as Taft Amendment
14039      Types.  When another package uses such a type, an incomplete DIE
14040      may be generated by the compiler.  */
14041   if (die_is_declaration (die, cu))
14042     TYPE_STUB (type) = 1;
14043
14044   /* Finish the creation of this type by using the enum's children.
14045      We must call this even when the underlying type has been provided
14046      so that we can determine if we're looking at a "flag" enum.  */
14047   update_enumeration_type_from_children (die, type, cu);
14048
14049   /* If this type has an underlying type that is not a stub, then we
14050      may use its attributes.  We always use the "unsigned" attribute
14051      in this situation, because ordinarily we guess whether the type
14052      is unsigned -- but the guess can be wrong and the underlying type
14053      can tell us the reality.  However, we defer to a local size
14054      attribute if one exists, because this lets the compiler override
14055      the underlying type if needed.  */
14056   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14057     {
14058       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14059       if (TYPE_LENGTH (type) == 0)
14060         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14061     }
14062
14063   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14064
14065   return set_die_type (die, type, cu);
14066 }
14067
14068 /* Given a pointer to a die which begins an enumeration, process all
14069    the dies that define the members of the enumeration, and create the
14070    symbol for the enumeration type.
14071
14072    NOTE: We reverse the order of the element list.  */
14073
14074 static void
14075 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14076 {
14077   struct type *this_type;
14078
14079   this_type = get_die_type (die, cu);
14080   if (this_type == NULL)
14081     this_type = read_enumeration_type (die, cu);
14082
14083   if (die->child != NULL)
14084     {
14085       struct die_info *child_die;
14086       struct symbol *sym;
14087       struct field *fields = NULL;
14088       int num_fields = 0;
14089       const char *name;
14090
14091       child_die = die->child;
14092       while (child_die && child_die->tag)
14093         {
14094           if (child_die->tag != DW_TAG_enumerator)
14095             {
14096               process_die (child_die, cu);
14097             }
14098           else
14099             {
14100               name = dwarf2_name (child_die, cu);
14101               if (name)
14102                 {
14103                   sym = new_symbol (child_die, this_type, cu);
14104
14105                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14106                     {
14107                       fields = (struct field *)
14108                         xrealloc (fields,
14109                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14110                                   * sizeof (struct field));
14111                     }
14112
14113                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14114                   FIELD_TYPE (fields[num_fields]) = NULL;
14115                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14116                   FIELD_BITSIZE (fields[num_fields]) = 0;
14117
14118                   num_fields++;
14119                 }
14120             }
14121
14122           child_die = sibling_die (child_die);
14123         }
14124
14125       if (num_fields)
14126         {
14127           TYPE_NFIELDS (this_type) = num_fields;
14128           TYPE_FIELDS (this_type) = (struct field *)
14129             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14130           memcpy (TYPE_FIELDS (this_type), fields,
14131                   sizeof (struct field) * num_fields);
14132           xfree (fields);
14133         }
14134     }
14135
14136   /* If we are reading an enum from a .debug_types unit, and the enum
14137      is a declaration, and the enum is not the signatured type in the
14138      unit, then we do not want to add a symbol for it.  Adding a
14139      symbol would in some cases obscure the true definition of the
14140      enum, giving users an incomplete type when the definition is
14141      actually available.  Note that we do not want to do this for all
14142      enums which are just declarations, because C++0x allows forward
14143      enum declarations.  */
14144   if (cu->per_cu->is_debug_types
14145       && die_is_declaration (die, cu))
14146     {
14147       struct signatured_type *sig_type;
14148
14149       sig_type = (struct signatured_type *) cu->per_cu;
14150       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14151       if (sig_type->type_offset_in_section != die->sect_off)
14152         return;
14153     }
14154
14155   new_symbol (die, this_type, cu);
14156 }
14157
14158 /* Extract all information from a DW_TAG_array_type DIE and put it in
14159    the DIE's type field.  For now, this only handles one dimensional
14160    arrays.  */
14161
14162 static struct type *
14163 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14164 {
14165   struct objfile *objfile = cu->objfile;
14166   struct die_info *child_die;
14167   struct type *type;
14168   struct type *element_type, *range_type, *index_type;
14169   struct attribute *attr;
14170   const char *name;
14171   unsigned int bit_stride = 0;
14172
14173   element_type = die_type (die, cu);
14174
14175   /* The die_type call above may have already set the type for this DIE.  */
14176   type = get_die_type (die, cu);
14177   if (type)
14178     return type;
14179
14180   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14181   if (attr != NULL)
14182     bit_stride = DW_UNSND (attr) * 8;
14183
14184   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14185   if (attr != NULL)
14186     bit_stride = DW_UNSND (attr);
14187
14188   /* Irix 6.2 native cc creates array types without children for
14189      arrays with unspecified length.  */
14190   if (die->child == NULL)
14191     {
14192       index_type = objfile_type (objfile)->builtin_int;
14193       range_type = create_static_range_type (NULL, index_type, 0, -1);
14194       type = create_array_type_with_stride (NULL, element_type, range_type,
14195                                             bit_stride);
14196       return set_die_type (die, type, cu);
14197     }
14198
14199   std::vector<struct type *> range_types;
14200   child_die = die->child;
14201   while (child_die && child_die->tag)
14202     {
14203       if (child_die->tag == DW_TAG_subrange_type)
14204         {
14205           struct type *child_type = read_type_die (child_die, cu);
14206
14207           if (child_type != NULL)
14208             {
14209               /* The range type was succesfully read.  Save it for the
14210                  array type creation.  */
14211               range_types.push_back (child_type);
14212             }
14213         }
14214       child_die = sibling_die (child_die);
14215     }
14216
14217   /* Dwarf2 dimensions are output from left to right, create the
14218      necessary array types in backwards order.  */
14219
14220   type = element_type;
14221
14222   if (read_array_order (die, cu) == DW_ORD_col_major)
14223     {
14224       int i = 0;
14225
14226       while (i < range_types.size ())
14227         type = create_array_type_with_stride (NULL, type, range_types[i++],
14228                                               bit_stride);
14229     }
14230   else
14231     {
14232       size_t ndim = range_types.size ();
14233       while (ndim-- > 0)
14234         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14235                                               bit_stride);
14236     }
14237
14238   /* Understand Dwarf2 support for vector types (like they occur on
14239      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14240      array type.  This is not part of the Dwarf2/3 standard yet, but a
14241      custom vendor extension.  The main difference between a regular
14242      array and the vector variant is that vectors are passed by value
14243      to functions.  */
14244   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14245   if (attr)
14246     make_vector_type (type);
14247
14248   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14249      implementation may choose to implement triple vectors using this
14250      attribute.  */
14251   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14252   if (attr)
14253     {
14254       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14255         TYPE_LENGTH (type) = DW_UNSND (attr);
14256       else
14257         complaint (&symfile_complaints,
14258                    _("DW_AT_byte_size for array type smaller "
14259                      "than the total size of elements"));
14260     }
14261
14262   name = dwarf2_name (die, cu);
14263   if (name)
14264     TYPE_NAME (type) = name;
14265
14266   /* Install the type in the die.  */
14267   set_die_type (die, type, cu);
14268
14269   /* set_die_type should be already done.  */
14270   set_descriptive_type (type, die, cu);
14271
14272   return type;
14273 }
14274
14275 static enum dwarf_array_dim_ordering
14276 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14277 {
14278   struct attribute *attr;
14279
14280   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14281
14282   if (attr)
14283     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14284
14285   /* GNU F77 is a special case, as at 08/2004 array type info is the
14286      opposite order to the dwarf2 specification, but data is still
14287      laid out as per normal fortran.
14288
14289      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14290      version checking.  */
14291
14292   if (cu->language == language_fortran
14293       && cu->producer && strstr (cu->producer, "GNU F77"))
14294     {
14295       return DW_ORD_row_major;
14296     }
14297
14298   switch (cu->language_defn->la_array_ordering)
14299     {
14300     case array_column_major:
14301       return DW_ORD_col_major;
14302     case array_row_major:
14303     default:
14304       return DW_ORD_row_major;
14305     };
14306 }
14307
14308 /* Extract all information from a DW_TAG_set_type DIE and put it in
14309    the DIE's type field.  */
14310
14311 static struct type *
14312 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14313 {
14314   struct type *domain_type, *set_type;
14315   struct attribute *attr;
14316
14317   domain_type = die_type (die, cu);
14318
14319   /* The die_type call above may have already set the type for this DIE.  */
14320   set_type = get_die_type (die, cu);
14321   if (set_type)
14322     return set_type;
14323
14324   set_type = create_set_type (NULL, domain_type);
14325
14326   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14327   if (attr)
14328     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14329
14330   return set_die_type (die, set_type, cu);
14331 }
14332
14333 /* A helper for read_common_block that creates a locexpr baton.
14334    SYM is the symbol which we are marking as computed.
14335    COMMON_DIE is the DIE for the common block.
14336    COMMON_LOC is the location expression attribute for the common
14337    block itself.
14338    MEMBER_LOC is the location expression attribute for the particular
14339    member of the common block that we are processing.
14340    CU is the CU from which the above come.  */
14341
14342 static void
14343 mark_common_block_symbol_computed (struct symbol *sym,
14344                                    struct die_info *common_die,
14345                                    struct attribute *common_loc,
14346                                    struct attribute *member_loc,
14347                                    struct dwarf2_cu *cu)
14348 {
14349   struct objfile *objfile = dwarf2_per_objfile->objfile;
14350   struct dwarf2_locexpr_baton *baton;
14351   gdb_byte *ptr;
14352   unsigned int cu_off;
14353   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14354   LONGEST offset = 0;
14355
14356   gdb_assert (common_loc && member_loc);
14357   gdb_assert (attr_form_is_block (common_loc));
14358   gdb_assert (attr_form_is_block (member_loc)
14359               || attr_form_is_constant (member_loc));
14360
14361   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14362   baton->per_cu = cu->per_cu;
14363   gdb_assert (baton->per_cu);
14364
14365   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14366
14367   if (attr_form_is_constant (member_loc))
14368     {
14369       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14370       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14371     }
14372   else
14373     baton->size += DW_BLOCK (member_loc)->size;
14374
14375   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14376   baton->data = ptr;
14377
14378   *ptr++ = DW_OP_call4;
14379   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14380   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14381   ptr += 4;
14382
14383   if (attr_form_is_constant (member_loc))
14384     {
14385       *ptr++ = DW_OP_addr;
14386       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14387       ptr += cu->header.addr_size;
14388     }
14389   else
14390     {
14391       /* We have to copy the data here, because DW_OP_call4 will only
14392          use a DW_AT_location attribute.  */
14393       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14394       ptr += DW_BLOCK (member_loc)->size;
14395     }
14396
14397   *ptr++ = DW_OP_plus;
14398   gdb_assert (ptr - baton->data == baton->size);
14399
14400   SYMBOL_LOCATION_BATON (sym) = baton;
14401   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14402 }
14403
14404 /* Create appropriate locally-scoped variables for all the
14405    DW_TAG_common_block entries.  Also create a struct common_block
14406    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14407    is used to sepate the common blocks name namespace from regular
14408    variable names.  */
14409
14410 static void
14411 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14412 {
14413   struct attribute *attr;
14414
14415   attr = dwarf2_attr (die, DW_AT_location, cu);
14416   if (attr)
14417     {
14418       /* Support the .debug_loc offsets.  */
14419       if (attr_form_is_block (attr))
14420         {
14421           /* Ok.  */
14422         }
14423       else if (attr_form_is_section_offset (attr))
14424         {
14425           dwarf2_complex_location_expr_complaint ();
14426           attr = NULL;
14427         }
14428       else
14429         {
14430           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14431                                                  "common block member");
14432           attr = NULL;
14433         }
14434     }
14435
14436   if (die->child != NULL)
14437     {
14438       struct objfile *objfile = cu->objfile;
14439       struct die_info *child_die;
14440       size_t n_entries = 0, size;
14441       struct common_block *common_block;
14442       struct symbol *sym;
14443
14444       for (child_die = die->child;
14445            child_die && child_die->tag;
14446            child_die = sibling_die (child_die))
14447         ++n_entries;
14448
14449       size = (sizeof (struct common_block)
14450               + (n_entries - 1) * sizeof (struct symbol *));
14451       common_block
14452         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14453                                                  size);
14454       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14455       common_block->n_entries = 0;
14456
14457       for (child_die = die->child;
14458            child_die && child_die->tag;
14459            child_die = sibling_die (child_die))
14460         {
14461           /* Create the symbol in the DW_TAG_common_block block in the current
14462              symbol scope.  */
14463           sym = new_symbol (child_die, NULL, cu);
14464           if (sym != NULL)
14465             {
14466               struct attribute *member_loc;
14467
14468               common_block->contents[common_block->n_entries++] = sym;
14469
14470               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14471                                         cu);
14472               if (member_loc)
14473                 {
14474                   /* GDB has handled this for a long time, but it is
14475                      not specified by DWARF.  It seems to have been
14476                      emitted by gfortran at least as recently as:
14477                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14478                   complaint (&symfile_complaints,
14479                              _("Variable in common block has "
14480                                "DW_AT_data_member_location "
14481                                "- DIE at 0x%x [in module %s]"),
14482                              to_underlying (child_die->sect_off),
14483                              objfile_name (cu->objfile));
14484
14485                   if (attr_form_is_section_offset (member_loc))
14486                     dwarf2_complex_location_expr_complaint ();
14487                   else if (attr_form_is_constant (member_loc)
14488                            || attr_form_is_block (member_loc))
14489                     {
14490                       if (attr)
14491                         mark_common_block_symbol_computed (sym, die, attr,
14492                                                            member_loc, cu);
14493                     }
14494                   else
14495                     dwarf2_complex_location_expr_complaint ();
14496                 }
14497             }
14498         }
14499
14500       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14501       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14502     }
14503 }
14504
14505 /* Create a type for a C++ namespace.  */
14506
14507 static struct type *
14508 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14509 {
14510   struct objfile *objfile = cu->objfile;
14511   const char *previous_prefix, *name;
14512   int is_anonymous;
14513   struct type *type;
14514
14515   /* For extensions, reuse the type of the original namespace.  */
14516   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14517     {
14518       struct die_info *ext_die;
14519       struct dwarf2_cu *ext_cu = cu;
14520
14521       ext_die = dwarf2_extension (die, &ext_cu);
14522       type = read_type_die (ext_die, ext_cu);
14523
14524       /* EXT_CU may not be the same as CU.
14525          Ensure TYPE is recorded with CU in die_type_hash.  */
14526       return set_die_type (die, type, cu);
14527     }
14528
14529   name = namespace_name (die, &is_anonymous, cu);
14530
14531   /* Now build the name of the current namespace.  */
14532
14533   previous_prefix = determine_prefix (die, cu);
14534   if (previous_prefix[0] != '\0')
14535     name = typename_concat (&objfile->objfile_obstack,
14536                             previous_prefix, name, 0, cu);
14537
14538   /* Create the type.  */
14539   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14540   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14541
14542   return set_die_type (die, type, cu);
14543 }
14544
14545 /* Read a namespace scope.  */
14546
14547 static void
14548 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14549 {
14550   struct objfile *objfile = cu->objfile;
14551   int is_anonymous;
14552
14553   /* Add a symbol associated to this if we haven't seen the namespace
14554      before.  Also, add a using directive if it's an anonymous
14555      namespace.  */
14556
14557   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14558     {
14559       struct type *type;
14560
14561       type = read_type_die (die, cu);
14562       new_symbol (die, type, cu);
14563
14564       namespace_name (die, &is_anonymous, cu);
14565       if (is_anonymous)
14566         {
14567           const char *previous_prefix = determine_prefix (die, cu);
14568
14569           std::vector<const char *> excludes;
14570           add_using_directive (using_directives (cu->language),
14571                                previous_prefix, TYPE_NAME (type), NULL,
14572                                NULL, excludes, 0, &objfile->objfile_obstack);
14573         }
14574     }
14575
14576   if (die->child != NULL)
14577     {
14578       struct die_info *child_die = die->child;
14579
14580       while (child_die && child_die->tag)
14581         {
14582           process_die (child_die, cu);
14583           child_die = sibling_die (child_die);
14584         }
14585     }
14586 }
14587
14588 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14589    imported module.  Still we need that type as local Fortran "use ... only"
14590    declaration imports depend on the created type in determine_prefix.  */
14591
14592 static struct type *
14593 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14594 {
14595   struct objfile *objfile = cu->objfile;
14596   const char *module_name;
14597   struct type *type;
14598
14599   module_name = dwarf2_name (die, cu);
14600   if (!module_name)
14601     complaint (&symfile_complaints,
14602                _("DW_TAG_module has no name, offset 0x%x"),
14603                to_underlying (die->sect_off));
14604   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14605
14606   /* determine_prefix uses TYPE_TAG_NAME.  */
14607   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14608
14609   return set_die_type (die, type, cu);
14610 }
14611
14612 /* Read a Fortran module.  */
14613
14614 static void
14615 read_module (struct die_info *die, struct dwarf2_cu *cu)
14616 {
14617   struct die_info *child_die = die->child;
14618   struct type *type;
14619
14620   type = read_type_die (die, cu);
14621   new_symbol (die, type, cu);
14622
14623   while (child_die && child_die->tag)
14624     {
14625       process_die (child_die, cu);
14626       child_die = sibling_die (child_die);
14627     }
14628 }
14629
14630 /* Return the name of the namespace represented by DIE.  Set
14631    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14632    namespace.  */
14633
14634 static const char *
14635 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14636 {
14637   struct die_info *current_die;
14638   const char *name = NULL;
14639
14640   /* Loop through the extensions until we find a name.  */
14641
14642   for (current_die = die;
14643        current_die != NULL;
14644        current_die = dwarf2_extension (die, &cu))
14645     {
14646       /* We don't use dwarf2_name here so that we can detect the absence
14647          of a name -> anonymous namespace.  */
14648       name = dwarf2_string_attr (die, DW_AT_name, cu);
14649
14650       if (name != NULL)
14651         break;
14652     }
14653
14654   /* Is it an anonymous namespace?  */
14655
14656   *is_anonymous = (name == NULL);
14657   if (*is_anonymous)
14658     name = CP_ANONYMOUS_NAMESPACE_STR;
14659
14660   return name;
14661 }
14662
14663 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14664    the user defined type vector.  */
14665
14666 static struct type *
14667 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14668 {
14669   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14670   struct comp_unit_head *cu_header = &cu->header;
14671   struct type *type;
14672   struct attribute *attr_byte_size;
14673   struct attribute *attr_address_class;
14674   int byte_size, addr_class;
14675   struct type *target_type;
14676
14677   target_type = die_type (die, cu);
14678
14679   /* The die_type call above may have already set the type for this DIE.  */
14680   type = get_die_type (die, cu);
14681   if (type)
14682     return type;
14683
14684   type = lookup_pointer_type (target_type);
14685
14686   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14687   if (attr_byte_size)
14688     byte_size = DW_UNSND (attr_byte_size);
14689   else
14690     byte_size = cu_header->addr_size;
14691
14692   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14693   if (attr_address_class)
14694     addr_class = DW_UNSND (attr_address_class);
14695   else
14696     addr_class = DW_ADDR_none;
14697
14698   /* If the pointer size or address class is different than the
14699      default, create a type variant marked as such and set the
14700      length accordingly.  */
14701   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14702     {
14703       if (gdbarch_address_class_type_flags_p (gdbarch))
14704         {
14705           int type_flags;
14706
14707           type_flags = gdbarch_address_class_type_flags
14708                          (gdbarch, byte_size, addr_class);
14709           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14710                       == 0);
14711           type = make_type_with_address_space (type, type_flags);
14712         }
14713       else if (TYPE_LENGTH (type) != byte_size)
14714         {
14715           complaint (&symfile_complaints,
14716                      _("invalid pointer size %d"), byte_size);
14717         }
14718       else
14719         {
14720           /* Should we also complain about unhandled address classes?  */
14721         }
14722     }
14723
14724   TYPE_LENGTH (type) = byte_size;
14725   return set_die_type (die, type, cu);
14726 }
14727
14728 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14729    the user defined type vector.  */
14730
14731 static struct type *
14732 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14733 {
14734   struct type *type;
14735   struct type *to_type;
14736   struct type *domain;
14737
14738   to_type = die_type (die, cu);
14739   domain = die_containing_type (die, cu);
14740
14741   /* The calls above may have already set the type for this DIE.  */
14742   type = get_die_type (die, cu);
14743   if (type)
14744     return type;
14745
14746   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14747     type = lookup_methodptr_type (to_type);
14748   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14749     {
14750       struct type *new_type = alloc_type (cu->objfile);
14751
14752       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14753                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14754                             TYPE_VARARGS (to_type));
14755       type = lookup_methodptr_type (new_type);
14756     }
14757   else
14758     type = lookup_memberptr_type (to_type, domain);
14759
14760   return set_die_type (die, type, cu);
14761 }
14762
14763 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14764    the user defined type vector.  */
14765
14766 static struct type *
14767 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14768                           enum type_code refcode)
14769 {
14770   struct comp_unit_head *cu_header = &cu->header;
14771   struct type *type, *target_type;
14772   struct attribute *attr;
14773
14774   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14775
14776   target_type = die_type (die, cu);
14777
14778   /* The die_type call above may have already set the type for this DIE.  */
14779   type = get_die_type (die, cu);
14780   if (type)
14781     return type;
14782
14783   type = lookup_reference_type (target_type, refcode);
14784   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14785   if (attr)
14786     {
14787       TYPE_LENGTH (type) = DW_UNSND (attr);
14788     }
14789   else
14790     {
14791       TYPE_LENGTH (type) = cu_header->addr_size;
14792     }
14793   return set_die_type (die, type, cu);
14794 }
14795
14796 /* Add the given cv-qualifiers to the element type of the array.  GCC
14797    outputs DWARF type qualifiers that apply to an array, not the
14798    element type.  But GDB relies on the array element type to carry
14799    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14800    specification.  */
14801
14802 static struct type *
14803 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14804                    struct type *base_type, int cnst, int voltl)
14805 {
14806   struct type *el_type, *inner_array;
14807
14808   base_type = copy_type (base_type);
14809   inner_array = base_type;
14810
14811   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14812     {
14813       TYPE_TARGET_TYPE (inner_array) =
14814         copy_type (TYPE_TARGET_TYPE (inner_array));
14815       inner_array = TYPE_TARGET_TYPE (inner_array);
14816     }
14817
14818   el_type = TYPE_TARGET_TYPE (inner_array);
14819   cnst |= TYPE_CONST (el_type);
14820   voltl |= TYPE_VOLATILE (el_type);
14821   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14822
14823   return set_die_type (die, base_type, cu);
14824 }
14825
14826 static struct type *
14827 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14828 {
14829   struct type *base_type, *cv_type;
14830
14831   base_type = die_type (die, cu);
14832
14833   /* The die_type call above may have already set the type for this DIE.  */
14834   cv_type = get_die_type (die, cu);
14835   if (cv_type)
14836     return cv_type;
14837
14838   /* In case the const qualifier is applied to an array type, the element type
14839      is so qualified, not the array type (section 6.7.3 of C99).  */
14840   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14841     return add_array_cv_type (die, cu, base_type, 1, 0);
14842
14843   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14844   return set_die_type (die, cv_type, cu);
14845 }
14846
14847 static struct type *
14848 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
14849 {
14850   struct type *base_type, *cv_type;
14851
14852   base_type = die_type (die, cu);
14853
14854   /* The die_type call above may have already set the type for this DIE.  */
14855   cv_type = get_die_type (die, cu);
14856   if (cv_type)
14857     return cv_type;
14858
14859   /* In case the volatile qualifier is applied to an array type, the
14860      element type is so qualified, not the array type (section 6.7.3
14861      of C99).  */
14862   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14863     return add_array_cv_type (die, cu, base_type, 0, 1);
14864
14865   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14866   return set_die_type (die, cv_type, cu);
14867 }
14868
14869 /* Handle DW_TAG_restrict_type.  */
14870
14871 static struct type *
14872 read_tag_restrict_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   cv_type = make_restrict_type (base_type);
14884   return set_die_type (die, cv_type, cu);
14885 }
14886
14887 /* Handle DW_TAG_atomic_type.  */
14888
14889 static struct type *
14890 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14891 {
14892   struct type *base_type, *cv_type;
14893
14894   base_type = die_type (die, cu);
14895
14896   /* The die_type call above may have already set the type for this DIE.  */
14897   cv_type = get_die_type (die, cu);
14898   if (cv_type)
14899     return cv_type;
14900
14901   cv_type = make_atomic_type (base_type);
14902   return set_die_type (die, cv_type, cu);
14903 }
14904
14905 /* Extract all information from a DW_TAG_string_type DIE and add to
14906    the user defined type vector.  It isn't really a user defined type,
14907    but it behaves like one, with other DIE's using an AT_user_def_type
14908    attribute to reference it.  */
14909
14910 static struct type *
14911 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14912 {
14913   struct objfile *objfile = cu->objfile;
14914   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14915   struct type *type, *range_type, *index_type, *char_type;
14916   struct attribute *attr;
14917   unsigned int length;
14918
14919   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14920   if (attr)
14921     {
14922       length = DW_UNSND (attr);
14923     }
14924   else
14925     {
14926       /* Check for the DW_AT_byte_size attribute.  */
14927       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14928       if (attr)
14929         {
14930           length = DW_UNSND (attr);
14931         }
14932       else
14933         {
14934           length = 1;
14935         }
14936     }
14937
14938   index_type = objfile_type (objfile)->builtin_int;
14939   range_type = create_static_range_type (NULL, index_type, 1, length);
14940   char_type = language_string_char_type (cu->language_defn, gdbarch);
14941   type = create_string_type (NULL, char_type, range_type);
14942
14943   return set_die_type (die, type, cu);
14944 }
14945
14946 /* Assuming that DIE corresponds to a function, returns nonzero
14947    if the function is prototyped.  */
14948
14949 static int
14950 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14951 {
14952   struct attribute *attr;
14953
14954   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14955   if (attr && (DW_UNSND (attr) != 0))
14956     return 1;
14957
14958   /* The DWARF standard implies that the DW_AT_prototyped attribute
14959      is only meaninful for C, but the concept also extends to other
14960      languages that allow unprototyped functions (Eg: Objective C).
14961      For all other languages, assume that functions are always
14962      prototyped.  */
14963   if (cu->language != language_c
14964       && cu->language != language_objc
14965       && cu->language != language_opencl)
14966     return 1;
14967
14968   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14969      prototyped and unprototyped functions; default to prototyped,
14970      since that is more common in modern code (and RealView warns
14971      about unprototyped functions).  */
14972   if (producer_is_realview (cu->producer))
14973     return 1;
14974
14975   return 0;
14976 }
14977
14978 /* Handle DIES due to C code like:
14979
14980    struct foo
14981    {
14982    int (*funcp)(int a, long l);
14983    int b;
14984    };
14985
14986    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14987
14988 static struct type *
14989 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14990 {
14991   struct objfile *objfile = cu->objfile;
14992   struct type *type;            /* Type that this function returns.  */
14993   struct type *ftype;           /* Function that returns above type.  */
14994   struct attribute *attr;
14995
14996   type = die_type (die, cu);
14997
14998   /* The die_type call above may have already set the type for this DIE.  */
14999   ftype = get_die_type (die, cu);
15000   if (ftype)
15001     return ftype;
15002
15003   ftype = lookup_function_type (type);
15004
15005   if (prototyped_function_p (die, cu))
15006     TYPE_PROTOTYPED (ftype) = 1;
15007
15008   /* Store the calling convention in the type if it's available in
15009      the subroutine die.  Otherwise set the calling convention to
15010      the default value DW_CC_normal.  */
15011   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15012   if (attr)
15013     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15014   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15015     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15016   else
15017     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15018
15019   /* Record whether the function returns normally to its caller or not
15020      if the DWARF producer set that information.  */
15021   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15022   if (attr && (DW_UNSND (attr) != 0))
15023     TYPE_NO_RETURN (ftype) = 1;
15024
15025   /* We need to add the subroutine type to the die immediately so
15026      we don't infinitely recurse when dealing with parameters
15027      declared as the same subroutine type.  */
15028   set_die_type (die, ftype, cu);
15029
15030   if (die->child != NULL)
15031     {
15032       struct type *void_type = objfile_type (objfile)->builtin_void;
15033       struct die_info *child_die;
15034       int nparams, iparams;
15035
15036       /* Count the number of parameters.
15037          FIXME: GDB currently ignores vararg functions, but knows about
15038          vararg member functions.  */
15039       nparams = 0;
15040       child_die = die->child;
15041       while (child_die && child_die->tag)
15042         {
15043           if (child_die->tag == DW_TAG_formal_parameter)
15044             nparams++;
15045           else if (child_die->tag == DW_TAG_unspecified_parameters)
15046             TYPE_VARARGS (ftype) = 1;
15047           child_die = sibling_die (child_die);
15048         }
15049
15050       /* Allocate storage for parameters and fill them in.  */
15051       TYPE_NFIELDS (ftype) = nparams;
15052       TYPE_FIELDS (ftype) = (struct field *)
15053         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15054
15055       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15056          even if we error out during the parameters reading below.  */
15057       for (iparams = 0; iparams < nparams; iparams++)
15058         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15059
15060       iparams = 0;
15061       child_die = die->child;
15062       while (child_die && child_die->tag)
15063         {
15064           if (child_die->tag == DW_TAG_formal_parameter)
15065             {
15066               struct type *arg_type;
15067
15068               /* DWARF version 2 has no clean way to discern C++
15069                  static and non-static member functions.  G++ helps
15070                  GDB by marking the first parameter for non-static
15071                  member functions (which is the this pointer) as
15072                  artificial.  We pass this information to
15073                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15074
15075                  DWARF version 3 added DW_AT_object_pointer, which GCC
15076                  4.5 does not yet generate.  */
15077               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15078               if (attr)
15079                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15080               else
15081                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15082               arg_type = die_type (child_die, cu);
15083
15084               /* RealView does not mark THIS as const, which the testsuite
15085                  expects.  GCC marks THIS as const in method definitions,
15086                  but not in the class specifications (GCC PR 43053).  */
15087               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15088                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15089                 {
15090                   int is_this = 0;
15091                   struct dwarf2_cu *arg_cu = cu;
15092                   const char *name = dwarf2_name (child_die, cu);
15093
15094                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15095                   if (attr)
15096                     {
15097                       /* If the compiler emits this, use it.  */
15098                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15099                         is_this = 1;
15100                     }
15101                   else if (name && strcmp (name, "this") == 0)
15102                     /* Function definitions will have the argument names.  */
15103                     is_this = 1;
15104                   else if (name == NULL && iparams == 0)
15105                     /* Declarations may not have the names, so like
15106                        elsewhere in GDB, assume an artificial first
15107                        argument is "this".  */
15108                     is_this = 1;
15109
15110                   if (is_this)
15111                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15112                                              arg_type, 0);
15113                 }
15114
15115               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15116               iparams++;
15117             }
15118           child_die = sibling_die (child_die);
15119         }
15120     }
15121
15122   return ftype;
15123 }
15124
15125 static struct type *
15126 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15127 {
15128   struct objfile *objfile = cu->objfile;
15129   const char *name = NULL;
15130   struct type *this_type, *target_type;
15131
15132   name = dwarf2_full_name (NULL, die, cu);
15133   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15134   TYPE_TARGET_STUB (this_type) = 1;
15135   set_die_type (die, this_type, cu);
15136   target_type = die_type (die, cu);
15137   if (target_type != this_type)
15138     TYPE_TARGET_TYPE (this_type) = target_type;
15139   else
15140     {
15141       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15142          spec and cause infinite loops in GDB.  */
15143       complaint (&symfile_complaints,
15144                  _("Self-referential DW_TAG_typedef "
15145                    "- DIE at 0x%x [in module %s]"),
15146                  to_underlying (die->sect_off), objfile_name (objfile));
15147       TYPE_TARGET_TYPE (this_type) = NULL;
15148     }
15149   return this_type;
15150 }
15151
15152 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15153    (which may be different from NAME) to the architecture back-end to allow
15154    it to guess the correct format if necessary.  */
15155
15156 static struct type *
15157 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15158                         const char *name_hint)
15159 {
15160   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15161   const struct floatformat **format;
15162   struct type *type;
15163
15164   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15165   if (format)
15166     type = init_float_type (objfile, bits, name, format);
15167   else
15168     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15169
15170   return type;
15171 }
15172
15173 /* Find a representation of a given base type and install
15174    it in the TYPE field of the die.  */
15175
15176 static struct type *
15177 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15178 {
15179   struct objfile *objfile = cu->objfile;
15180   struct type *type;
15181   struct attribute *attr;
15182   int encoding = 0, bits = 0;
15183   const char *name;
15184
15185   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15186   if (attr)
15187     {
15188       encoding = DW_UNSND (attr);
15189     }
15190   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15191   if (attr)
15192     {
15193       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15194     }
15195   name = dwarf2_name (die, cu);
15196   if (!name)
15197     {
15198       complaint (&symfile_complaints,
15199                  _("DW_AT_name missing from DW_TAG_base_type"));
15200     }
15201
15202   switch (encoding)
15203     {
15204       case DW_ATE_address:
15205         /* Turn DW_ATE_address into a void * pointer.  */
15206         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
15207         type = init_pointer_type (objfile, bits, name, type);
15208         break;
15209       case DW_ATE_boolean:
15210         type = init_boolean_type (objfile, bits, 1, name);
15211         break;
15212       case DW_ATE_complex_float:
15213         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15214         type = init_complex_type (objfile, name, type);
15215         break;
15216       case DW_ATE_decimal_float:
15217         type = init_decfloat_type (objfile, bits, name);
15218         break;
15219       case DW_ATE_float:
15220         type = dwarf2_init_float_type (objfile, bits, name, name);
15221         break;
15222       case DW_ATE_signed:
15223         type = init_integer_type (objfile, bits, 0, name);
15224         break;
15225       case DW_ATE_unsigned:
15226         if (cu->language == language_fortran
15227             && name
15228             && startswith (name, "character("))
15229           type = init_character_type (objfile, bits, 1, name);
15230         else
15231           type = init_integer_type (objfile, bits, 1, name);
15232         break;
15233       case DW_ATE_signed_char:
15234         if (cu->language == language_ada || cu->language == language_m2
15235             || cu->language == language_pascal
15236             || cu->language == language_fortran)
15237           type = init_character_type (objfile, bits, 0, name);
15238         else
15239           type = init_integer_type (objfile, bits, 0, name);
15240         break;
15241       case DW_ATE_unsigned_char:
15242         if (cu->language == language_ada || cu->language == language_m2
15243             || cu->language == language_pascal
15244             || cu->language == language_fortran
15245             || cu->language == language_rust)
15246           type = init_character_type (objfile, bits, 1, name);
15247         else
15248           type = init_integer_type (objfile, bits, 1, name);
15249         break;
15250       case DW_ATE_UTF:
15251         {
15252           gdbarch *arch = get_objfile_arch (objfile);
15253
15254           if (bits == 16)
15255             type = builtin_type (arch)->builtin_char16;
15256           else if (bits == 32)
15257             type = builtin_type (arch)->builtin_char32;
15258           else
15259             {
15260               complaint (&symfile_complaints,
15261                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15262                          bits);
15263               type = init_integer_type (objfile, bits, 1, name);
15264             }
15265           return set_die_type (die, type, cu);
15266         }
15267         break;
15268
15269       default:
15270         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15271                    dwarf_type_encoding_name (encoding));
15272         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15273         break;
15274     }
15275
15276   if (name && strcmp (name, "char") == 0)
15277     TYPE_NOSIGN (type) = 1;
15278
15279   return set_die_type (die, type, cu);
15280 }
15281
15282 /* Parse dwarf attribute if it's a block, reference or constant and put the
15283    resulting value of the attribute into struct bound_prop.
15284    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15285
15286 static int
15287 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15288                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15289 {
15290   struct dwarf2_property_baton *baton;
15291   struct obstack *obstack = &cu->objfile->objfile_obstack;
15292
15293   if (attr == NULL || prop == NULL)
15294     return 0;
15295
15296   if (attr_form_is_block (attr))
15297     {
15298       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15299       baton->referenced_type = NULL;
15300       baton->locexpr.per_cu = cu->per_cu;
15301       baton->locexpr.size = DW_BLOCK (attr)->size;
15302       baton->locexpr.data = DW_BLOCK (attr)->data;
15303       prop->data.baton = baton;
15304       prop->kind = PROP_LOCEXPR;
15305       gdb_assert (prop->data.baton != NULL);
15306     }
15307   else if (attr_form_is_ref (attr))
15308     {
15309       struct dwarf2_cu *target_cu = cu;
15310       struct die_info *target_die;
15311       struct attribute *target_attr;
15312
15313       target_die = follow_die_ref (die, attr, &target_cu);
15314       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15315       if (target_attr == NULL)
15316         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15317                                    target_cu);
15318       if (target_attr == NULL)
15319         return 0;
15320
15321       switch (target_attr->name)
15322         {
15323           case DW_AT_location:
15324             if (attr_form_is_section_offset (target_attr))
15325               {
15326                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15327                 baton->referenced_type = die_type (target_die, target_cu);
15328                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15329                 prop->data.baton = baton;
15330                 prop->kind = PROP_LOCLIST;
15331                 gdb_assert (prop->data.baton != NULL);
15332               }
15333             else if (attr_form_is_block (target_attr))
15334               {
15335                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15336                 baton->referenced_type = die_type (target_die, target_cu);
15337                 baton->locexpr.per_cu = cu->per_cu;
15338                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15339                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15340                 prop->data.baton = baton;
15341                 prop->kind = PROP_LOCEXPR;
15342                 gdb_assert (prop->data.baton != NULL);
15343               }
15344             else
15345               {
15346                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15347                                                        "dynamic property");
15348                 return 0;
15349               }
15350             break;
15351           case DW_AT_data_member_location:
15352             {
15353               LONGEST offset;
15354
15355               if (!handle_data_member_location (target_die, target_cu,
15356                                                 &offset))
15357                 return 0;
15358
15359               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15360               baton->referenced_type = read_type_die (target_die->parent,
15361                                                       target_cu);
15362               baton->offset_info.offset = offset;
15363               baton->offset_info.type = die_type (target_die, target_cu);
15364               prop->data.baton = baton;
15365               prop->kind = PROP_ADDR_OFFSET;
15366               break;
15367             }
15368         }
15369     }
15370   else if (attr_form_is_constant (attr))
15371     {
15372       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15373       prop->kind = PROP_CONST;
15374     }
15375   else
15376     {
15377       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15378                                              dwarf2_name (die, cu));
15379       return 0;
15380     }
15381
15382   return 1;
15383 }
15384
15385 /* Read the given DW_AT_subrange DIE.  */
15386
15387 static struct type *
15388 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15389 {
15390   struct type *base_type, *orig_base_type;
15391   struct type *range_type;
15392   struct attribute *attr;
15393   struct dynamic_prop low, high;
15394   int low_default_is_valid;
15395   int high_bound_is_count = 0;
15396   const char *name;
15397   LONGEST negative_mask;
15398
15399   orig_base_type = die_type (die, cu);
15400   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15401      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15402      creating the range type, but we use the result of check_typedef
15403      when examining properties of the type.  */
15404   base_type = check_typedef (orig_base_type);
15405
15406   /* The die_type call above may have already set the type for this DIE.  */
15407   range_type = get_die_type (die, cu);
15408   if (range_type)
15409     return range_type;
15410
15411   low.kind = PROP_CONST;
15412   high.kind = PROP_CONST;
15413   high.data.const_val = 0;
15414
15415   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15416      omitting DW_AT_lower_bound.  */
15417   switch (cu->language)
15418     {
15419     case language_c:
15420     case language_cplus:
15421       low.data.const_val = 0;
15422       low_default_is_valid = 1;
15423       break;
15424     case language_fortran:
15425       low.data.const_val = 1;
15426       low_default_is_valid = 1;
15427       break;
15428     case language_d:
15429     case language_objc:
15430     case language_rust:
15431       low.data.const_val = 0;
15432       low_default_is_valid = (cu->header.version >= 4);
15433       break;
15434     case language_ada:
15435     case language_m2:
15436     case language_pascal:
15437       low.data.const_val = 1;
15438       low_default_is_valid = (cu->header.version >= 4);
15439       break;
15440     default:
15441       low.data.const_val = 0;
15442       low_default_is_valid = 0;
15443       break;
15444     }
15445
15446   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15447   if (attr)
15448     attr_to_dynamic_prop (attr, die, cu, &low);
15449   else if (!low_default_is_valid)
15450     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15451                                       "- DIE at 0x%x [in module %s]"),
15452                to_underlying (die->sect_off), objfile_name (cu->objfile));
15453
15454   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15455   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15456     {
15457       attr = dwarf2_attr (die, DW_AT_count, cu);
15458       if (attr_to_dynamic_prop (attr, die, cu, &high))
15459         {
15460           /* If bounds are constant do the final calculation here.  */
15461           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15462             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15463           else
15464             high_bound_is_count = 1;
15465         }
15466     }
15467
15468   /* Dwarf-2 specifications explicitly allows to create subrange types
15469      without specifying a base type.
15470      In that case, the base type must be set to the type of
15471      the lower bound, upper bound or count, in that order, if any of these
15472      three attributes references an object that has a type.
15473      If no base type is found, the Dwarf-2 specifications say that
15474      a signed integer type of size equal to the size of an address should
15475      be used.
15476      For the following C code: `extern char gdb_int [];'
15477      GCC produces an empty range DIE.
15478      FIXME: muller/2010-05-28: Possible references to object for low bound,
15479      high bound or count are not yet handled by this code.  */
15480   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15481     {
15482       struct objfile *objfile = cu->objfile;
15483       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15484       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15485       struct type *int_type = objfile_type (objfile)->builtin_int;
15486
15487       /* Test "int", "long int", and "long long int" objfile types,
15488          and select the first one having a size above or equal to the
15489          architecture address size.  */
15490       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15491         base_type = int_type;
15492       else
15493         {
15494           int_type = objfile_type (objfile)->builtin_long;
15495           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15496             base_type = int_type;
15497           else
15498             {
15499               int_type = objfile_type (objfile)->builtin_long_long;
15500               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15501                 base_type = int_type;
15502             }
15503         }
15504     }
15505
15506   /* Normally, the DWARF producers are expected to use a signed
15507      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15508      But this is unfortunately not always the case, as witnessed
15509      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15510      is used instead.  To work around that ambiguity, we treat
15511      the bounds as signed, and thus sign-extend their values, when
15512      the base type is signed.  */
15513   negative_mask =
15514     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15515   if (low.kind == PROP_CONST
15516       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15517     low.data.const_val |= negative_mask;
15518   if (high.kind == PROP_CONST
15519       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15520     high.data.const_val |= negative_mask;
15521
15522   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15523
15524   if (high_bound_is_count)
15525     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15526
15527   /* Ada expects an empty array on no boundary attributes.  */
15528   if (attr == NULL && cu->language != language_ada)
15529     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15530
15531   name = dwarf2_name (die, cu);
15532   if (name)
15533     TYPE_NAME (range_type) = name;
15534
15535   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15536   if (attr)
15537     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15538
15539   set_die_type (die, range_type, cu);
15540
15541   /* set_die_type should be already done.  */
15542   set_descriptive_type (range_type, die, cu);
15543
15544   return range_type;
15545 }
15546
15547 static struct type *
15548 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15549 {
15550   struct type *type;
15551
15552   /* For now, we only support the C meaning of an unspecified type: void.  */
15553
15554   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15555   TYPE_NAME (type) = dwarf2_name (die, cu);
15556
15557   return set_die_type (die, type, cu);
15558 }
15559
15560 /* Read a single die and all its descendents.  Set the die's sibling
15561    field to NULL; set other fields in the die correctly, and set all
15562    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15563    location of the info_ptr after reading all of those dies.  PARENT
15564    is the parent of the die in question.  */
15565
15566 static struct die_info *
15567 read_die_and_children (const struct die_reader_specs *reader,
15568                        const gdb_byte *info_ptr,
15569                        const gdb_byte **new_info_ptr,
15570                        struct die_info *parent)
15571 {
15572   struct die_info *die;
15573   const gdb_byte *cur_ptr;
15574   int has_children;
15575
15576   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15577   if (die == NULL)
15578     {
15579       *new_info_ptr = cur_ptr;
15580       return NULL;
15581     }
15582   store_in_ref_table (die, reader->cu);
15583
15584   if (has_children)
15585     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15586   else
15587     {
15588       die->child = NULL;
15589       *new_info_ptr = cur_ptr;
15590     }
15591
15592   die->sibling = NULL;
15593   die->parent = parent;
15594   return die;
15595 }
15596
15597 /* Read a die, all of its descendents, and all of its siblings; set
15598    all of the fields of all of the dies correctly.  Arguments are as
15599    in read_die_and_children.  */
15600
15601 static struct die_info *
15602 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15603                          const gdb_byte *info_ptr,
15604                          const gdb_byte **new_info_ptr,
15605                          struct die_info *parent)
15606 {
15607   struct die_info *first_die, *last_sibling;
15608   const gdb_byte *cur_ptr;
15609
15610   cur_ptr = info_ptr;
15611   first_die = last_sibling = NULL;
15612
15613   while (1)
15614     {
15615       struct die_info *die
15616         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15617
15618       if (die == NULL)
15619         {
15620           *new_info_ptr = cur_ptr;
15621           return first_die;
15622         }
15623
15624       if (!first_die)
15625         first_die = die;
15626       else
15627         last_sibling->sibling = die;
15628
15629       last_sibling = die;
15630     }
15631 }
15632
15633 /* Read a die, all of its descendents, and all of its siblings; set
15634    all of the fields of all of the dies correctly.  Arguments are as
15635    in read_die_and_children.
15636    This the main entry point for reading a DIE and all its children.  */
15637
15638 static struct die_info *
15639 read_die_and_siblings (const struct die_reader_specs *reader,
15640                        const gdb_byte *info_ptr,
15641                        const gdb_byte **new_info_ptr,
15642                        struct die_info *parent)
15643 {
15644   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15645                                                   new_info_ptr, parent);
15646
15647   if (dwarf_die_debug)
15648     {
15649       fprintf_unfiltered (gdb_stdlog,
15650                           "Read die from %s@0x%x of %s:\n",
15651                           get_section_name (reader->die_section),
15652                           (unsigned) (info_ptr - reader->die_section->buffer),
15653                           bfd_get_filename (reader->abfd));
15654       dump_die (die, dwarf_die_debug);
15655     }
15656
15657   return die;
15658 }
15659
15660 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15661    attributes.
15662    The caller is responsible for filling in the extra attributes
15663    and updating (*DIEP)->num_attrs.
15664    Set DIEP to point to a newly allocated die with its information,
15665    except for its child, sibling, and parent fields.
15666    Set HAS_CHILDREN to tell whether the die has children or not.  */
15667
15668 static const gdb_byte *
15669 read_full_die_1 (const struct die_reader_specs *reader,
15670                  struct die_info **diep, const gdb_byte *info_ptr,
15671                  int *has_children, int num_extra_attrs)
15672 {
15673   unsigned int abbrev_number, bytes_read, i;
15674   struct abbrev_info *abbrev;
15675   struct die_info *die;
15676   struct dwarf2_cu *cu = reader->cu;
15677   bfd *abfd = reader->abfd;
15678
15679   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15680   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15681   info_ptr += bytes_read;
15682   if (!abbrev_number)
15683     {
15684       *diep = NULL;
15685       *has_children = 0;
15686       return info_ptr;
15687     }
15688
15689   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15690   if (!abbrev)
15691     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15692            abbrev_number,
15693            bfd_get_filename (abfd));
15694
15695   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15696   die->sect_off = sect_off;
15697   die->tag = abbrev->tag;
15698   die->abbrev = abbrev_number;
15699
15700   /* Make the result usable.
15701      The caller needs to update num_attrs after adding the extra
15702      attributes.  */
15703   die->num_attrs = abbrev->num_attrs;
15704
15705   for (i = 0; i < abbrev->num_attrs; ++i)
15706     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15707                                info_ptr);
15708
15709   *diep = die;
15710   *has_children = abbrev->has_children;
15711   return info_ptr;
15712 }
15713
15714 /* Read a die and all its attributes.
15715    Set DIEP to point to a newly allocated die with its information,
15716    except for its child, sibling, and parent fields.
15717    Set HAS_CHILDREN to tell whether the die has children or not.  */
15718
15719 static const gdb_byte *
15720 read_full_die (const struct die_reader_specs *reader,
15721                struct die_info **diep, const gdb_byte *info_ptr,
15722                int *has_children)
15723 {
15724   const gdb_byte *result;
15725
15726   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15727
15728   if (dwarf_die_debug)
15729     {
15730       fprintf_unfiltered (gdb_stdlog,
15731                           "Read die from %s@0x%x of %s:\n",
15732                           get_section_name (reader->die_section),
15733                           (unsigned) (info_ptr - reader->die_section->buffer),
15734                           bfd_get_filename (reader->abfd));
15735       dump_die (*diep, dwarf_die_debug);
15736     }
15737
15738   return result;
15739 }
15740 \f
15741 /* Abbreviation tables.
15742
15743    In DWARF version 2, the description of the debugging information is
15744    stored in a separate .debug_abbrev section.  Before we read any
15745    dies from a section we read in all abbreviations and install them
15746    in a hash table.  */
15747
15748 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15749
15750 static struct abbrev_info *
15751 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15752 {
15753   struct abbrev_info *abbrev;
15754
15755   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15756   memset (abbrev, 0, sizeof (struct abbrev_info));
15757
15758   return abbrev;
15759 }
15760
15761 /* Add an abbreviation to the table.  */
15762
15763 static void
15764 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15765                          unsigned int abbrev_number,
15766                          struct abbrev_info *abbrev)
15767 {
15768   unsigned int hash_number;
15769
15770   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15771   abbrev->next = abbrev_table->abbrevs[hash_number];
15772   abbrev_table->abbrevs[hash_number] = abbrev;
15773 }
15774
15775 /* Look up an abbrev in the table.
15776    Returns NULL if the abbrev is not found.  */
15777
15778 static struct abbrev_info *
15779 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15780                             unsigned int abbrev_number)
15781 {
15782   unsigned int hash_number;
15783   struct abbrev_info *abbrev;
15784
15785   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15786   abbrev = abbrev_table->abbrevs[hash_number];
15787
15788   while (abbrev)
15789     {
15790       if (abbrev->number == abbrev_number)
15791         return abbrev;
15792       abbrev = abbrev->next;
15793     }
15794   return NULL;
15795 }
15796
15797 /* Read in an abbrev table.  */
15798
15799 static struct abbrev_table *
15800 abbrev_table_read_table (struct dwarf2_section_info *section,
15801                          sect_offset sect_off)
15802 {
15803   struct objfile *objfile = dwarf2_per_objfile->objfile;
15804   bfd *abfd = get_section_bfd_owner (section);
15805   struct abbrev_table *abbrev_table;
15806   const gdb_byte *abbrev_ptr;
15807   struct abbrev_info *cur_abbrev;
15808   unsigned int abbrev_number, bytes_read, abbrev_name;
15809   unsigned int abbrev_form;
15810   struct attr_abbrev *cur_attrs;
15811   unsigned int allocated_attrs;
15812
15813   abbrev_table = XNEW (struct abbrev_table);
15814   abbrev_table->sect_off = sect_off;
15815   obstack_init (&abbrev_table->abbrev_obstack);
15816   abbrev_table->abbrevs =
15817     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15818                ABBREV_HASH_SIZE);
15819   memset (abbrev_table->abbrevs, 0,
15820           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15821
15822   dwarf2_read_section (objfile, section);
15823   abbrev_ptr = section->buffer + to_underlying (sect_off);
15824   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15825   abbrev_ptr += bytes_read;
15826
15827   allocated_attrs = ATTR_ALLOC_CHUNK;
15828   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15829
15830   /* Loop until we reach an abbrev number of 0.  */
15831   while (abbrev_number)
15832     {
15833       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15834
15835       /* read in abbrev header */
15836       cur_abbrev->number = abbrev_number;
15837       cur_abbrev->tag
15838         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15839       abbrev_ptr += bytes_read;
15840       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15841       abbrev_ptr += 1;
15842
15843       /* now read in declarations */
15844       for (;;)
15845         {
15846           LONGEST implicit_const;
15847
15848           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15849           abbrev_ptr += bytes_read;
15850           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15851           abbrev_ptr += bytes_read;
15852           if (abbrev_form == DW_FORM_implicit_const)
15853             {
15854               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15855                                                    &bytes_read);
15856               abbrev_ptr += bytes_read;
15857             }
15858           else
15859             {
15860               /* Initialize it due to a false compiler warning.  */
15861               implicit_const = -1;
15862             }
15863
15864           if (abbrev_name == 0)
15865             break;
15866
15867           if (cur_abbrev->num_attrs == allocated_attrs)
15868             {
15869               allocated_attrs += ATTR_ALLOC_CHUNK;
15870               cur_attrs
15871                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15872             }
15873
15874           cur_attrs[cur_abbrev->num_attrs].name
15875             = (enum dwarf_attribute) abbrev_name;
15876           cur_attrs[cur_abbrev->num_attrs].form
15877             = (enum dwarf_form) abbrev_form;
15878           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15879           ++cur_abbrev->num_attrs;
15880         }
15881
15882       cur_abbrev->attrs =
15883         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15884                    cur_abbrev->num_attrs);
15885       memcpy (cur_abbrev->attrs, cur_attrs,
15886               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15887
15888       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15889
15890       /* Get next abbreviation.
15891          Under Irix6 the abbreviations for a compilation unit are not
15892          always properly terminated with an abbrev number of 0.
15893          Exit loop if we encounter an abbreviation which we have
15894          already read (which means we are about to read the abbreviations
15895          for the next compile unit) or if the end of the abbreviation
15896          table is reached.  */
15897       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15898         break;
15899       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15900       abbrev_ptr += bytes_read;
15901       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15902         break;
15903     }
15904
15905   xfree (cur_attrs);
15906   return abbrev_table;
15907 }
15908
15909 /* Free the resources held by ABBREV_TABLE.  */
15910
15911 static void
15912 abbrev_table_free (struct abbrev_table *abbrev_table)
15913 {
15914   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15915   xfree (abbrev_table);
15916 }
15917
15918 /* Same as abbrev_table_free but as a cleanup.
15919    We pass in a pointer to the pointer to the table so that we can
15920    set the pointer to NULL when we're done.  It also simplifies
15921    build_type_psymtabs_1.  */
15922
15923 static void
15924 abbrev_table_free_cleanup (void *table_ptr)
15925 {
15926   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15927
15928   if (*abbrev_table_ptr != NULL)
15929     abbrev_table_free (*abbrev_table_ptr);
15930   *abbrev_table_ptr = NULL;
15931 }
15932
15933 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15934
15935 static void
15936 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15937                      struct dwarf2_section_info *abbrev_section)
15938 {
15939   cu->abbrev_table =
15940     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15941 }
15942
15943 /* Release the memory used by the abbrev table for a compilation unit.  */
15944
15945 static void
15946 dwarf2_free_abbrev_table (void *ptr_to_cu)
15947 {
15948   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15949
15950   if (cu->abbrev_table != NULL)
15951     abbrev_table_free (cu->abbrev_table);
15952   /* Set this to NULL so that we SEGV if we try to read it later,
15953      and also because free_comp_unit verifies this is NULL.  */
15954   cu->abbrev_table = NULL;
15955 }
15956 \f
15957 /* Returns nonzero if TAG represents a type that we might generate a partial
15958    symbol for.  */
15959
15960 static int
15961 is_type_tag_for_partial (int tag)
15962 {
15963   switch (tag)
15964     {
15965 #if 0
15966     /* Some types that would be reasonable to generate partial symbols for,
15967        that we don't at present.  */
15968     case DW_TAG_array_type:
15969     case DW_TAG_file_type:
15970     case DW_TAG_ptr_to_member_type:
15971     case DW_TAG_set_type:
15972     case DW_TAG_string_type:
15973     case DW_TAG_subroutine_type:
15974 #endif
15975     case DW_TAG_base_type:
15976     case DW_TAG_class_type:
15977     case DW_TAG_interface_type:
15978     case DW_TAG_enumeration_type:
15979     case DW_TAG_structure_type:
15980     case DW_TAG_subrange_type:
15981     case DW_TAG_typedef:
15982     case DW_TAG_union_type:
15983       return 1;
15984     default:
15985       return 0;
15986     }
15987 }
15988
15989 /* Load all DIEs that are interesting for partial symbols into memory.  */
15990
15991 static struct partial_die_info *
15992 load_partial_dies (const struct die_reader_specs *reader,
15993                    const gdb_byte *info_ptr, int building_psymtab)
15994 {
15995   struct dwarf2_cu *cu = reader->cu;
15996   struct objfile *objfile = cu->objfile;
15997   struct partial_die_info *part_die;
15998   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15999   struct abbrev_info *abbrev;
16000   unsigned int bytes_read;
16001   unsigned int load_all = 0;
16002   int nesting_level = 1;
16003
16004   parent_die = NULL;
16005   last_die = NULL;
16006
16007   gdb_assert (cu->per_cu != NULL);
16008   if (cu->per_cu->load_all_dies)
16009     load_all = 1;
16010
16011   cu->partial_dies
16012     = htab_create_alloc_ex (cu->header.length / 12,
16013                             partial_die_hash,
16014                             partial_die_eq,
16015                             NULL,
16016                             &cu->comp_unit_obstack,
16017                             hashtab_obstack_allocate,
16018                             dummy_obstack_deallocate);
16019
16020   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16021
16022   while (1)
16023     {
16024       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16025
16026       /* A NULL abbrev means the end of a series of children.  */
16027       if (abbrev == NULL)
16028         {
16029           if (--nesting_level == 0)
16030             {
16031               /* PART_DIE was probably the last thing allocated on the
16032                  comp_unit_obstack, so we could call obstack_free
16033                  here.  We don't do that because the waste is small,
16034                  and will be cleaned up when we're done with this
16035                  compilation unit.  This way, we're also more robust
16036                  against other users of the comp_unit_obstack.  */
16037               return first_die;
16038             }
16039           info_ptr += bytes_read;
16040           last_die = parent_die;
16041           parent_die = parent_die->die_parent;
16042           continue;
16043         }
16044
16045       /* Check for template arguments.  We never save these; if
16046          they're seen, we just mark the parent, and go on our way.  */
16047       if (parent_die != NULL
16048           && cu->language == language_cplus
16049           && (abbrev->tag == DW_TAG_template_type_param
16050               || abbrev->tag == DW_TAG_template_value_param))
16051         {
16052           parent_die->has_template_arguments = 1;
16053
16054           if (!load_all)
16055             {
16056               /* We don't need a partial DIE for the template argument.  */
16057               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16058               continue;
16059             }
16060         }
16061
16062       /* We only recurse into c++ subprograms looking for template arguments.
16063          Skip their other children.  */
16064       if (!load_all
16065           && cu->language == language_cplus
16066           && parent_die != NULL
16067           && parent_die->tag == DW_TAG_subprogram)
16068         {
16069           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16070           continue;
16071         }
16072
16073       /* Check whether this DIE is interesting enough to save.  Normally
16074          we would not be interested in members here, but there may be
16075          later variables referencing them via DW_AT_specification (for
16076          static members).  */
16077       if (!load_all
16078           && !is_type_tag_for_partial (abbrev->tag)
16079           && abbrev->tag != DW_TAG_constant
16080           && abbrev->tag != DW_TAG_enumerator
16081           && abbrev->tag != DW_TAG_subprogram
16082           && abbrev->tag != DW_TAG_lexical_block
16083           && abbrev->tag != DW_TAG_variable
16084           && abbrev->tag != DW_TAG_namespace
16085           && abbrev->tag != DW_TAG_module
16086           && abbrev->tag != DW_TAG_member
16087           && abbrev->tag != DW_TAG_imported_unit
16088           && abbrev->tag != DW_TAG_imported_declaration)
16089         {
16090           /* Otherwise we skip to the next sibling, if any.  */
16091           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16092           continue;
16093         }
16094
16095       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16096                                    info_ptr);
16097
16098       /* This two-pass algorithm for processing partial symbols has a
16099          high cost in cache pressure.  Thus, handle some simple cases
16100          here which cover the majority of C partial symbols.  DIEs
16101          which neither have specification tags in them, nor could have
16102          specification tags elsewhere pointing at them, can simply be
16103          processed and discarded.
16104
16105          This segment is also optional; scan_partial_symbols and
16106          add_partial_symbol will handle these DIEs if we chain
16107          them in normally.  When compilers which do not emit large
16108          quantities of duplicate debug information are more common,
16109          this code can probably be removed.  */
16110
16111       /* Any complete simple types at the top level (pretty much all
16112          of them, for a language without namespaces), can be processed
16113          directly.  */
16114       if (parent_die == NULL
16115           && part_die->has_specification == 0
16116           && part_die->is_declaration == 0
16117           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16118               || part_die->tag == DW_TAG_base_type
16119               || part_die->tag == DW_TAG_subrange_type))
16120         {
16121           if (building_psymtab && part_die->name != NULL)
16122             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16123                                  VAR_DOMAIN, LOC_TYPEDEF,
16124                                  &objfile->static_psymbols,
16125                                  0, cu->language, objfile);
16126           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16127           continue;
16128         }
16129
16130       /* The exception for DW_TAG_typedef with has_children above is
16131          a workaround of GCC PR debug/47510.  In the case of this complaint
16132          type_name_no_tag_or_error will error on such types later.
16133
16134          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16135          it could not find the child DIEs referenced later, this is checked
16136          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16137
16138       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16139         complaint (&symfile_complaints,
16140                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16141                      "- DIE at 0x%x [in module %s]"),
16142                    to_underlying (part_die->sect_off), objfile_name (objfile));
16143
16144       /* If we're at the second level, and we're an enumerator, and
16145          our parent has no specification (meaning possibly lives in a
16146          namespace elsewhere), then we can add the partial symbol now
16147          instead of queueing it.  */
16148       if (part_die->tag == DW_TAG_enumerator
16149           && parent_die != NULL
16150           && parent_die->die_parent == NULL
16151           && parent_die->tag == DW_TAG_enumeration_type
16152           && parent_die->has_specification == 0)
16153         {
16154           if (part_die->name == NULL)
16155             complaint (&symfile_complaints,
16156                        _("malformed enumerator DIE ignored"));
16157           else if (building_psymtab)
16158             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16159                                  VAR_DOMAIN, LOC_CONST,
16160                                  cu->language == language_cplus
16161                                  ? &objfile->global_psymbols
16162                                  : &objfile->static_psymbols,
16163                                  0, cu->language, objfile);
16164
16165           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16166           continue;
16167         }
16168
16169       /* We'll save this DIE so link it in.  */
16170       part_die->die_parent = parent_die;
16171       part_die->die_sibling = NULL;
16172       part_die->die_child = NULL;
16173
16174       if (last_die && last_die == parent_die)
16175         last_die->die_child = part_die;
16176       else if (last_die)
16177         last_die->die_sibling = part_die;
16178
16179       last_die = part_die;
16180
16181       if (first_die == NULL)
16182         first_die = part_die;
16183
16184       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16185          find interesting need to be in the hash table, because we
16186          also have the parent/sibling/child chains; only those that we
16187          might refer to by offset later during partial symbol reading.
16188
16189          For now this means things that might have be the target of a
16190          DW_AT_specification, DW_AT_abstract_origin, or
16191          DW_AT_extension.  DW_AT_extension will refer only to
16192          namespaces; DW_AT_abstract_origin refers to functions (and
16193          many things under the function DIE, but we do not recurse
16194          into function DIEs during partial symbol reading) and
16195          possibly variables as well; DW_AT_specification refers to
16196          declarations.  Declarations ought to have the DW_AT_declaration
16197          flag.  It happens that GCC forgets to put it in sometimes, but
16198          only for functions, not for types.
16199
16200          Adding more things than necessary to the hash table is harmless
16201          except for the performance cost.  Adding too few will result in
16202          wasted time in find_partial_die, when we reread the compilation
16203          unit with load_all_dies set.  */
16204
16205       if (load_all
16206           || abbrev->tag == DW_TAG_constant
16207           || abbrev->tag == DW_TAG_subprogram
16208           || abbrev->tag == DW_TAG_variable
16209           || abbrev->tag == DW_TAG_namespace
16210           || part_die->is_declaration)
16211         {
16212           void **slot;
16213
16214           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16215                                            to_underlying (part_die->sect_off),
16216                                            INSERT);
16217           *slot = part_die;
16218         }
16219
16220       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16221
16222       /* For some DIEs we want to follow their children (if any).  For C
16223          we have no reason to follow the children of structures; for other
16224          languages we have to, so that we can get at method physnames
16225          to infer fully qualified class names, for DW_AT_specification,
16226          and for C++ template arguments.  For C++, we also look one level
16227          inside functions to find template arguments (if the name of the
16228          function does not already contain the template arguments).
16229
16230          For Ada, we need to scan the children of subprograms and lexical
16231          blocks as well because Ada allows the definition of nested
16232          entities that could be interesting for the debugger, such as
16233          nested subprograms for instance.  */
16234       if (last_die->has_children
16235           && (load_all
16236               || last_die->tag == DW_TAG_namespace
16237               || last_die->tag == DW_TAG_module
16238               || last_die->tag == DW_TAG_enumeration_type
16239               || (cu->language == language_cplus
16240                   && last_die->tag == DW_TAG_subprogram
16241                   && (last_die->name == NULL
16242                       || strchr (last_die->name, '<') == NULL))
16243               || (cu->language != language_c
16244                   && (last_die->tag == DW_TAG_class_type
16245                       || last_die->tag == DW_TAG_interface_type
16246                       || last_die->tag == DW_TAG_structure_type
16247                       || last_die->tag == DW_TAG_union_type))
16248               || (cu->language == language_ada
16249                   && (last_die->tag == DW_TAG_subprogram
16250                       || last_die->tag == DW_TAG_lexical_block))))
16251         {
16252           nesting_level++;
16253           parent_die = last_die;
16254           continue;
16255         }
16256
16257       /* Otherwise we skip to the next sibling, if any.  */
16258       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16259
16260       /* Back to the top, do it again.  */
16261     }
16262 }
16263
16264 /* Read a minimal amount of information into the minimal die structure.  */
16265
16266 static const gdb_byte *
16267 read_partial_die (const struct die_reader_specs *reader,
16268                   struct partial_die_info *part_die,
16269                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16270                   const gdb_byte *info_ptr)
16271 {
16272   struct dwarf2_cu *cu = reader->cu;
16273   struct objfile *objfile = cu->objfile;
16274   const gdb_byte *buffer = reader->buffer;
16275   unsigned int i;
16276   struct attribute attr;
16277   int has_low_pc_attr = 0;
16278   int has_high_pc_attr = 0;
16279   int high_pc_relative = 0;
16280
16281   memset (part_die, 0, sizeof (struct partial_die_info));
16282
16283   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16284
16285   info_ptr += abbrev_len;
16286
16287   if (abbrev == NULL)
16288     return info_ptr;
16289
16290   part_die->tag = abbrev->tag;
16291   part_die->has_children = abbrev->has_children;
16292
16293   for (i = 0; i < abbrev->num_attrs; ++i)
16294     {
16295       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16296
16297       /* Store the data if it is of an attribute we want to keep in a
16298          partial symbol table.  */
16299       switch (attr.name)
16300         {
16301         case DW_AT_name:
16302           switch (part_die->tag)
16303             {
16304             case DW_TAG_compile_unit:
16305             case DW_TAG_partial_unit:
16306             case DW_TAG_type_unit:
16307               /* Compilation units have a DW_AT_name that is a filename, not
16308                  a source language identifier.  */
16309             case DW_TAG_enumeration_type:
16310             case DW_TAG_enumerator:
16311               /* These tags always have simple identifiers already; no need
16312                  to canonicalize them.  */
16313               part_die->name = DW_STRING (&attr);
16314               break;
16315             default:
16316               part_die->name
16317                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16318                                             &objfile->per_bfd->storage_obstack);
16319               break;
16320             }
16321           break;
16322         case DW_AT_linkage_name:
16323         case DW_AT_MIPS_linkage_name:
16324           /* Note that both forms of linkage name might appear.  We
16325              assume they will be the same, and we only store the last
16326              one we see.  */
16327           if (cu->language == language_ada)
16328             part_die->name = DW_STRING (&attr);
16329           part_die->linkage_name = DW_STRING (&attr);
16330           break;
16331         case DW_AT_low_pc:
16332           has_low_pc_attr = 1;
16333           part_die->lowpc = attr_value_as_address (&attr);
16334           break;
16335         case DW_AT_high_pc:
16336           has_high_pc_attr = 1;
16337           part_die->highpc = attr_value_as_address (&attr);
16338           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16339                 high_pc_relative = 1;
16340           break;
16341         case DW_AT_location:
16342           /* Support the .debug_loc offsets.  */
16343           if (attr_form_is_block (&attr))
16344             {
16345                part_die->d.locdesc = DW_BLOCK (&attr);
16346             }
16347           else if (attr_form_is_section_offset (&attr))
16348             {
16349               dwarf2_complex_location_expr_complaint ();
16350             }
16351           else
16352             {
16353               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16354                                                      "partial symbol information");
16355             }
16356           break;
16357         case DW_AT_external:
16358           part_die->is_external = DW_UNSND (&attr);
16359           break;
16360         case DW_AT_declaration:
16361           part_die->is_declaration = DW_UNSND (&attr);
16362           break;
16363         case DW_AT_type:
16364           part_die->has_type = 1;
16365           break;
16366         case DW_AT_abstract_origin:
16367         case DW_AT_specification:
16368         case DW_AT_extension:
16369           part_die->has_specification = 1;
16370           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16371           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16372                                    || cu->per_cu->is_dwz);
16373           break;
16374         case DW_AT_sibling:
16375           /* Ignore absolute siblings, they might point outside of
16376              the current compile unit.  */
16377           if (attr.form == DW_FORM_ref_addr)
16378             complaint (&symfile_complaints,
16379                        _("ignoring absolute DW_AT_sibling"));
16380           else
16381             {
16382               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16383               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16384
16385               if (sibling_ptr < info_ptr)
16386                 complaint (&symfile_complaints,
16387                            _("DW_AT_sibling points backwards"));
16388               else if (sibling_ptr > reader->buffer_end)
16389                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16390               else
16391                 part_die->sibling = sibling_ptr;
16392             }
16393           break;
16394         case DW_AT_byte_size:
16395           part_die->has_byte_size = 1;
16396           break;
16397         case DW_AT_const_value:
16398           part_die->has_const_value = 1;
16399           break;
16400         case DW_AT_calling_convention:
16401           /* DWARF doesn't provide a way to identify a program's source-level
16402              entry point.  DW_AT_calling_convention attributes are only meant
16403              to describe functions' calling conventions.
16404
16405              However, because it's a necessary piece of information in
16406              Fortran, and before DWARF 4 DW_CC_program was the only
16407              piece of debugging information whose definition refers to
16408              a 'main program' at all, several compilers marked Fortran
16409              main programs with DW_CC_program --- even when those
16410              functions use the standard calling conventions.
16411
16412              Although DWARF now specifies a way to provide this
16413              information, we support this practice for backward
16414              compatibility.  */
16415           if (DW_UNSND (&attr) == DW_CC_program
16416               && cu->language == language_fortran)
16417             part_die->main_subprogram = 1;
16418           break;
16419         case DW_AT_inline:
16420           if (DW_UNSND (&attr) == DW_INL_inlined
16421               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16422             part_die->may_be_inlined = 1;
16423           break;
16424
16425         case DW_AT_import:
16426           if (part_die->tag == DW_TAG_imported_unit)
16427             {
16428               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16429               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16430                                   || cu->per_cu->is_dwz);
16431             }
16432           break;
16433
16434         case DW_AT_main_subprogram:
16435           part_die->main_subprogram = DW_UNSND (&attr);
16436           break;
16437
16438         default:
16439           break;
16440         }
16441     }
16442
16443   if (high_pc_relative)
16444     part_die->highpc += part_die->lowpc;
16445
16446   if (has_low_pc_attr && has_high_pc_attr)
16447     {
16448       /* When using the GNU linker, .gnu.linkonce. sections are used to
16449          eliminate duplicate copies of functions and vtables and such.
16450          The linker will arbitrarily choose one and discard the others.
16451          The AT_*_pc values for such functions refer to local labels in
16452          these sections.  If the section from that file was discarded, the
16453          labels are not in the output, so the relocs get a value of 0.
16454          If this is a discarded function, mark the pc bounds as invalid,
16455          so that GDB will ignore it.  */
16456       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16457         {
16458           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16459
16460           complaint (&symfile_complaints,
16461                      _("DW_AT_low_pc %s is zero "
16462                        "for DIE at 0x%x [in module %s]"),
16463                      paddress (gdbarch, part_die->lowpc),
16464                      to_underlying (part_die->sect_off), objfile_name (objfile));
16465         }
16466       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16467       else if (part_die->lowpc >= part_die->highpc)
16468         {
16469           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16470
16471           complaint (&symfile_complaints,
16472                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16473                        "for DIE at 0x%x [in module %s]"),
16474                      paddress (gdbarch, part_die->lowpc),
16475                      paddress (gdbarch, part_die->highpc),
16476                      to_underlying (part_die->sect_off),
16477                      objfile_name (objfile));
16478         }
16479       else
16480         part_die->has_pc_info = 1;
16481     }
16482
16483   return info_ptr;
16484 }
16485
16486 /* Find a cached partial DIE at OFFSET in CU.  */
16487
16488 static struct partial_die_info *
16489 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16490 {
16491   struct partial_die_info *lookup_die = NULL;
16492   struct partial_die_info part_die;
16493
16494   part_die.sect_off = sect_off;
16495   lookup_die = ((struct partial_die_info *)
16496                 htab_find_with_hash (cu->partial_dies, &part_die,
16497                                      to_underlying (sect_off)));
16498
16499   return lookup_die;
16500 }
16501
16502 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16503    except in the case of .debug_types DIEs which do not reference
16504    outside their CU (they do however referencing other types via
16505    DW_FORM_ref_sig8).  */
16506
16507 static struct partial_die_info *
16508 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16509 {
16510   struct objfile *objfile = cu->objfile;
16511   struct dwarf2_per_cu_data *per_cu = NULL;
16512   struct partial_die_info *pd = NULL;
16513
16514   if (offset_in_dwz == cu->per_cu->is_dwz
16515       && offset_in_cu_p (&cu->header, sect_off))
16516     {
16517       pd = find_partial_die_in_comp_unit (sect_off, cu);
16518       if (pd != NULL)
16519         return pd;
16520       /* We missed recording what we needed.
16521          Load all dies and try again.  */
16522       per_cu = cu->per_cu;
16523     }
16524   else
16525     {
16526       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16527       if (cu->per_cu->is_debug_types)
16528         {
16529           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16530                    " external reference to offset 0x%x [in module %s].\n"),
16531                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16532                  bfd_get_filename (objfile->obfd));
16533         }
16534       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16535                                                  objfile);
16536
16537       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16538         load_partial_comp_unit (per_cu);
16539
16540       per_cu->cu->last_used = 0;
16541       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16542     }
16543
16544   /* If we didn't find it, and not all dies have been loaded,
16545      load them all and try again.  */
16546
16547   if (pd == NULL && per_cu->load_all_dies == 0)
16548     {
16549       per_cu->load_all_dies = 1;
16550
16551       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16552          THIS_CU->cu may already be in use.  So we can't just free it and
16553          replace its DIEs with the ones we read in.  Instead, we leave those
16554          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16555          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16556          set.  */
16557       load_partial_comp_unit (per_cu);
16558
16559       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16560     }
16561
16562   if (pd == NULL)
16563     internal_error (__FILE__, __LINE__,
16564                     _("could not find partial DIE 0x%x "
16565                       "in cache [from module %s]\n"),
16566                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16567   return pd;
16568 }
16569
16570 /* See if we can figure out if the class lives in a namespace.  We do
16571    this by looking for a member function; its demangled name will
16572    contain namespace info, if there is any.  */
16573
16574 static void
16575 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16576                                   struct dwarf2_cu *cu)
16577 {
16578   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16579      what template types look like, because the demangler
16580      frequently doesn't give the same name as the debug info.  We
16581      could fix this by only using the demangled name to get the
16582      prefix (but see comment in read_structure_type).  */
16583
16584   struct partial_die_info *real_pdi;
16585   struct partial_die_info *child_pdi;
16586
16587   /* If this DIE (this DIE's specification, if any) has a parent, then
16588      we should not do this.  We'll prepend the parent's fully qualified
16589      name when we create the partial symbol.  */
16590
16591   real_pdi = struct_pdi;
16592   while (real_pdi->has_specification)
16593     real_pdi = find_partial_die (real_pdi->spec_offset,
16594                                  real_pdi->spec_is_dwz, cu);
16595
16596   if (real_pdi->die_parent != NULL)
16597     return;
16598
16599   for (child_pdi = struct_pdi->die_child;
16600        child_pdi != NULL;
16601        child_pdi = child_pdi->die_sibling)
16602     {
16603       if (child_pdi->tag == DW_TAG_subprogram
16604           && child_pdi->linkage_name != NULL)
16605         {
16606           char *actual_class_name
16607             = language_class_name_from_physname (cu->language_defn,
16608                                                  child_pdi->linkage_name);
16609           if (actual_class_name != NULL)
16610             {
16611               struct_pdi->name
16612                 = ((const char *)
16613                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16614                                   actual_class_name,
16615                                   strlen (actual_class_name)));
16616               xfree (actual_class_name);
16617             }
16618           break;
16619         }
16620     }
16621 }
16622
16623 /* Adjust PART_DIE before generating a symbol for it.  This function
16624    may set the is_external flag or change the DIE's name.  */
16625
16626 static void
16627 fixup_partial_die (struct partial_die_info *part_die,
16628                    struct dwarf2_cu *cu)
16629 {
16630   /* Once we've fixed up a die, there's no point in doing so again.
16631      This also avoids a memory leak if we were to call
16632      guess_partial_die_structure_name multiple times.  */
16633   if (part_die->fixup_called)
16634     return;
16635
16636   /* If we found a reference attribute and the DIE has no name, try
16637      to find a name in the referred to DIE.  */
16638
16639   if (part_die->name == NULL && part_die->has_specification)
16640     {
16641       struct partial_die_info *spec_die;
16642
16643       spec_die = find_partial_die (part_die->spec_offset,
16644                                    part_die->spec_is_dwz, cu);
16645
16646       fixup_partial_die (spec_die, cu);
16647
16648       if (spec_die->name)
16649         {
16650           part_die->name = spec_die->name;
16651
16652           /* Copy DW_AT_external attribute if it is set.  */
16653           if (spec_die->is_external)
16654             part_die->is_external = spec_die->is_external;
16655         }
16656     }
16657
16658   /* Set default names for some unnamed DIEs.  */
16659
16660   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16661     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16662
16663   /* If there is no parent die to provide a namespace, and there are
16664      children, see if we can determine the namespace from their linkage
16665      name.  */
16666   if (cu->language == language_cplus
16667       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16668       && part_die->die_parent == NULL
16669       && part_die->has_children
16670       && (part_die->tag == DW_TAG_class_type
16671           || part_die->tag == DW_TAG_structure_type
16672           || part_die->tag == DW_TAG_union_type))
16673     guess_partial_die_structure_name (part_die, cu);
16674
16675   /* GCC might emit a nameless struct or union that has a linkage
16676      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16677   if (part_die->name == NULL
16678       && (part_die->tag == DW_TAG_class_type
16679           || part_die->tag == DW_TAG_interface_type
16680           || part_die->tag == DW_TAG_structure_type
16681           || part_die->tag == DW_TAG_union_type)
16682       && part_die->linkage_name != NULL)
16683     {
16684       char *demangled;
16685
16686       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16687       if (demangled)
16688         {
16689           const char *base;
16690
16691           /* Strip any leading namespaces/classes, keep only the base name.
16692              DW_AT_name for named DIEs does not contain the prefixes.  */
16693           base = strrchr (demangled, ':');
16694           if (base && base > demangled && base[-1] == ':')
16695             base++;
16696           else
16697             base = demangled;
16698
16699           part_die->name
16700             = ((const char *)
16701                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16702                               base, strlen (base)));
16703           xfree (demangled);
16704         }
16705     }
16706
16707   part_die->fixup_called = 1;
16708 }
16709
16710 /* Read an attribute value described by an attribute form.  */
16711
16712 static const gdb_byte *
16713 read_attribute_value (const struct die_reader_specs *reader,
16714                       struct attribute *attr, unsigned form,
16715                       LONGEST implicit_const, const gdb_byte *info_ptr)
16716 {
16717   struct dwarf2_cu *cu = reader->cu;
16718   struct objfile *objfile = cu->objfile;
16719   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16720   bfd *abfd = reader->abfd;
16721   struct comp_unit_head *cu_header = &cu->header;
16722   unsigned int bytes_read;
16723   struct dwarf_block *blk;
16724
16725   attr->form = (enum dwarf_form) form;
16726   switch (form)
16727     {
16728     case DW_FORM_ref_addr:
16729       if (cu->header.version == 2)
16730         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16731       else
16732         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16733                                        &cu->header, &bytes_read);
16734       info_ptr += bytes_read;
16735       break;
16736     case DW_FORM_GNU_ref_alt:
16737       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16738       info_ptr += bytes_read;
16739       break;
16740     case DW_FORM_addr:
16741       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16742       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16743       info_ptr += bytes_read;
16744       break;
16745     case DW_FORM_block2:
16746       blk = dwarf_alloc_block (cu);
16747       blk->size = read_2_bytes (abfd, info_ptr);
16748       info_ptr += 2;
16749       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16750       info_ptr += blk->size;
16751       DW_BLOCK (attr) = blk;
16752       break;
16753     case DW_FORM_block4:
16754       blk = dwarf_alloc_block (cu);
16755       blk->size = read_4_bytes (abfd, info_ptr);
16756       info_ptr += 4;
16757       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16758       info_ptr += blk->size;
16759       DW_BLOCK (attr) = blk;
16760       break;
16761     case DW_FORM_data2:
16762       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16763       info_ptr += 2;
16764       break;
16765     case DW_FORM_data4:
16766       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16767       info_ptr += 4;
16768       break;
16769     case DW_FORM_data8:
16770       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16771       info_ptr += 8;
16772       break;
16773     case DW_FORM_data16:
16774       blk = dwarf_alloc_block (cu);
16775       blk->size = 16;
16776       blk->data = read_n_bytes (abfd, info_ptr, 16);
16777       info_ptr += 16;
16778       DW_BLOCK (attr) = blk;
16779       break;
16780     case DW_FORM_sec_offset:
16781       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16782       info_ptr += bytes_read;
16783       break;
16784     case DW_FORM_string:
16785       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16786       DW_STRING_IS_CANONICAL (attr) = 0;
16787       info_ptr += bytes_read;
16788       break;
16789     case DW_FORM_strp:
16790       if (!cu->per_cu->is_dwz)
16791         {
16792           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16793                                                    &bytes_read);
16794           DW_STRING_IS_CANONICAL (attr) = 0;
16795           info_ptr += bytes_read;
16796           break;
16797         }
16798       /* FALLTHROUGH */
16799     case DW_FORM_line_strp:
16800       if (!cu->per_cu->is_dwz)
16801         {
16802           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16803                                                         cu_header, &bytes_read);
16804           DW_STRING_IS_CANONICAL (attr) = 0;
16805           info_ptr += bytes_read;
16806           break;
16807         }
16808       /* FALLTHROUGH */
16809     case DW_FORM_GNU_strp_alt:
16810       {
16811         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16812         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16813                                           &bytes_read);
16814
16815         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16816         DW_STRING_IS_CANONICAL (attr) = 0;
16817         info_ptr += bytes_read;
16818       }
16819       break;
16820     case DW_FORM_exprloc:
16821     case DW_FORM_block:
16822       blk = dwarf_alloc_block (cu);
16823       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16824       info_ptr += bytes_read;
16825       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16826       info_ptr += blk->size;
16827       DW_BLOCK (attr) = blk;
16828       break;
16829     case DW_FORM_block1:
16830       blk = dwarf_alloc_block (cu);
16831       blk->size = read_1_byte (abfd, info_ptr);
16832       info_ptr += 1;
16833       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16834       info_ptr += blk->size;
16835       DW_BLOCK (attr) = blk;
16836       break;
16837     case DW_FORM_data1:
16838       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16839       info_ptr += 1;
16840       break;
16841     case DW_FORM_flag:
16842       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16843       info_ptr += 1;
16844       break;
16845     case DW_FORM_flag_present:
16846       DW_UNSND (attr) = 1;
16847       break;
16848     case DW_FORM_sdata:
16849       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16850       info_ptr += bytes_read;
16851       break;
16852     case DW_FORM_udata:
16853       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16854       info_ptr += bytes_read;
16855       break;
16856     case DW_FORM_ref1:
16857       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16858                          + read_1_byte (abfd, info_ptr));
16859       info_ptr += 1;
16860       break;
16861     case DW_FORM_ref2:
16862       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16863                          + read_2_bytes (abfd, info_ptr));
16864       info_ptr += 2;
16865       break;
16866     case DW_FORM_ref4:
16867       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16868                          + read_4_bytes (abfd, info_ptr));
16869       info_ptr += 4;
16870       break;
16871     case DW_FORM_ref8:
16872       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16873                          + read_8_bytes (abfd, info_ptr));
16874       info_ptr += 8;
16875       break;
16876     case DW_FORM_ref_sig8:
16877       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16878       info_ptr += 8;
16879       break;
16880     case DW_FORM_ref_udata:
16881       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16882                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16883       info_ptr += bytes_read;
16884       break;
16885     case DW_FORM_indirect:
16886       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16887       info_ptr += bytes_read;
16888       if (form == DW_FORM_implicit_const)
16889         {
16890           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16891           info_ptr += bytes_read;
16892         }
16893       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16894                                        info_ptr);
16895       break;
16896     case DW_FORM_implicit_const:
16897       DW_SND (attr) = implicit_const;
16898       break;
16899     case DW_FORM_GNU_addr_index:
16900       if (reader->dwo_file == NULL)
16901         {
16902           /* For now flag a hard error.
16903              Later we can turn this into a complaint.  */
16904           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16905                  dwarf_form_name (form),
16906                  bfd_get_filename (abfd));
16907         }
16908       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16909       info_ptr += bytes_read;
16910       break;
16911     case DW_FORM_GNU_str_index:
16912       if (reader->dwo_file == NULL)
16913         {
16914           /* For now flag a hard error.
16915              Later we can turn this into a complaint if warranted.  */
16916           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16917                  dwarf_form_name (form),
16918                  bfd_get_filename (abfd));
16919         }
16920       {
16921         ULONGEST str_index =
16922           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16923
16924         DW_STRING (attr) = read_str_index (reader, str_index);
16925         DW_STRING_IS_CANONICAL (attr) = 0;
16926         info_ptr += bytes_read;
16927       }
16928       break;
16929     default:
16930       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16931              dwarf_form_name (form),
16932              bfd_get_filename (abfd));
16933     }
16934
16935   /* Super hack.  */
16936   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16937     attr->form = DW_FORM_GNU_ref_alt;
16938
16939   /* We have seen instances where the compiler tried to emit a byte
16940      size attribute of -1 which ended up being encoded as an unsigned
16941      0xffffffff.  Although 0xffffffff is technically a valid size value,
16942      an object of this size seems pretty unlikely so we can relatively
16943      safely treat these cases as if the size attribute was invalid and
16944      treat them as zero by default.  */
16945   if (attr->name == DW_AT_byte_size
16946       && form == DW_FORM_data4
16947       && DW_UNSND (attr) >= 0xffffffff)
16948     {
16949       complaint
16950         (&symfile_complaints,
16951          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16952          hex_string (DW_UNSND (attr)));
16953       DW_UNSND (attr) = 0;
16954     }
16955
16956   return info_ptr;
16957 }
16958
16959 /* Read an attribute described by an abbreviated attribute.  */
16960
16961 static const gdb_byte *
16962 read_attribute (const struct die_reader_specs *reader,
16963                 struct attribute *attr, struct attr_abbrev *abbrev,
16964                 const gdb_byte *info_ptr)
16965 {
16966   attr->name = abbrev->name;
16967   return read_attribute_value (reader, attr, abbrev->form,
16968                                abbrev->implicit_const, info_ptr);
16969 }
16970
16971 /* Read dwarf information from a buffer.  */
16972
16973 static unsigned int
16974 read_1_byte (bfd *abfd, const gdb_byte *buf)
16975 {
16976   return bfd_get_8 (abfd, buf);
16977 }
16978
16979 static int
16980 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16981 {
16982   return bfd_get_signed_8 (abfd, buf);
16983 }
16984
16985 static unsigned int
16986 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16987 {
16988   return bfd_get_16 (abfd, buf);
16989 }
16990
16991 static int
16992 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16993 {
16994   return bfd_get_signed_16 (abfd, buf);
16995 }
16996
16997 static unsigned int
16998 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16999 {
17000   return bfd_get_32 (abfd, buf);
17001 }
17002
17003 static int
17004 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17005 {
17006   return bfd_get_signed_32 (abfd, buf);
17007 }
17008
17009 static ULONGEST
17010 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17011 {
17012   return bfd_get_64 (abfd, buf);
17013 }
17014
17015 static CORE_ADDR
17016 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17017               unsigned int *bytes_read)
17018 {
17019   struct comp_unit_head *cu_header = &cu->header;
17020   CORE_ADDR retval = 0;
17021
17022   if (cu_header->signed_addr_p)
17023     {
17024       switch (cu_header->addr_size)
17025         {
17026         case 2:
17027           retval = bfd_get_signed_16 (abfd, buf);
17028           break;
17029         case 4:
17030           retval = bfd_get_signed_32 (abfd, buf);
17031           break;
17032         case 8:
17033           retval = bfd_get_signed_64 (abfd, buf);
17034           break;
17035         default:
17036           internal_error (__FILE__, __LINE__,
17037                           _("read_address: bad switch, signed [in module %s]"),
17038                           bfd_get_filename (abfd));
17039         }
17040     }
17041   else
17042     {
17043       switch (cu_header->addr_size)
17044         {
17045         case 2:
17046           retval = bfd_get_16 (abfd, buf);
17047           break;
17048         case 4:
17049           retval = bfd_get_32 (abfd, buf);
17050           break;
17051         case 8:
17052           retval = bfd_get_64 (abfd, buf);
17053           break;
17054         default:
17055           internal_error (__FILE__, __LINE__,
17056                           _("read_address: bad switch, "
17057                             "unsigned [in module %s]"),
17058                           bfd_get_filename (abfd));
17059         }
17060     }
17061
17062   *bytes_read = cu_header->addr_size;
17063   return retval;
17064 }
17065
17066 /* Read the initial length from a section.  The (draft) DWARF 3
17067    specification allows the initial length to take up either 4 bytes
17068    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17069    bytes describe the length and all offsets will be 8 bytes in length
17070    instead of 4.
17071
17072    An older, non-standard 64-bit format is also handled by this
17073    function.  The older format in question stores the initial length
17074    as an 8-byte quantity without an escape value.  Lengths greater
17075    than 2^32 aren't very common which means that the initial 4 bytes
17076    is almost always zero.  Since a length value of zero doesn't make
17077    sense for the 32-bit format, this initial zero can be considered to
17078    be an escape value which indicates the presence of the older 64-bit
17079    format.  As written, the code can't detect (old format) lengths
17080    greater than 4GB.  If it becomes necessary to handle lengths
17081    somewhat larger than 4GB, we could allow other small values (such
17082    as the non-sensical values of 1, 2, and 3) to also be used as
17083    escape values indicating the presence of the old format.
17084
17085    The value returned via bytes_read should be used to increment the
17086    relevant pointer after calling read_initial_length().
17087
17088    [ Note:  read_initial_length() and read_offset() are based on the
17089      document entitled "DWARF Debugging Information Format", revision
17090      3, draft 8, dated November 19, 2001.  This document was obtained
17091      from:
17092
17093         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17094
17095      This document is only a draft and is subject to change.  (So beware.)
17096
17097      Details regarding the older, non-standard 64-bit format were
17098      determined empirically by examining 64-bit ELF files produced by
17099      the SGI toolchain on an IRIX 6.5 machine.
17100
17101      - Kevin, July 16, 2002
17102    ] */
17103
17104 static LONGEST
17105 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17106 {
17107   LONGEST length = bfd_get_32 (abfd, buf);
17108
17109   if (length == 0xffffffff)
17110     {
17111       length = bfd_get_64 (abfd, buf + 4);
17112       *bytes_read = 12;
17113     }
17114   else if (length == 0)
17115     {
17116       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17117       length = bfd_get_64 (abfd, buf);
17118       *bytes_read = 8;
17119     }
17120   else
17121     {
17122       *bytes_read = 4;
17123     }
17124
17125   return length;
17126 }
17127
17128 /* Cover function for read_initial_length.
17129    Returns the length of the object at BUF, and stores the size of the
17130    initial length in *BYTES_READ and stores the size that offsets will be in
17131    *OFFSET_SIZE.
17132    If the initial length size is not equivalent to that specified in
17133    CU_HEADER then issue a complaint.
17134    This is useful when reading non-comp-unit headers.  */
17135
17136 static LONGEST
17137 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17138                                         const struct comp_unit_head *cu_header,
17139                                         unsigned int *bytes_read,
17140                                         unsigned int *offset_size)
17141 {
17142   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17143
17144   gdb_assert (cu_header->initial_length_size == 4
17145               || cu_header->initial_length_size == 8
17146               || cu_header->initial_length_size == 12);
17147
17148   if (cu_header->initial_length_size != *bytes_read)
17149     complaint (&symfile_complaints,
17150                _("intermixed 32-bit and 64-bit DWARF sections"));
17151
17152   *offset_size = (*bytes_read == 4) ? 4 : 8;
17153   return length;
17154 }
17155
17156 /* Read an offset from the data stream.  The size of the offset is
17157    given by cu_header->offset_size.  */
17158
17159 static LONGEST
17160 read_offset (bfd *abfd, const gdb_byte *buf,
17161              const struct comp_unit_head *cu_header,
17162              unsigned int *bytes_read)
17163 {
17164   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17165
17166   *bytes_read = cu_header->offset_size;
17167   return offset;
17168 }
17169
17170 /* Read an offset from the data stream.  */
17171
17172 static LONGEST
17173 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17174 {
17175   LONGEST retval = 0;
17176
17177   switch (offset_size)
17178     {
17179     case 4:
17180       retval = bfd_get_32 (abfd, buf);
17181       break;
17182     case 8:
17183       retval = bfd_get_64 (abfd, buf);
17184       break;
17185     default:
17186       internal_error (__FILE__, __LINE__,
17187                       _("read_offset_1: bad switch [in module %s]"),
17188                       bfd_get_filename (abfd));
17189     }
17190
17191   return retval;
17192 }
17193
17194 static const gdb_byte *
17195 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17196 {
17197   /* If the size of a host char is 8 bits, we can return a pointer
17198      to the buffer, otherwise we have to copy the data to a buffer
17199      allocated on the temporary obstack.  */
17200   gdb_assert (HOST_CHAR_BIT == 8);
17201   return buf;
17202 }
17203
17204 static const char *
17205 read_direct_string (bfd *abfd, const gdb_byte *buf,
17206                     unsigned int *bytes_read_ptr)
17207 {
17208   /* If the size of a host char is 8 bits, we can return a pointer
17209      to the string, otherwise we have to copy the string to a buffer
17210      allocated on the temporary obstack.  */
17211   gdb_assert (HOST_CHAR_BIT == 8);
17212   if (*buf == '\0')
17213     {
17214       *bytes_read_ptr = 1;
17215       return NULL;
17216     }
17217   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17218   return (const char *) buf;
17219 }
17220
17221 /* Return pointer to string at section SECT offset STR_OFFSET with error
17222    reporting strings FORM_NAME and SECT_NAME.  */
17223
17224 static const char *
17225 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17226                                      struct dwarf2_section_info *sect,
17227                                      const char *form_name,
17228                                      const char *sect_name)
17229 {
17230   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17231   if (sect->buffer == NULL)
17232     error (_("%s used without %s section [in module %s]"),
17233            form_name, sect_name, bfd_get_filename (abfd));
17234   if (str_offset >= sect->size)
17235     error (_("%s pointing outside of %s section [in module %s]"),
17236            form_name, sect_name, bfd_get_filename (abfd));
17237   gdb_assert (HOST_CHAR_BIT == 8);
17238   if (sect->buffer[str_offset] == '\0')
17239     return NULL;
17240   return (const char *) (sect->buffer + str_offset);
17241 }
17242
17243 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17244
17245 static const char *
17246 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17247 {
17248   return read_indirect_string_at_offset_from (abfd, str_offset,
17249                                               &dwarf2_per_objfile->str,
17250                                               "DW_FORM_strp", ".debug_str");
17251 }
17252
17253 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17254
17255 static const char *
17256 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17257 {
17258   return read_indirect_string_at_offset_from (abfd, str_offset,
17259                                               &dwarf2_per_objfile->line_str,
17260                                               "DW_FORM_line_strp",
17261                                               ".debug_line_str");
17262 }
17263
17264 /* Read a string at offset STR_OFFSET in the .debug_str section from
17265    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17266    the string consists of a single NUL byte, return NULL; otherwise
17267    return a pointer to the string.  */
17268
17269 static const char *
17270 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17271 {
17272   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17273
17274   if (dwz->str.buffer == NULL)
17275     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17276              "section [in module %s]"),
17277            bfd_get_filename (dwz->dwz_bfd));
17278   if (str_offset >= dwz->str.size)
17279     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17280              ".debug_str section [in module %s]"),
17281            bfd_get_filename (dwz->dwz_bfd));
17282   gdb_assert (HOST_CHAR_BIT == 8);
17283   if (dwz->str.buffer[str_offset] == '\0')
17284     return NULL;
17285   return (const char *) (dwz->str.buffer + str_offset);
17286 }
17287
17288 /* Return pointer to string at .debug_str offset as read from BUF.
17289    BUF is assumed to be in a compilation unit described by CU_HEADER.
17290    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17291
17292 static const char *
17293 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17294                       const struct comp_unit_head *cu_header,
17295                       unsigned int *bytes_read_ptr)
17296 {
17297   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17298
17299   return read_indirect_string_at_offset (abfd, str_offset);
17300 }
17301
17302 /* Return pointer to string at .debug_line_str offset as read from BUF.
17303    BUF is assumed to be in a compilation unit described by CU_HEADER.
17304    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17305
17306 static const char *
17307 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17308                            const struct comp_unit_head *cu_header,
17309                            unsigned int *bytes_read_ptr)
17310 {
17311   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17312
17313   return read_indirect_line_string_at_offset (abfd, str_offset);
17314 }
17315
17316 ULONGEST
17317 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17318                           unsigned int *bytes_read_ptr)
17319 {
17320   ULONGEST result;
17321   unsigned int num_read;
17322   int shift;
17323   unsigned char byte;
17324
17325   result = 0;
17326   shift = 0;
17327   num_read = 0;
17328   while (1)
17329     {
17330       byte = bfd_get_8 (abfd, buf);
17331       buf++;
17332       num_read++;
17333       result |= ((ULONGEST) (byte & 127) << shift);
17334       if ((byte & 128) == 0)
17335         {
17336           break;
17337         }
17338       shift += 7;
17339     }
17340   *bytes_read_ptr = num_read;
17341   return result;
17342 }
17343
17344 static LONGEST
17345 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17346                     unsigned int *bytes_read_ptr)
17347 {
17348   LONGEST result;
17349   int shift, num_read;
17350   unsigned char byte;
17351
17352   result = 0;
17353   shift = 0;
17354   num_read = 0;
17355   while (1)
17356     {
17357       byte = bfd_get_8 (abfd, buf);
17358       buf++;
17359       num_read++;
17360       result |= ((LONGEST) (byte & 127) << shift);
17361       shift += 7;
17362       if ((byte & 128) == 0)
17363         {
17364           break;
17365         }
17366     }
17367   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17368     result |= -(((LONGEST) 1) << shift);
17369   *bytes_read_ptr = num_read;
17370   return result;
17371 }
17372
17373 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17374    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17375    ADDR_SIZE is the size of addresses from the CU header.  */
17376
17377 static CORE_ADDR
17378 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17379 {
17380   struct objfile *objfile = dwarf2_per_objfile->objfile;
17381   bfd *abfd = objfile->obfd;
17382   const gdb_byte *info_ptr;
17383
17384   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17385   if (dwarf2_per_objfile->addr.buffer == NULL)
17386     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17387            objfile_name (objfile));
17388   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17389     error (_("DW_FORM_addr_index pointing outside of "
17390              ".debug_addr section [in module %s]"),
17391            objfile_name (objfile));
17392   info_ptr = (dwarf2_per_objfile->addr.buffer
17393               + addr_base + addr_index * addr_size);
17394   if (addr_size == 4)
17395     return bfd_get_32 (abfd, info_ptr);
17396   else
17397     return bfd_get_64 (abfd, info_ptr);
17398 }
17399
17400 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17401
17402 static CORE_ADDR
17403 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17404 {
17405   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17406 }
17407
17408 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17409
17410 static CORE_ADDR
17411 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17412                              unsigned int *bytes_read)
17413 {
17414   bfd *abfd = cu->objfile->obfd;
17415   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17416
17417   return read_addr_index (cu, addr_index);
17418 }
17419
17420 /* Data structure to pass results from dwarf2_read_addr_index_reader
17421    back to dwarf2_read_addr_index.  */
17422
17423 struct dwarf2_read_addr_index_data
17424 {
17425   ULONGEST addr_base;
17426   int addr_size;
17427 };
17428
17429 /* die_reader_func for dwarf2_read_addr_index.  */
17430
17431 static void
17432 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17433                                const gdb_byte *info_ptr,
17434                                struct die_info *comp_unit_die,
17435                                int has_children,
17436                                void *data)
17437 {
17438   struct dwarf2_cu *cu = reader->cu;
17439   struct dwarf2_read_addr_index_data *aidata =
17440     (struct dwarf2_read_addr_index_data *) data;
17441
17442   aidata->addr_base = cu->addr_base;
17443   aidata->addr_size = cu->header.addr_size;
17444 }
17445
17446 /* Given an index in .debug_addr, fetch the value.
17447    NOTE: This can be called during dwarf expression evaluation,
17448    long after the debug information has been read, and thus per_cu->cu
17449    may no longer exist.  */
17450
17451 CORE_ADDR
17452 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17453                         unsigned int addr_index)
17454 {
17455   struct objfile *objfile = per_cu->objfile;
17456   struct dwarf2_cu *cu = per_cu->cu;
17457   ULONGEST addr_base;
17458   int addr_size;
17459
17460   /* This is intended to be called from outside this file.  */
17461   dw2_setup (objfile);
17462
17463   /* We need addr_base and addr_size.
17464      If we don't have PER_CU->cu, we have to get it.
17465      Nasty, but the alternative is storing the needed info in PER_CU,
17466      which at this point doesn't seem justified: it's not clear how frequently
17467      it would get used and it would increase the size of every PER_CU.
17468      Entry points like dwarf2_per_cu_addr_size do a similar thing
17469      so we're not in uncharted territory here.
17470      Alas we need to be a bit more complicated as addr_base is contained
17471      in the DIE.
17472
17473      We don't need to read the entire CU(/TU).
17474      We just need the header and top level die.
17475
17476      IWBN to use the aging mechanism to let us lazily later discard the CU.
17477      For now we skip this optimization.  */
17478
17479   if (cu != NULL)
17480     {
17481       addr_base = cu->addr_base;
17482       addr_size = cu->header.addr_size;
17483     }
17484   else
17485     {
17486       struct dwarf2_read_addr_index_data aidata;
17487
17488       /* Note: We can't use init_cutu_and_read_dies_simple here,
17489          we need addr_base.  */
17490       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17491                                dwarf2_read_addr_index_reader, &aidata);
17492       addr_base = aidata.addr_base;
17493       addr_size = aidata.addr_size;
17494     }
17495
17496   return read_addr_index_1 (addr_index, addr_base, addr_size);
17497 }
17498
17499 /* Given a DW_FORM_GNU_str_index, fetch the string.
17500    This is only used by the Fission support.  */
17501
17502 static const char *
17503 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17504 {
17505   struct objfile *objfile = dwarf2_per_objfile->objfile;
17506   const char *objf_name = objfile_name (objfile);
17507   bfd *abfd = objfile->obfd;
17508   struct dwarf2_cu *cu = reader->cu;
17509   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17510   struct dwarf2_section_info *str_offsets_section =
17511     &reader->dwo_file->sections.str_offsets;
17512   const gdb_byte *info_ptr;
17513   ULONGEST str_offset;
17514   static const char form_name[] = "DW_FORM_GNU_str_index";
17515
17516   dwarf2_read_section (objfile, str_section);
17517   dwarf2_read_section (objfile, str_offsets_section);
17518   if (str_section->buffer == NULL)
17519     error (_("%s used without .debug_str.dwo section"
17520              " in CU at offset 0x%x [in module %s]"),
17521            form_name, to_underlying (cu->header.sect_off), objf_name);
17522   if (str_offsets_section->buffer == NULL)
17523     error (_("%s used without .debug_str_offsets.dwo section"
17524              " in CU at offset 0x%x [in module %s]"),
17525            form_name, to_underlying (cu->header.sect_off), objf_name);
17526   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17527     error (_("%s pointing outside of .debug_str_offsets.dwo"
17528              " section in CU at offset 0x%x [in module %s]"),
17529            form_name, to_underlying (cu->header.sect_off), objf_name);
17530   info_ptr = (str_offsets_section->buffer
17531               + str_index * cu->header.offset_size);
17532   if (cu->header.offset_size == 4)
17533     str_offset = bfd_get_32 (abfd, info_ptr);
17534   else
17535     str_offset = bfd_get_64 (abfd, info_ptr);
17536   if (str_offset >= str_section->size)
17537     error (_("Offset from %s pointing outside of"
17538              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17539            form_name, to_underlying (cu->header.sect_off), objf_name);
17540   return (const char *) (str_section->buffer + str_offset);
17541 }
17542
17543 /* Return the length of an LEB128 number in BUF.  */
17544
17545 static int
17546 leb128_size (const gdb_byte *buf)
17547 {
17548   const gdb_byte *begin = buf;
17549   gdb_byte byte;
17550
17551   while (1)
17552     {
17553       byte = *buf++;
17554       if ((byte & 128) == 0)
17555         return buf - begin;
17556     }
17557 }
17558
17559 static void
17560 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17561 {
17562   switch (lang)
17563     {
17564     case DW_LANG_C89:
17565     case DW_LANG_C99:
17566     case DW_LANG_C11:
17567     case DW_LANG_C:
17568     case DW_LANG_UPC:
17569       cu->language = language_c;
17570       break;
17571     case DW_LANG_Java:
17572     case DW_LANG_C_plus_plus:
17573     case DW_LANG_C_plus_plus_11:
17574     case DW_LANG_C_plus_plus_14:
17575       cu->language = language_cplus;
17576       break;
17577     case DW_LANG_D:
17578       cu->language = language_d;
17579       break;
17580     case DW_LANG_Fortran77:
17581     case DW_LANG_Fortran90:
17582     case DW_LANG_Fortran95:
17583     case DW_LANG_Fortran03:
17584     case DW_LANG_Fortran08:
17585       cu->language = language_fortran;
17586       break;
17587     case DW_LANG_Go:
17588       cu->language = language_go;
17589       break;
17590     case DW_LANG_Mips_Assembler:
17591       cu->language = language_asm;
17592       break;
17593     case DW_LANG_Ada83:
17594     case DW_LANG_Ada95:
17595       cu->language = language_ada;
17596       break;
17597     case DW_LANG_Modula2:
17598       cu->language = language_m2;
17599       break;
17600     case DW_LANG_Pascal83:
17601       cu->language = language_pascal;
17602       break;
17603     case DW_LANG_ObjC:
17604       cu->language = language_objc;
17605       break;
17606     case DW_LANG_Rust:
17607     case DW_LANG_Rust_old:
17608       cu->language = language_rust;
17609       break;
17610     case DW_LANG_Cobol74:
17611     case DW_LANG_Cobol85:
17612     default:
17613       cu->language = language_minimal;
17614       break;
17615     }
17616   cu->language_defn = language_def (cu->language);
17617 }
17618
17619 /* Return the named attribute or NULL if not there.  */
17620
17621 static struct attribute *
17622 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17623 {
17624   for (;;)
17625     {
17626       unsigned int i;
17627       struct attribute *spec = NULL;
17628
17629       for (i = 0; i < die->num_attrs; ++i)
17630         {
17631           if (die->attrs[i].name == name)
17632             return &die->attrs[i];
17633           if (die->attrs[i].name == DW_AT_specification
17634               || die->attrs[i].name == DW_AT_abstract_origin)
17635             spec = &die->attrs[i];
17636         }
17637
17638       if (!spec)
17639         break;
17640
17641       die = follow_die_ref (die, spec, &cu);
17642     }
17643
17644   return NULL;
17645 }
17646
17647 /* Return the named attribute or NULL if not there,
17648    but do not follow DW_AT_specification, etc.
17649    This is for use in contexts where we're reading .debug_types dies.
17650    Following DW_AT_specification, DW_AT_abstract_origin will take us
17651    back up the chain, and we want to go down.  */
17652
17653 static struct attribute *
17654 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17655 {
17656   unsigned int i;
17657
17658   for (i = 0; i < die->num_attrs; ++i)
17659     if (die->attrs[i].name == name)
17660       return &die->attrs[i];
17661
17662   return NULL;
17663 }
17664
17665 /* Return the string associated with a string-typed attribute, or NULL if it
17666    is either not found or is of an incorrect type.  */
17667
17668 static const char *
17669 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17670 {
17671   struct attribute *attr;
17672   const char *str = NULL;
17673
17674   attr = dwarf2_attr (die, name, cu);
17675
17676   if (attr != NULL)
17677     {
17678       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17679           || attr->form == DW_FORM_string
17680           || attr->form == DW_FORM_GNU_str_index
17681           || attr->form == DW_FORM_GNU_strp_alt)
17682         str = DW_STRING (attr);
17683       else
17684         complaint (&symfile_complaints,
17685                    _("string type expected for attribute %s for "
17686                      "DIE at 0x%x in module %s"),
17687                    dwarf_attr_name (name), to_underlying (die->sect_off),
17688                    objfile_name (cu->objfile));
17689     }
17690
17691   return str;
17692 }
17693
17694 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17695    and holds a non-zero value.  This function should only be used for
17696    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17697
17698 static int
17699 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17700 {
17701   struct attribute *attr = dwarf2_attr (die, name, cu);
17702
17703   return (attr && DW_UNSND (attr));
17704 }
17705
17706 static int
17707 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17708 {
17709   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17710      which value is non-zero.  However, we have to be careful with
17711      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17712      (via dwarf2_flag_true_p) follows this attribute.  So we may
17713      end up accidently finding a declaration attribute that belongs
17714      to a different DIE referenced by the specification attribute,
17715      even though the given DIE does not have a declaration attribute.  */
17716   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17717           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17718 }
17719
17720 /* Return the die giving the specification for DIE, if there is
17721    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17722    containing the return value on output.  If there is no
17723    specification, but there is an abstract origin, that is
17724    returned.  */
17725
17726 static struct die_info *
17727 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17728 {
17729   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17730                                              *spec_cu);
17731
17732   if (spec_attr == NULL)
17733     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17734
17735   if (spec_attr == NULL)
17736     return NULL;
17737   else
17738     return follow_die_ref (die, spec_attr, spec_cu);
17739 }
17740
17741 /* Stub for free_line_header to match void * callback types.  */
17742
17743 static void
17744 free_line_header_voidp (void *arg)
17745 {
17746   struct line_header *lh = (struct line_header *) arg;
17747
17748   delete lh;
17749 }
17750
17751 void
17752 line_header::add_include_dir (const char *include_dir)
17753 {
17754   if (dwarf_line_debug >= 2)
17755     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17756                         include_dirs.size () + 1, include_dir);
17757
17758   include_dirs.push_back (include_dir);
17759 }
17760
17761 void
17762 line_header::add_file_name (const char *name,
17763                             dir_index d_index,
17764                             unsigned int mod_time,
17765                             unsigned int length)
17766 {
17767   if (dwarf_line_debug >= 2)
17768     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17769                         (unsigned) file_names.size () + 1, name);
17770
17771   file_names.emplace_back (name, d_index, mod_time, length);
17772 }
17773
17774 /* A convenience function to find the proper .debug_line section for a CU.  */
17775
17776 static struct dwarf2_section_info *
17777 get_debug_line_section (struct dwarf2_cu *cu)
17778 {
17779   struct dwarf2_section_info *section;
17780
17781   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17782      DWO file.  */
17783   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17784     section = &cu->dwo_unit->dwo_file->sections.line;
17785   else if (cu->per_cu->is_dwz)
17786     {
17787       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17788
17789       section = &dwz->line;
17790     }
17791   else
17792     section = &dwarf2_per_objfile->line;
17793
17794   return section;
17795 }
17796
17797 /* Read directory or file name entry format, starting with byte of
17798    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17799    entries count and the entries themselves in the described entry
17800    format.  */
17801
17802 static void
17803 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17804                         struct line_header *lh,
17805                         const struct comp_unit_head *cu_header,
17806                         void (*callback) (struct line_header *lh,
17807                                           const char *name,
17808                                           dir_index d_index,
17809                                           unsigned int mod_time,
17810                                           unsigned int length))
17811 {
17812   gdb_byte format_count, formati;
17813   ULONGEST data_count, datai;
17814   const gdb_byte *buf = *bufp;
17815   const gdb_byte *format_header_data;
17816   int i;
17817   unsigned int bytes_read;
17818
17819   format_count = read_1_byte (abfd, buf);
17820   buf += 1;
17821   format_header_data = buf;
17822   for (formati = 0; formati < format_count; formati++)
17823     {
17824       read_unsigned_leb128 (abfd, buf, &bytes_read);
17825       buf += bytes_read;
17826       read_unsigned_leb128 (abfd, buf, &bytes_read);
17827       buf += bytes_read;
17828     }
17829
17830   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17831   buf += bytes_read;
17832   for (datai = 0; datai < data_count; datai++)
17833     {
17834       const gdb_byte *format = format_header_data;
17835       struct file_entry fe;
17836
17837       for (formati = 0; formati < format_count; formati++)
17838         {
17839           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17840           format += bytes_read;
17841
17842           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17843           format += bytes_read;
17844
17845           gdb::optional<const char *> string;
17846           gdb::optional<unsigned int> uint;
17847
17848           switch (form)
17849             {
17850             case DW_FORM_string:
17851               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17852               buf += bytes_read;
17853               break;
17854
17855             case DW_FORM_line_strp:
17856               string.emplace (read_indirect_line_string (abfd, buf,
17857                                                          cu_header,
17858                                                          &bytes_read));
17859               buf += bytes_read;
17860               break;
17861
17862             case DW_FORM_data1:
17863               uint.emplace (read_1_byte (abfd, buf));
17864               buf += 1;
17865               break;
17866
17867             case DW_FORM_data2:
17868               uint.emplace (read_2_bytes (abfd, buf));
17869               buf += 2;
17870               break;
17871
17872             case DW_FORM_data4:
17873               uint.emplace (read_4_bytes (abfd, buf));
17874               buf += 4;
17875               break;
17876
17877             case DW_FORM_data8:
17878               uint.emplace (read_8_bytes (abfd, buf));
17879               buf += 8;
17880               break;
17881
17882             case DW_FORM_udata:
17883               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17884               buf += bytes_read;
17885               break;
17886
17887             case DW_FORM_block:
17888               /* It is valid only for DW_LNCT_timestamp which is ignored by
17889                  current GDB.  */
17890               break;
17891             }
17892
17893           switch (content_type)
17894             {
17895             case DW_LNCT_path:
17896               if (string.has_value ())
17897                 fe.name = *string;
17898               break;
17899             case DW_LNCT_directory_index:
17900               if (uint.has_value ())
17901                 fe.d_index = (dir_index) *uint;
17902               break;
17903             case DW_LNCT_timestamp:
17904               if (uint.has_value ())
17905                 fe.mod_time = *uint;
17906               break;
17907             case DW_LNCT_size:
17908               if (uint.has_value ())
17909                 fe.length = *uint;
17910               break;
17911             case DW_LNCT_MD5:
17912               break;
17913             default:
17914               complaint (&symfile_complaints,
17915                          _("Unknown format content type %s"),
17916                          pulongest (content_type));
17917             }
17918         }
17919
17920       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17921     }
17922
17923   *bufp = buf;
17924 }
17925
17926 /* Read the statement program header starting at OFFSET in
17927    .debug_line, or .debug_line.dwo.  Return a pointer
17928    to a struct line_header, allocated using xmalloc.
17929    Returns NULL if there is a problem reading the header, e.g., if it
17930    has a version we don't understand.
17931
17932    NOTE: the strings in the include directory and file name tables of
17933    the returned object point into the dwarf line section buffer,
17934    and must not be freed.  */
17935
17936 static line_header_up
17937 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17938 {
17939   const gdb_byte *line_ptr;
17940   unsigned int bytes_read, offset_size;
17941   int i;
17942   const char *cur_dir, *cur_file;
17943   struct dwarf2_section_info *section;
17944   bfd *abfd;
17945
17946   section = get_debug_line_section (cu);
17947   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17948   if (section->buffer == NULL)
17949     {
17950       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17951         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17952       else
17953         complaint (&symfile_complaints, _("missing .debug_line section"));
17954       return 0;
17955     }
17956
17957   /* We can't do this until we know the section is non-empty.
17958      Only then do we know we have such a section.  */
17959   abfd = get_section_bfd_owner (section);
17960
17961   /* Make sure that at least there's room for the total_length field.
17962      That could be 12 bytes long, but we're just going to fudge that.  */
17963   if (to_underlying (sect_off) + 4 >= section->size)
17964     {
17965       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17966       return 0;
17967     }
17968
17969   line_header_up lh (new line_header ());
17970
17971   lh->sect_off = sect_off;
17972   lh->offset_in_dwz = cu->per_cu->is_dwz;
17973
17974   line_ptr = section->buffer + to_underlying (sect_off);
17975
17976   /* Read in the header.  */
17977   lh->total_length =
17978     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17979                                             &bytes_read, &offset_size);
17980   line_ptr += bytes_read;
17981   if (line_ptr + lh->total_length > (section->buffer + section->size))
17982     {
17983       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17984       return 0;
17985     }
17986   lh->statement_program_end = line_ptr + lh->total_length;
17987   lh->version = read_2_bytes (abfd, line_ptr);
17988   line_ptr += 2;
17989   if (lh->version > 5)
17990     {
17991       /* This is a version we don't understand.  The format could have
17992          changed in ways we don't handle properly so just punt.  */
17993       complaint (&symfile_complaints,
17994                  _("unsupported version in .debug_line section"));
17995       return NULL;
17996     }
17997   if (lh->version >= 5)
17998     {
17999       gdb_byte segment_selector_size;
18000
18001       /* Skip address size.  */
18002       read_1_byte (abfd, line_ptr);
18003       line_ptr += 1;
18004
18005       segment_selector_size = read_1_byte (abfd, line_ptr);
18006       line_ptr += 1;
18007       if (segment_selector_size != 0)
18008         {
18009           complaint (&symfile_complaints,
18010                      _("unsupported segment selector size %u "
18011                        "in .debug_line section"),
18012                      segment_selector_size);
18013           return NULL;
18014         }
18015     }
18016   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18017   line_ptr += offset_size;
18018   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18019   line_ptr += 1;
18020   if (lh->version >= 4)
18021     {
18022       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18023       line_ptr += 1;
18024     }
18025   else
18026     lh->maximum_ops_per_instruction = 1;
18027
18028   if (lh->maximum_ops_per_instruction == 0)
18029     {
18030       lh->maximum_ops_per_instruction = 1;
18031       complaint (&symfile_complaints,
18032                  _("invalid maximum_ops_per_instruction "
18033                    "in `.debug_line' section"));
18034     }
18035
18036   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18037   line_ptr += 1;
18038   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18039   line_ptr += 1;
18040   lh->line_range = read_1_byte (abfd, line_ptr);
18041   line_ptr += 1;
18042   lh->opcode_base = read_1_byte (abfd, line_ptr);
18043   line_ptr += 1;
18044   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18045
18046   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18047   for (i = 1; i < lh->opcode_base; ++i)
18048     {
18049       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18050       line_ptr += 1;
18051     }
18052
18053   if (lh->version >= 5)
18054     {
18055       /* Read directory table.  */
18056       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18057                               [] (struct line_header *lh, const char *name,
18058                                   dir_index d_index, unsigned int mod_time,
18059                                   unsigned int length)
18060         {
18061           lh->add_include_dir (name);
18062         });
18063
18064       /* Read file name table.  */
18065       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18066                               [] (struct line_header *lh, const char *name,
18067                                   dir_index d_index, unsigned int mod_time,
18068                                   unsigned int length)
18069         {
18070           lh->add_file_name (name, d_index, mod_time, length);
18071         });
18072     }
18073   else
18074     {
18075       /* Read directory table.  */
18076       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18077         {
18078           line_ptr += bytes_read;
18079           lh->add_include_dir (cur_dir);
18080         }
18081       line_ptr += bytes_read;
18082
18083       /* Read file name table.  */
18084       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18085         {
18086           unsigned int mod_time, length;
18087           dir_index d_index;
18088
18089           line_ptr += bytes_read;
18090           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18091           line_ptr += bytes_read;
18092           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18093           line_ptr += bytes_read;
18094           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18095           line_ptr += bytes_read;
18096
18097           lh->add_file_name (cur_file, d_index, mod_time, length);
18098         }
18099       line_ptr += bytes_read;
18100     }
18101   lh->statement_program_start = line_ptr;
18102
18103   if (line_ptr > (section->buffer + section->size))
18104     complaint (&symfile_complaints,
18105                _("line number info header doesn't "
18106                  "fit in `.debug_line' section"));
18107
18108   return lh;
18109 }
18110
18111 /* Subroutine of dwarf_decode_lines to simplify it.
18112    Return the file name of the psymtab for included file FILE_INDEX
18113    in line header LH of PST.
18114    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18115    If space for the result is malloc'd, it will be freed by a cleanup.
18116    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18117
18118    The function creates dangling cleanup registration.  */
18119
18120 static const char *
18121 psymtab_include_file_name (const struct line_header *lh, int file_index,
18122                            const struct partial_symtab *pst,
18123                            const char *comp_dir)
18124 {
18125   const file_entry &fe = lh->file_names[file_index];
18126   const char *include_name = fe.name;
18127   const char *include_name_to_compare = include_name;
18128   const char *pst_filename;
18129   char *copied_name = NULL;
18130   int file_is_pst;
18131
18132   const char *dir_name = fe.include_dir (lh);
18133
18134   if (!IS_ABSOLUTE_PATH (include_name)
18135       && (dir_name != NULL || comp_dir != NULL))
18136     {
18137       /* Avoid creating a duplicate psymtab for PST.
18138          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18139          Before we do the comparison, however, we need to account
18140          for DIR_NAME and COMP_DIR.
18141          First prepend dir_name (if non-NULL).  If we still don't
18142          have an absolute path prepend comp_dir (if non-NULL).
18143          However, the directory we record in the include-file's
18144          psymtab does not contain COMP_DIR (to match the
18145          corresponding symtab(s)).
18146
18147          Example:
18148
18149          bash$ cd /tmp
18150          bash$ gcc -g ./hello.c
18151          include_name = "hello.c"
18152          dir_name = "."
18153          DW_AT_comp_dir = comp_dir = "/tmp"
18154          DW_AT_name = "./hello.c"
18155
18156       */
18157
18158       if (dir_name != NULL)
18159         {
18160           char *tem = concat (dir_name, SLASH_STRING,
18161                               include_name, (char *)NULL);
18162
18163           make_cleanup (xfree, tem);
18164           include_name = tem;
18165           include_name_to_compare = include_name;
18166         }
18167       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18168         {
18169           char *tem = concat (comp_dir, SLASH_STRING,
18170                               include_name, (char *)NULL);
18171
18172           make_cleanup (xfree, tem);
18173           include_name_to_compare = tem;
18174         }
18175     }
18176
18177   pst_filename = pst->filename;
18178   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18179     {
18180       copied_name = concat (pst->dirname, SLASH_STRING,
18181                             pst_filename, (char *)NULL);
18182       pst_filename = copied_name;
18183     }
18184
18185   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18186
18187   if (copied_name != NULL)
18188     xfree (copied_name);
18189
18190   if (file_is_pst)
18191     return NULL;
18192   return include_name;
18193 }
18194
18195 /* State machine to track the state of the line number program.  */
18196
18197 class lnp_state_machine
18198 {
18199 public:
18200   /* Initialize a machine state for the start of a line number
18201      program.  */
18202   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18203
18204   file_entry *current_file ()
18205   {
18206     /* lh->file_names is 0-based, but the file name numbers in the
18207        statement program are 1-based.  */
18208     return m_line_header->file_name_at (m_file);
18209   }
18210
18211   /* Record the line in the state machine.  END_SEQUENCE is true if
18212      we're processing the end of a sequence.  */
18213   void record_line (bool end_sequence);
18214
18215   /* Check address and if invalid nop-out the rest of the lines in this
18216      sequence.  */
18217   void check_line_address (struct dwarf2_cu *cu,
18218                            const gdb_byte *line_ptr,
18219                            CORE_ADDR lowpc, CORE_ADDR address);
18220
18221   void handle_set_discriminator (unsigned int discriminator)
18222   {
18223     m_discriminator = discriminator;
18224     m_line_has_non_zero_discriminator |= discriminator != 0;
18225   }
18226
18227   /* Handle DW_LNE_set_address.  */
18228   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18229   {
18230     m_op_index = 0;
18231     address += baseaddr;
18232     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18233   }
18234
18235   /* Handle DW_LNS_advance_pc.  */
18236   void handle_advance_pc (CORE_ADDR adjust);
18237
18238   /* Handle a special opcode.  */
18239   void handle_special_opcode (unsigned char op_code);
18240
18241   /* Handle DW_LNS_advance_line.  */
18242   void handle_advance_line (int line_delta)
18243   {
18244     advance_line (line_delta);
18245   }
18246
18247   /* Handle DW_LNS_set_file.  */
18248   void handle_set_file (file_name_index file);
18249
18250   /* Handle DW_LNS_negate_stmt.  */
18251   void handle_negate_stmt ()
18252   {
18253     m_is_stmt = !m_is_stmt;
18254   }
18255
18256   /* Handle DW_LNS_const_add_pc.  */
18257   void handle_const_add_pc ();
18258
18259   /* Handle DW_LNS_fixed_advance_pc.  */
18260   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18261   {
18262     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18263     m_op_index = 0;
18264   }
18265
18266   /* Handle DW_LNS_copy.  */
18267   void handle_copy ()
18268   {
18269     record_line (false);
18270     m_discriminator = 0;
18271   }
18272
18273   /* Handle DW_LNE_end_sequence.  */
18274   void handle_end_sequence ()
18275   {
18276     m_record_line_callback = ::record_line;
18277   }
18278
18279 private:
18280   /* Advance the line by LINE_DELTA.  */
18281   void advance_line (int line_delta)
18282   {
18283     m_line += line_delta;
18284
18285     if (line_delta != 0)
18286       m_line_has_non_zero_discriminator = m_discriminator != 0;
18287   }
18288
18289   gdbarch *m_gdbarch;
18290
18291   /* True if we're recording lines.
18292      Otherwise we're building partial symtabs and are just interested in
18293      finding include files mentioned by the line number program.  */
18294   bool m_record_lines_p;
18295
18296   /* The line number header.  */
18297   line_header *m_line_header;
18298
18299   /* These are part of the standard DWARF line number state machine,
18300      and initialized according to the DWARF spec.  */
18301
18302   unsigned char m_op_index = 0;
18303   /* The line table index (1-based) of the current file.  */
18304   file_name_index m_file = (file_name_index) 1;
18305   unsigned int m_line = 1;
18306
18307   /* These are initialized in the constructor.  */
18308
18309   CORE_ADDR m_address;
18310   bool m_is_stmt;
18311   unsigned int m_discriminator;
18312
18313   /* Additional bits of state we need to track.  */
18314
18315   /* The last file that we called dwarf2_start_subfile for.
18316      This is only used for TLLs.  */
18317   unsigned int m_last_file = 0;
18318   /* The last file a line number was recorded for.  */
18319   struct subfile *m_last_subfile = NULL;
18320
18321   /* The function to call to record a line.  */
18322   record_line_ftype *m_record_line_callback = NULL;
18323
18324   /* The last line number that was recorded, used to coalesce
18325      consecutive entries for the same line.  This can happen, for
18326      example, when discriminators are present.  PR 17276.  */
18327   unsigned int m_last_line = 0;
18328   bool m_line_has_non_zero_discriminator = false;
18329 };
18330
18331 void
18332 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18333 {
18334   CORE_ADDR addr_adj = (((m_op_index + adjust)
18335                          / m_line_header->maximum_ops_per_instruction)
18336                         * m_line_header->minimum_instruction_length);
18337   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18338   m_op_index = ((m_op_index + adjust)
18339                 % m_line_header->maximum_ops_per_instruction);
18340 }
18341
18342 void
18343 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18344 {
18345   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18346   CORE_ADDR addr_adj = (((m_op_index
18347                           + (adj_opcode / m_line_header->line_range))
18348                          / m_line_header->maximum_ops_per_instruction)
18349                         * m_line_header->minimum_instruction_length);
18350   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18351   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18352                 % m_line_header->maximum_ops_per_instruction);
18353
18354   int line_delta = (m_line_header->line_base
18355                     + (adj_opcode % m_line_header->line_range));
18356   advance_line (line_delta);
18357   record_line (false);
18358   m_discriminator = 0;
18359 }
18360
18361 void
18362 lnp_state_machine::handle_set_file (file_name_index file)
18363 {
18364   m_file = file;
18365
18366   const file_entry *fe = current_file ();
18367   if (fe == NULL)
18368     dwarf2_debug_line_missing_file_complaint ();
18369   else if (m_record_lines_p)
18370     {
18371       const char *dir = fe->include_dir (m_line_header);
18372
18373       m_last_subfile = current_subfile;
18374       m_line_has_non_zero_discriminator = m_discriminator != 0;
18375       dwarf2_start_subfile (fe->name, dir);
18376     }
18377 }
18378
18379 void
18380 lnp_state_machine::handle_const_add_pc ()
18381 {
18382   CORE_ADDR adjust
18383     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18384
18385   CORE_ADDR addr_adj
18386     = (((m_op_index + adjust)
18387         / m_line_header->maximum_ops_per_instruction)
18388        * m_line_header->minimum_instruction_length);
18389
18390   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18391   m_op_index = ((m_op_index + adjust)
18392                 % m_line_header->maximum_ops_per_instruction);
18393 }
18394
18395 /* Ignore this record_line request.  */
18396
18397 static void
18398 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18399 {
18400   return;
18401 }
18402
18403 /* Return non-zero if we should add LINE to the line number table.
18404    LINE is the line to add, LAST_LINE is the last line that was added,
18405    LAST_SUBFILE is the subfile for LAST_LINE.
18406    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18407    had a non-zero discriminator.
18408
18409    We have to be careful in the presence of discriminators.
18410    E.g., for this line:
18411
18412      for (i = 0; i < 100000; i++);
18413
18414    clang can emit four line number entries for that one line,
18415    each with a different discriminator.
18416    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18417
18418    However, we want gdb to coalesce all four entries into one.
18419    Otherwise the user could stepi into the middle of the line and
18420    gdb would get confused about whether the pc really was in the
18421    middle of the line.
18422
18423    Things are further complicated by the fact that two consecutive
18424    line number entries for the same line is a heuristic used by gcc
18425    to denote the end of the prologue.  So we can't just discard duplicate
18426    entries, we have to be selective about it.  The heuristic we use is
18427    that we only collapse consecutive entries for the same line if at least
18428    one of those entries has a non-zero discriminator.  PR 17276.
18429
18430    Note: Addresses in the line number state machine can never go backwards
18431    within one sequence, thus this coalescing is ok.  */
18432
18433 static int
18434 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18435                      int line_has_non_zero_discriminator,
18436                      struct subfile *last_subfile)
18437 {
18438   if (current_subfile != last_subfile)
18439     return 1;
18440   if (line != last_line)
18441     return 1;
18442   /* Same line for the same file that we've seen already.
18443      As a last check, for pr 17276, only record the line if the line
18444      has never had a non-zero discriminator.  */
18445   if (!line_has_non_zero_discriminator)
18446     return 1;
18447   return 0;
18448 }
18449
18450 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18451    in the line table of subfile SUBFILE.  */
18452
18453 static void
18454 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18455                      unsigned int line, CORE_ADDR address,
18456                      record_line_ftype p_record_line)
18457 {
18458   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18459
18460   if (dwarf_line_debug)
18461     {
18462       fprintf_unfiltered (gdb_stdlog,
18463                           "Recording line %u, file %s, address %s\n",
18464                           line, lbasename (subfile->name),
18465                           paddress (gdbarch, address));
18466     }
18467
18468   (*p_record_line) (subfile, line, addr);
18469 }
18470
18471 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18472    Mark the end of a set of line number records.
18473    The arguments are the same as for dwarf_record_line_1.
18474    If SUBFILE is NULL the request is ignored.  */
18475
18476 static void
18477 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18478                    CORE_ADDR address, record_line_ftype p_record_line)
18479 {
18480   if (subfile == NULL)
18481     return;
18482
18483   if (dwarf_line_debug)
18484     {
18485       fprintf_unfiltered (gdb_stdlog,
18486                           "Finishing current line, file %s, address %s\n",
18487                           lbasename (subfile->name),
18488                           paddress (gdbarch, address));
18489     }
18490
18491   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18492 }
18493
18494 void
18495 lnp_state_machine::record_line (bool end_sequence)
18496 {
18497   if (dwarf_line_debug)
18498     {
18499       fprintf_unfiltered (gdb_stdlog,
18500                           "Processing actual line %u: file %u,"
18501                           " address %s, is_stmt %u, discrim %u\n",
18502                           m_line, to_underlying (m_file),
18503                           paddress (m_gdbarch, m_address),
18504                           m_is_stmt, m_discriminator);
18505     }
18506
18507   file_entry *fe = current_file ();
18508
18509   if (fe == NULL)
18510     dwarf2_debug_line_missing_file_complaint ();
18511   /* For now we ignore lines not starting on an instruction boundary.
18512      But not when processing end_sequence for compatibility with the
18513      previous version of the code.  */
18514   else if (m_op_index == 0 || end_sequence)
18515     {
18516       fe->included_p = 1;
18517       if (m_record_lines_p && m_is_stmt)
18518         {
18519           if (m_last_subfile != current_subfile || end_sequence)
18520             {
18521               dwarf_finish_line (m_gdbarch, m_last_subfile,
18522                                  m_address, m_record_line_callback);
18523             }
18524
18525           if (!end_sequence)
18526             {
18527               if (dwarf_record_line_p (m_line, m_last_line,
18528                                        m_line_has_non_zero_discriminator,
18529                                        m_last_subfile))
18530                 {
18531                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18532                                        m_line, m_address,
18533                                        m_record_line_callback);
18534                 }
18535               m_last_subfile = current_subfile;
18536               m_last_line = m_line;
18537             }
18538         }
18539     }
18540 }
18541
18542 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18543                                       bool record_lines_p)
18544 {
18545   m_gdbarch = arch;
18546   m_record_lines_p = record_lines_p;
18547   m_line_header = lh;
18548
18549   m_record_line_callback = ::record_line;
18550
18551   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18552      was a line entry for it so that the backend has a chance to adjust it
18553      and also record it in case it needs it.  This is currently used by MIPS
18554      code, cf. `mips_adjust_dwarf2_line'.  */
18555   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18556   m_is_stmt = lh->default_is_stmt;
18557   m_discriminator = 0;
18558 }
18559
18560 void
18561 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18562                                        const gdb_byte *line_ptr,
18563                                        CORE_ADDR lowpc, CORE_ADDR address)
18564 {
18565   /* If address < lowpc then it's not a usable value, it's outside the
18566      pc range of the CU.  However, we restrict the test to only address
18567      values of zero to preserve GDB's previous behaviour which is to
18568      handle the specific case of a function being GC'd by the linker.  */
18569
18570   if (address == 0 && address < lowpc)
18571     {
18572       /* This line table is for a function which has been
18573          GCd by the linker.  Ignore it.  PR gdb/12528 */
18574
18575       struct objfile *objfile = cu->objfile;
18576       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18577
18578       complaint (&symfile_complaints,
18579                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18580                  line_offset, objfile_name (objfile));
18581       m_record_line_callback = noop_record_line;
18582       /* Note: record_line_callback is left as noop_record_line until
18583          we see DW_LNE_end_sequence.  */
18584     }
18585 }
18586
18587 /* Subroutine of dwarf_decode_lines to simplify it.
18588    Process the line number information in LH.
18589    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18590    program in order to set included_p for every referenced header.  */
18591
18592 static void
18593 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18594                       const int decode_for_pst_p, CORE_ADDR lowpc)
18595 {
18596   const gdb_byte *line_ptr, *extended_end;
18597   const gdb_byte *line_end;
18598   unsigned int bytes_read, extended_len;
18599   unsigned char op_code, extended_op;
18600   CORE_ADDR baseaddr;
18601   struct objfile *objfile = cu->objfile;
18602   bfd *abfd = objfile->obfd;
18603   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18604   /* True if we're recording line info (as opposed to building partial
18605      symtabs and just interested in finding include files mentioned by
18606      the line number program).  */
18607   bool record_lines_p = !decode_for_pst_p;
18608
18609   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18610
18611   line_ptr = lh->statement_program_start;
18612   line_end = lh->statement_program_end;
18613
18614   /* Read the statement sequences until there's nothing left.  */
18615   while (line_ptr < line_end)
18616     {
18617       /* The DWARF line number program state machine.  Reset the state
18618          machine at the start of each sequence.  */
18619       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18620       bool end_sequence = false;
18621
18622       if (record_lines_p)
18623         {
18624           /* Start a subfile for the current file of the state
18625              machine.  */
18626           const file_entry *fe = state_machine.current_file ();
18627
18628           if (fe != NULL)
18629             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18630         }
18631
18632       /* Decode the table.  */
18633       while (line_ptr < line_end && !end_sequence)
18634         {
18635           op_code = read_1_byte (abfd, line_ptr);
18636           line_ptr += 1;
18637
18638           if (op_code >= lh->opcode_base)
18639             {
18640               /* Special opcode.  */
18641               state_machine.handle_special_opcode (op_code);
18642             }
18643           else switch (op_code)
18644             {
18645             case DW_LNS_extended_op:
18646               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18647                                                    &bytes_read);
18648               line_ptr += bytes_read;
18649               extended_end = line_ptr + extended_len;
18650               extended_op = read_1_byte (abfd, line_ptr);
18651               line_ptr += 1;
18652               switch (extended_op)
18653                 {
18654                 case DW_LNE_end_sequence:
18655                   state_machine.handle_end_sequence ();
18656                   end_sequence = true;
18657                   break;
18658                 case DW_LNE_set_address:
18659                   {
18660                     CORE_ADDR address
18661                       = read_address (abfd, line_ptr, cu, &bytes_read);
18662                     line_ptr += bytes_read;
18663
18664                     state_machine.check_line_address (cu, line_ptr,
18665                                                       lowpc, address);
18666                     state_machine.handle_set_address (baseaddr, address);
18667                   }
18668                   break;
18669                 case DW_LNE_define_file:
18670                   {
18671                     const char *cur_file;
18672                     unsigned int mod_time, length;
18673                     dir_index dindex;
18674
18675                     cur_file = read_direct_string (abfd, line_ptr,
18676                                                    &bytes_read);
18677                     line_ptr += bytes_read;
18678                     dindex = (dir_index)
18679                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18680                     line_ptr += bytes_read;
18681                     mod_time =
18682                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18683                     line_ptr += bytes_read;
18684                     length =
18685                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18686                     line_ptr += bytes_read;
18687                     lh->add_file_name (cur_file, dindex, mod_time, length);
18688                   }
18689                   break;
18690                 case DW_LNE_set_discriminator:
18691                   {
18692                     /* The discriminator is not interesting to the
18693                        debugger; just ignore it.  We still need to
18694                        check its value though:
18695                        if there are consecutive entries for the same
18696                        (non-prologue) line we want to coalesce them.
18697                        PR 17276.  */
18698                     unsigned int discr
18699                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18700                     line_ptr += bytes_read;
18701
18702                     state_machine.handle_set_discriminator (discr);
18703                   }
18704                   break;
18705                 default:
18706                   complaint (&symfile_complaints,
18707                              _("mangled .debug_line section"));
18708                   return;
18709                 }
18710               /* Make sure that we parsed the extended op correctly.  If e.g.
18711                  we expected a different address size than the producer used,
18712                  we may have read the wrong number of bytes.  */
18713               if (line_ptr != extended_end)
18714                 {
18715                   complaint (&symfile_complaints,
18716                              _("mangled .debug_line section"));
18717                   return;
18718                 }
18719               break;
18720             case DW_LNS_copy:
18721               state_machine.handle_copy ();
18722               break;
18723             case DW_LNS_advance_pc:
18724               {
18725                 CORE_ADDR adjust
18726                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18727                 line_ptr += bytes_read;
18728
18729                 state_machine.handle_advance_pc (adjust);
18730               }
18731               break;
18732             case DW_LNS_advance_line:
18733               {
18734                 int line_delta
18735                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18736                 line_ptr += bytes_read;
18737
18738                 state_machine.handle_advance_line (line_delta);
18739               }
18740               break;
18741             case DW_LNS_set_file:
18742               {
18743                 file_name_index file
18744                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18745                                                             &bytes_read);
18746                 line_ptr += bytes_read;
18747
18748                 state_machine.handle_set_file (file);
18749               }
18750               break;
18751             case DW_LNS_set_column:
18752               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18753               line_ptr += bytes_read;
18754               break;
18755             case DW_LNS_negate_stmt:
18756               state_machine.handle_negate_stmt ();
18757               break;
18758             case DW_LNS_set_basic_block:
18759               break;
18760             /* Add to the address register of the state machine the
18761                address increment value corresponding to special opcode
18762                255.  I.e., this value is scaled by the minimum
18763                instruction length since special opcode 255 would have
18764                scaled the increment.  */
18765             case DW_LNS_const_add_pc:
18766               state_machine.handle_const_add_pc ();
18767               break;
18768             case DW_LNS_fixed_advance_pc:
18769               {
18770                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18771                 line_ptr += 2;
18772
18773                 state_machine.handle_fixed_advance_pc (addr_adj);
18774               }
18775               break;
18776             default:
18777               {
18778                 /* Unknown standard opcode, ignore it.  */
18779                 int i;
18780
18781                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18782                   {
18783                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18784                     line_ptr += bytes_read;
18785                   }
18786               }
18787             }
18788         }
18789
18790       if (!end_sequence)
18791         dwarf2_debug_line_missing_end_sequence_complaint ();
18792
18793       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18794          in which case we still finish recording the last line).  */
18795       state_machine.record_line (true);
18796     }
18797 }
18798
18799 /* Decode the Line Number Program (LNP) for the given line_header
18800    structure and CU.  The actual information extracted and the type
18801    of structures created from the LNP depends on the value of PST.
18802
18803    1. If PST is NULL, then this procedure uses the data from the program
18804       to create all necessary symbol tables, and their linetables.
18805
18806    2. If PST is not NULL, this procedure reads the program to determine
18807       the list of files included by the unit represented by PST, and
18808       builds all the associated partial symbol tables.
18809
18810    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18811    It is used for relative paths in the line table.
18812    NOTE: When processing partial symtabs (pst != NULL),
18813    comp_dir == pst->dirname.
18814
18815    NOTE: It is important that psymtabs have the same file name (via strcmp)
18816    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18817    symtab we don't use it in the name of the psymtabs we create.
18818    E.g. expand_line_sal requires this when finding psymtabs to expand.
18819    A good testcase for this is mb-inline.exp.
18820
18821    LOWPC is the lowest address in CU (or 0 if not known).
18822
18823    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18824    for its PC<->lines mapping information.  Otherwise only the filename
18825    table is read in.  */
18826
18827 static void
18828 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18829                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18830                     CORE_ADDR lowpc, int decode_mapping)
18831 {
18832   struct objfile *objfile = cu->objfile;
18833   const int decode_for_pst_p = (pst != NULL);
18834
18835   if (decode_mapping)
18836     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18837
18838   if (decode_for_pst_p)
18839     {
18840       int file_index;
18841
18842       /* Now that we're done scanning the Line Header Program, we can
18843          create the psymtab of each included file.  */
18844       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18845         if (lh->file_names[file_index].included_p == 1)
18846           {
18847             const char *include_name =
18848               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18849             if (include_name != NULL)
18850               dwarf2_create_include_psymtab (include_name, pst, objfile);
18851           }
18852     }
18853   else
18854     {
18855       /* Make sure a symtab is created for every file, even files
18856          which contain only variables (i.e. no code with associated
18857          line numbers).  */
18858       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18859       int i;
18860
18861       for (i = 0; i < lh->file_names.size (); i++)
18862         {
18863           file_entry &fe = lh->file_names[i];
18864
18865           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18866
18867           if (current_subfile->symtab == NULL)
18868             {
18869               current_subfile->symtab
18870                 = allocate_symtab (cust, current_subfile->name);
18871             }
18872           fe.symtab = current_subfile->symtab;
18873         }
18874     }
18875 }
18876
18877 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18878    DIRNAME the name of the source directory which contains FILENAME
18879    or NULL if not known.
18880    This routine tries to keep line numbers from identical absolute and
18881    relative file names in a common subfile.
18882
18883    Using the `list' example from the GDB testsuite, which resides in
18884    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18885    of /srcdir/list0.c yields the following debugging information for list0.c:
18886
18887    DW_AT_name:          /srcdir/list0.c
18888    DW_AT_comp_dir:      /compdir
18889    files.files[0].name: list0.h
18890    files.files[0].dir:  /srcdir
18891    files.files[1].name: list0.c
18892    files.files[1].dir:  /srcdir
18893
18894    The line number information for list0.c has to end up in a single
18895    subfile, so that `break /srcdir/list0.c:1' works as expected.
18896    start_subfile will ensure that this happens provided that we pass the
18897    concatenation of files.files[1].dir and files.files[1].name as the
18898    subfile's name.  */
18899
18900 static void
18901 dwarf2_start_subfile (const char *filename, const char *dirname)
18902 {
18903   char *copy = NULL;
18904
18905   /* In order not to lose the line information directory,
18906      we concatenate it to the filename when it makes sense.
18907      Note that the Dwarf3 standard says (speaking of filenames in line
18908      information): ``The directory index is ignored for file names
18909      that represent full path names''.  Thus ignoring dirname in the
18910      `else' branch below isn't an issue.  */
18911
18912   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18913     {
18914       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18915       filename = copy;
18916     }
18917
18918   start_subfile (filename);
18919
18920   if (copy != NULL)
18921     xfree (copy);
18922 }
18923
18924 /* Start a symtab for DWARF.
18925    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18926
18927 static struct compunit_symtab *
18928 dwarf2_start_symtab (struct dwarf2_cu *cu,
18929                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18930 {
18931   struct compunit_symtab *cust
18932     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18933
18934   record_debugformat ("DWARF 2");
18935   record_producer (cu->producer);
18936
18937   /* We assume that we're processing GCC output.  */
18938   processing_gcc_compilation = 2;
18939
18940   cu->processing_has_namespace_info = 0;
18941
18942   return cust;
18943 }
18944
18945 static void
18946 var_decode_location (struct attribute *attr, struct symbol *sym,
18947                      struct dwarf2_cu *cu)
18948 {
18949   struct objfile *objfile = cu->objfile;
18950   struct comp_unit_head *cu_header = &cu->header;
18951
18952   /* NOTE drow/2003-01-30: There used to be a comment and some special
18953      code here to turn a symbol with DW_AT_external and a
18954      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18955      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18956      with some versions of binutils) where shared libraries could have
18957      relocations against symbols in their debug information - the
18958      minimal symbol would have the right address, but the debug info
18959      would not.  It's no longer necessary, because we will explicitly
18960      apply relocations when we read in the debug information now.  */
18961
18962   /* A DW_AT_location attribute with no contents indicates that a
18963      variable has been optimized away.  */
18964   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18965     {
18966       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18967       return;
18968     }
18969
18970   /* Handle one degenerate form of location expression specially, to
18971      preserve GDB's previous behavior when section offsets are
18972      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18973      then mark this symbol as LOC_STATIC.  */
18974
18975   if (attr_form_is_block (attr)
18976       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18977            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18978           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18979               && (DW_BLOCK (attr)->size
18980                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18981     {
18982       unsigned int dummy;
18983
18984       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18985         SYMBOL_VALUE_ADDRESS (sym) =
18986           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18987       else
18988         SYMBOL_VALUE_ADDRESS (sym) =
18989           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18990       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18991       fixup_symbol_section (sym, objfile);
18992       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18993                                               SYMBOL_SECTION (sym));
18994       return;
18995     }
18996
18997   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18998      expression evaluator, and use LOC_COMPUTED only when necessary
18999      (i.e. when the value of a register or memory location is
19000      referenced, or a thread-local block, etc.).  Then again, it might
19001      not be worthwhile.  I'm assuming that it isn't unless performance
19002      or memory numbers show me otherwise.  */
19003
19004   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19005
19006   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19007     cu->has_loclist = 1;
19008 }
19009
19010 /* Given a pointer to a DWARF information entry, figure out if we need
19011    to make a symbol table entry for it, and if so, create a new entry
19012    and return a pointer to it.
19013    If TYPE is NULL, determine symbol type from the die, otherwise
19014    used the passed type.
19015    If SPACE is not NULL, use it to hold the new symbol.  If it is
19016    NULL, allocate a new symbol on the objfile's obstack.  */
19017
19018 static struct symbol *
19019 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19020                  struct symbol *space)
19021 {
19022   struct objfile *objfile = cu->objfile;
19023   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19024   struct symbol *sym = NULL;
19025   const char *name;
19026   struct attribute *attr = NULL;
19027   struct attribute *attr2 = NULL;
19028   CORE_ADDR baseaddr;
19029   struct pending **list_to_add = NULL;
19030
19031   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19032
19033   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19034
19035   name = dwarf2_name (die, cu);
19036   if (name)
19037     {
19038       const char *linkagename;
19039       int suppress_add = 0;
19040
19041       if (space)
19042         sym = space;
19043       else
19044         sym = allocate_symbol (objfile);
19045       OBJSTAT (objfile, n_syms++);
19046
19047       /* Cache this symbol's name and the name's demangled form (if any).  */
19048       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19049       linkagename = dwarf2_physname (name, die, cu);
19050       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19051
19052       /* Fortran does not have mangling standard and the mangling does differ
19053          between gfortran, iFort etc.  */
19054       if (cu->language == language_fortran
19055           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19056         symbol_set_demangled_name (&(sym->ginfo),
19057                                    dwarf2_full_name (name, die, cu),
19058                                    NULL);
19059
19060       /* Default assumptions.
19061          Use the passed type or decode it from the die.  */
19062       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19063       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19064       if (type != NULL)
19065         SYMBOL_TYPE (sym) = type;
19066       else
19067         SYMBOL_TYPE (sym) = die_type (die, cu);
19068       attr = dwarf2_attr (die,
19069                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19070                           cu);
19071       if (attr)
19072         {
19073           SYMBOL_LINE (sym) = DW_UNSND (attr);
19074         }
19075
19076       attr = dwarf2_attr (die,
19077                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19078                           cu);
19079       if (attr)
19080         {
19081           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19082           struct file_entry *fe;
19083
19084           if (cu->line_header != NULL)
19085             fe = cu->line_header->file_name_at (file_index);
19086           else
19087             fe = NULL;
19088
19089           if (fe == NULL)
19090             complaint (&symfile_complaints,
19091                        _("file index out of range"));
19092           else
19093             symbol_set_symtab (sym, fe->symtab);
19094         }
19095
19096       switch (die->tag)
19097         {
19098         case DW_TAG_label:
19099           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19100           if (attr)
19101             {
19102               CORE_ADDR addr;
19103
19104               addr = attr_value_as_address (attr);
19105               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19106               SYMBOL_VALUE_ADDRESS (sym) = addr;
19107             }
19108           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19109           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19110           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19111           add_symbol_to_list (sym, cu->list_in_scope);
19112           break;
19113         case DW_TAG_subprogram:
19114           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19115              finish_block.  */
19116           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19117           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19118           if ((attr2 && (DW_UNSND (attr2) != 0))
19119               || cu->language == language_ada)
19120             {
19121               /* Subprograms marked external are stored as a global symbol.
19122                  Ada subprograms, whether marked external or not, are always
19123                  stored as a global symbol, because we want to be able to
19124                  access them globally.  For instance, we want to be able
19125                  to break on a nested subprogram without having to
19126                  specify the context.  */
19127               list_to_add = &global_symbols;
19128             }
19129           else
19130             {
19131               list_to_add = cu->list_in_scope;
19132             }
19133           break;
19134         case DW_TAG_inlined_subroutine:
19135           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19136              finish_block.  */
19137           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19138           SYMBOL_INLINED (sym) = 1;
19139           list_to_add = cu->list_in_scope;
19140           break;
19141         case DW_TAG_template_value_param:
19142           suppress_add = 1;
19143           /* Fall through.  */
19144         case DW_TAG_constant:
19145         case DW_TAG_variable:
19146         case DW_TAG_member:
19147           /* Compilation with minimal debug info may result in
19148              variables with missing type entries.  Change the
19149              misleading `void' type to something sensible.  */
19150           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19151             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19152
19153           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19154           /* In the case of DW_TAG_member, we should only be called for
19155              static const members.  */
19156           if (die->tag == DW_TAG_member)
19157             {
19158               /* dwarf2_add_field uses die_is_declaration,
19159                  so we do the same.  */
19160               gdb_assert (die_is_declaration (die, cu));
19161               gdb_assert (attr);
19162             }
19163           if (attr)
19164             {
19165               dwarf2_const_value (attr, sym, cu);
19166               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19167               if (!suppress_add)
19168                 {
19169                   if (attr2 && (DW_UNSND (attr2) != 0))
19170                     list_to_add = &global_symbols;
19171                   else
19172                     list_to_add = cu->list_in_scope;
19173                 }
19174               break;
19175             }
19176           attr = dwarf2_attr (die, DW_AT_location, cu);
19177           if (attr)
19178             {
19179               var_decode_location (attr, sym, cu);
19180               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19181
19182               /* Fortran explicitly imports any global symbols to the local
19183                  scope by DW_TAG_common_block.  */
19184               if (cu->language == language_fortran && die->parent
19185                   && die->parent->tag == DW_TAG_common_block)
19186                 attr2 = NULL;
19187
19188               if (SYMBOL_CLASS (sym) == LOC_STATIC
19189                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19190                   && !dwarf2_per_objfile->has_section_at_zero)
19191                 {
19192                   /* When a static variable is eliminated by the linker,
19193                      the corresponding debug information is not stripped
19194                      out, but the variable address is set to null;
19195                      do not add such variables into symbol table.  */
19196                 }
19197               else if (attr2 && (DW_UNSND (attr2) != 0))
19198                 {
19199                   /* Workaround gfortran PR debug/40040 - it uses
19200                      DW_AT_location for variables in -fPIC libraries which may
19201                      get overriden by other libraries/executable and get
19202                      a different address.  Resolve it by the minimal symbol
19203                      which may come from inferior's executable using copy
19204                      relocation.  Make this workaround only for gfortran as for
19205                      other compilers GDB cannot guess the minimal symbol
19206                      Fortran mangling kind.  */
19207                   if (cu->language == language_fortran && die->parent
19208                       && die->parent->tag == DW_TAG_module
19209                       && cu->producer
19210                       && startswith (cu->producer, "GNU Fortran"))
19211                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19212
19213                   /* A variable with DW_AT_external is never static,
19214                      but it may be block-scoped.  */
19215                   list_to_add = (cu->list_in_scope == &file_symbols
19216                                  ? &global_symbols : cu->list_in_scope);
19217                 }
19218               else
19219                 list_to_add = cu->list_in_scope;
19220             }
19221           else
19222             {
19223               /* We do not know the address of this symbol.
19224                  If it is an external symbol and we have type information
19225                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19226                  The address of the variable will then be determined from
19227                  the minimal symbol table whenever the variable is
19228                  referenced.  */
19229               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19230
19231               /* Fortran explicitly imports any global symbols to the local
19232                  scope by DW_TAG_common_block.  */
19233               if (cu->language == language_fortran && die->parent
19234                   && die->parent->tag == DW_TAG_common_block)
19235                 {
19236                   /* SYMBOL_CLASS doesn't matter here because
19237                      read_common_block is going to reset it.  */
19238                   if (!suppress_add)
19239                     list_to_add = cu->list_in_scope;
19240                 }
19241               else if (attr2 && (DW_UNSND (attr2) != 0)
19242                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19243                 {
19244                   /* A variable with DW_AT_external is never static, but it
19245                      may be block-scoped.  */
19246                   list_to_add = (cu->list_in_scope == &file_symbols
19247                                  ? &global_symbols : cu->list_in_scope);
19248
19249                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19250                 }
19251               else if (!die_is_declaration (die, cu))
19252                 {
19253                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19254                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19255                   if (!suppress_add)
19256                     list_to_add = cu->list_in_scope;
19257                 }
19258             }
19259           break;
19260         case DW_TAG_formal_parameter:
19261           /* If we are inside a function, mark this as an argument.  If
19262              not, we might be looking at an argument to an inlined function
19263              when we do not have enough information to show inlined frames;
19264              pretend it's a local variable in that case so that the user can
19265              still see it.  */
19266           if (context_stack_depth > 0
19267               && context_stack[context_stack_depth - 1].name != NULL)
19268             SYMBOL_IS_ARGUMENT (sym) = 1;
19269           attr = dwarf2_attr (die, DW_AT_location, cu);
19270           if (attr)
19271             {
19272               var_decode_location (attr, sym, cu);
19273             }
19274           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19275           if (attr)
19276             {
19277               dwarf2_const_value (attr, sym, cu);
19278             }
19279
19280           list_to_add = cu->list_in_scope;
19281           break;
19282         case DW_TAG_unspecified_parameters:
19283           /* From varargs functions; gdb doesn't seem to have any
19284              interest in this information, so just ignore it for now.
19285              (FIXME?) */
19286           break;
19287         case DW_TAG_template_type_param:
19288           suppress_add = 1;
19289           /* Fall through.  */
19290         case DW_TAG_class_type:
19291         case DW_TAG_interface_type:
19292         case DW_TAG_structure_type:
19293         case DW_TAG_union_type:
19294         case DW_TAG_set_type:
19295         case DW_TAG_enumeration_type:
19296           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19297           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19298
19299           {
19300             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19301                really ever be static objects: otherwise, if you try
19302                to, say, break of a class's method and you're in a file
19303                which doesn't mention that class, it won't work unless
19304                the check for all static symbols in lookup_symbol_aux
19305                saves you.  See the OtherFileClass tests in
19306                gdb.c++/namespace.exp.  */
19307
19308             if (!suppress_add)
19309               {
19310                 list_to_add = (cu->list_in_scope == &file_symbols
19311                                && cu->language == language_cplus
19312                                ? &global_symbols : cu->list_in_scope);
19313
19314                 /* The semantics of C++ state that "struct foo {
19315                    ... }" also defines a typedef for "foo".  */
19316                 if (cu->language == language_cplus
19317                     || cu->language == language_ada
19318                     || cu->language == language_d
19319                     || cu->language == language_rust)
19320                   {
19321                     /* The symbol's name is already allocated along
19322                        with this objfile, so we don't need to
19323                        duplicate it for the type.  */
19324                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19325                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19326                   }
19327               }
19328           }
19329           break;
19330         case DW_TAG_typedef:
19331           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19332           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19333           list_to_add = cu->list_in_scope;
19334           break;
19335         case DW_TAG_base_type:
19336         case DW_TAG_subrange_type:
19337           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19338           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19339           list_to_add = cu->list_in_scope;
19340           break;
19341         case DW_TAG_enumerator:
19342           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19343           if (attr)
19344             {
19345               dwarf2_const_value (attr, sym, cu);
19346             }
19347           {
19348             /* NOTE: carlton/2003-11-10: See comment above in the
19349                DW_TAG_class_type, etc. block.  */
19350
19351             list_to_add = (cu->list_in_scope == &file_symbols
19352                            && cu->language == language_cplus
19353                            ? &global_symbols : cu->list_in_scope);
19354           }
19355           break;
19356         case DW_TAG_imported_declaration:
19357         case DW_TAG_namespace:
19358           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19359           list_to_add = &global_symbols;
19360           break;
19361         case DW_TAG_module:
19362           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19363           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19364           list_to_add = &global_symbols;
19365           break;
19366         case DW_TAG_common_block:
19367           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19368           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19369           add_symbol_to_list (sym, cu->list_in_scope);
19370           break;
19371         default:
19372           /* Not a tag we recognize.  Hopefully we aren't processing
19373              trash data, but since we must specifically ignore things
19374              we don't recognize, there is nothing else we should do at
19375              this point.  */
19376           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19377                      dwarf_tag_name (die->tag));
19378           break;
19379         }
19380
19381       if (suppress_add)
19382         {
19383           sym->hash_next = objfile->template_symbols;
19384           objfile->template_symbols = sym;
19385           list_to_add = NULL;
19386         }
19387
19388       if (list_to_add != NULL)
19389         add_symbol_to_list (sym, list_to_add);
19390
19391       /* For the benefit of old versions of GCC, check for anonymous
19392          namespaces based on the demangled name.  */
19393       if (!cu->processing_has_namespace_info
19394           && cu->language == language_cplus)
19395         cp_scan_for_anonymous_namespaces (sym, objfile);
19396     }
19397   return (sym);
19398 }
19399
19400 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19401
19402 static struct symbol *
19403 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19404 {
19405   return new_symbol_full (die, type, cu, NULL);
19406 }
19407
19408 /* Given an attr with a DW_FORM_dataN value in host byte order,
19409    zero-extend it as appropriate for the symbol's type.  The DWARF
19410    standard (v4) is not entirely clear about the meaning of using
19411    DW_FORM_dataN for a constant with a signed type, where the type is
19412    wider than the data.  The conclusion of a discussion on the DWARF
19413    list was that this is unspecified.  We choose to always zero-extend
19414    because that is the interpretation long in use by GCC.  */
19415
19416 static gdb_byte *
19417 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19418                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19419 {
19420   struct objfile *objfile = cu->objfile;
19421   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19422                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19423   LONGEST l = DW_UNSND (attr);
19424
19425   if (bits < sizeof (*value) * 8)
19426     {
19427       l &= ((LONGEST) 1 << bits) - 1;
19428       *value = l;
19429     }
19430   else if (bits == sizeof (*value) * 8)
19431     *value = l;
19432   else
19433     {
19434       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19435       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19436       return bytes;
19437     }
19438
19439   return NULL;
19440 }
19441
19442 /* Read a constant value from an attribute.  Either set *VALUE, or if
19443    the value does not fit in *VALUE, set *BYTES - either already
19444    allocated on the objfile obstack, or newly allocated on OBSTACK,
19445    or, set *BATON, if we translated the constant to a location
19446    expression.  */
19447
19448 static void
19449 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19450                          const char *name, struct obstack *obstack,
19451                          struct dwarf2_cu *cu,
19452                          LONGEST *value, const gdb_byte **bytes,
19453                          struct dwarf2_locexpr_baton **baton)
19454 {
19455   struct objfile *objfile = cu->objfile;
19456   struct comp_unit_head *cu_header = &cu->header;
19457   struct dwarf_block *blk;
19458   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19459                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19460
19461   *value = 0;
19462   *bytes = NULL;
19463   *baton = NULL;
19464
19465   switch (attr->form)
19466     {
19467     case DW_FORM_addr:
19468     case DW_FORM_GNU_addr_index:
19469       {
19470         gdb_byte *data;
19471
19472         if (TYPE_LENGTH (type) != cu_header->addr_size)
19473           dwarf2_const_value_length_mismatch_complaint (name,
19474                                                         cu_header->addr_size,
19475                                                         TYPE_LENGTH (type));
19476         /* Symbols of this form are reasonably rare, so we just
19477            piggyback on the existing location code rather than writing
19478            a new implementation of symbol_computed_ops.  */
19479         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19480         (*baton)->per_cu = cu->per_cu;
19481         gdb_assert ((*baton)->per_cu);
19482
19483         (*baton)->size = 2 + cu_header->addr_size;
19484         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19485         (*baton)->data = data;
19486
19487         data[0] = DW_OP_addr;
19488         store_unsigned_integer (&data[1], cu_header->addr_size,
19489                                 byte_order, DW_ADDR (attr));
19490         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19491       }
19492       break;
19493     case DW_FORM_string:
19494     case DW_FORM_strp:
19495     case DW_FORM_GNU_str_index:
19496     case DW_FORM_GNU_strp_alt:
19497       /* DW_STRING is already allocated on the objfile obstack, point
19498          directly to it.  */
19499       *bytes = (const gdb_byte *) DW_STRING (attr);
19500       break;
19501     case DW_FORM_block1:
19502     case DW_FORM_block2:
19503     case DW_FORM_block4:
19504     case DW_FORM_block:
19505     case DW_FORM_exprloc:
19506     case DW_FORM_data16:
19507       blk = DW_BLOCK (attr);
19508       if (TYPE_LENGTH (type) != blk->size)
19509         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19510                                                       TYPE_LENGTH (type));
19511       *bytes = blk->data;
19512       break;
19513
19514       /* The DW_AT_const_value attributes are supposed to carry the
19515          symbol's value "represented as it would be on the target
19516          architecture."  By the time we get here, it's already been
19517          converted to host endianness, so we just need to sign- or
19518          zero-extend it as appropriate.  */
19519     case DW_FORM_data1:
19520       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19521       break;
19522     case DW_FORM_data2:
19523       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19524       break;
19525     case DW_FORM_data4:
19526       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19527       break;
19528     case DW_FORM_data8:
19529       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19530       break;
19531
19532     case DW_FORM_sdata:
19533     case DW_FORM_implicit_const:
19534       *value = DW_SND (attr);
19535       break;
19536
19537     case DW_FORM_udata:
19538       *value = DW_UNSND (attr);
19539       break;
19540
19541     default:
19542       complaint (&symfile_complaints,
19543                  _("unsupported const value attribute form: '%s'"),
19544                  dwarf_form_name (attr->form));
19545       *value = 0;
19546       break;
19547     }
19548 }
19549
19550
19551 /* Copy constant value from an attribute to a symbol.  */
19552
19553 static void
19554 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19555                     struct dwarf2_cu *cu)
19556 {
19557   struct objfile *objfile = cu->objfile;
19558   LONGEST value;
19559   const gdb_byte *bytes;
19560   struct dwarf2_locexpr_baton *baton;
19561
19562   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19563                            SYMBOL_PRINT_NAME (sym),
19564                            &objfile->objfile_obstack, cu,
19565                            &value, &bytes, &baton);
19566
19567   if (baton != NULL)
19568     {
19569       SYMBOL_LOCATION_BATON (sym) = baton;
19570       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19571     }
19572   else if (bytes != NULL)
19573      {
19574       SYMBOL_VALUE_BYTES (sym) = bytes;
19575       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19576     }
19577   else
19578     {
19579       SYMBOL_VALUE (sym) = value;
19580       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19581     }
19582 }
19583
19584 /* Return the type of the die in question using its DW_AT_type attribute.  */
19585
19586 static struct type *
19587 die_type (struct die_info *die, struct dwarf2_cu *cu)
19588 {
19589   struct attribute *type_attr;
19590
19591   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19592   if (!type_attr)
19593     {
19594       /* A missing DW_AT_type represents a void type.  */
19595       return objfile_type (cu->objfile)->builtin_void;
19596     }
19597
19598   return lookup_die_type (die, type_attr, cu);
19599 }
19600
19601 /* True iff CU's producer generates GNAT Ada auxiliary information
19602    that allows to find parallel types through that information instead
19603    of having to do expensive parallel lookups by type name.  */
19604
19605 static int
19606 need_gnat_info (struct dwarf2_cu *cu)
19607 {
19608   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19609      of GNAT produces this auxiliary information, without any indication
19610      that it is produced.  Part of enhancing the FSF version of GNAT
19611      to produce that information will be to put in place an indicator
19612      that we can use in order to determine whether the descriptive type
19613      info is available or not.  One suggestion that has been made is
19614      to use a new attribute, attached to the CU die.  For now, assume
19615      that the descriptive type info is not available.  */
19616   return 0;
19617 }
19618
19619 /* Return the auxiliary type of the die in question using its
19620    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19621    attribute is not present.  */
19622
19623 static struct type *
19624 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19625 {
19626   struct attribute *type_attr;
19627
19628   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19629   if (!type_attr)
19630     return NULL;
19631
19632   return lookup_die_type (die, type_attr, cu);
19633 }
19634
19635 /* If DIE has a descriptive_type attribute, then set the TYPE's
19636    descriptive type accordingly.  */
19637
19638 static void
19639 set_descriptive_type (struct type *type, struct die_info *die,
19640                       struct dwarf2_cu *cu)
19641 {
19642   struct type *descriptive_type = die_descriptive_type (die, cu);
19643
19644   if (descriptive_type)
19645     {
19646       ALLOCATE_GNAT_AUX_TYPE (type);
19647       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19648     }
19649 }
19650
19651 /* Return the containing type of the die in question using its
19652    DW_AT_containing_type attribute.  */
19653
19654 static struct type *
19655 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19656 {
19657   struct attribute *type_attr;
19658
19659   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19660   if (!type_attr)
19661     error (_("Dwarf Error: Problem turning containing type into gdb type "
19662              "[in module %s]"), objfile_name (cu->objfile));
19663
19664   return lookup_die_type (die, type_attr, cu);
19665 }
19666
19667 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19668
19669 static struct type *
19670 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19671 {
19672   struct objfile *objfile = dwarf2_per_objfile->objfile;
19673   char *message, *saved;
19674
19675   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19676                         objfile_name (objfile),
19677                         to_underlying (cu->header.sect_off),
19678                         to_underlying (die->sect_off));
19679   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19680                                   message, strlen (message));
19681   xfree (message);
19682
19683   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19684 }
19685
19686 /* Look up the type of DIE in CU using its type attribute ATTR.
19687    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19688    DW_AT_containing_type.
19689    If there is no type substitute an error marker.  */
19690
19691 static struct type *
19692 lookup_die_type (struct die_info *die, const struct attribute *attr,
19693                  struct dwarf2_cu *cu)
19694 {
19695   struct objfile *objfile = cu->objfile;
19696   struct type *this_type;
19697
19698   gdb_assert (attr->name == DW_AT_type
19699               || attr->name == DW_AT_GNAT_descriptive_type
19700               || attr->name == DW_AT_containing_type);
19701
19702   /* First see if we have it cached.  */
19703
19704   if (attr->form == DW_FORM_GNU_ref_alt)
19705     {
19706       struct dwarf2_per_cu_data *per_cu;
19707       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19708
19709       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19710       this_type = get_die_type_at_offset (sect_off, per_cu);
19711     }
19712   else if (attr_form_is_ref (attr))
19713     {
19714       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19715
19716       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19717     }
19718   else if (attr->form == DW_FORM_ref_sig8)
19719     {
19720       ULONGEST signature = DW_SIGNATURE (attr);
19721
19722       return get_signatured_type (die, signature, cu);
19723     }
19724   else
19725     {
19726       complaint (&symfile_complaints,
19727                  _("Dwarf Error: Bad type attribute %s in DIE"
19728                    " at 0x%x [in module %s]"),
19729                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19730                  objfile_name (objfile));
19731       return build_error_marker_type (cu, die);
19732     }
19733
19734   /* If not cached we need to read it in.  */
19735
19736   if (this_type == NULL)
19737     {
19738       struct die_info *type_die = NULL;
19739       struct dwarf2_cu *type_cu = cu;
19740
19741       if (attr_form_is_ref (attr))
19742         type_die = follow_die_ref (die, attr, &type_cu);
19743       if (type_die == NULL)
19744         return build_error_marker_type (cu, die);
19745       /* If we find the type now, it's probably because the type came
19746          from an inter-CU reference and the type's CU got expanded before
19747          ours.  */
19748       this_type = read_type_die (type_die, type_cu);
19749     }
19750
19751   /* If we still don't have a type use an error marker.  */
19752
19753   if (this_type == NULL)
19754     return build_error_marker_type (cu, die);
19755
19756   return this_type;
19757 }
19758
19759 /* Return the type in DIE, CU.
19760    Returns NULL for invalid types.
19761
19762    This first does a lookup in die_type_hash,
19763    and only reads the die in if necessary.
19764
19765    NOTE: This can be called when reading in partial or full symbols.  */
19766
19767 static struct type *
19768 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19769 {
19770   struct type *this_type;
19771
19772   this_type = get_die_type (die, cu);
19773   if (this_type)
19774     return this_type;
19775
19776   return read_type_die_1 (die, cu);
19777 }
19778
19779 /* Read the type in DIE, CU.
19780    Returns NULL for invalid types.  */
19781
19782 static struct type *
19783 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19784 {
19785   struct type *this_type = NULL;
19786
19787   switch (die->tag)
19788     {
19789     case DW_TAG_class_type:
19790     case DW_TAG_interface_type:
19791     case DW_TAG_structure_type:
19792     case DW_TAG_union_type:
19793       this_type = read_structure_type (die, cu);
19794       break;
19795     case DW_TAG_enumeration_type:
19796       this_type = read_enumeration_type (die, cu);
19797       break;
19798     case DW_TAG_subprogram:
19799     case DW_TAG_subroutine_type:
19800     case DW_TAG_inlined_subroutine:
19801       this_type = read_subroutine_type (die, cu);
19802       break;
19803     case DW_TAG_array_type:
19804       this_type = read_array_type (die, cu);
19805       break;
19806     case DW_TAG_set_type:
19807       this_type = read_set_type (die, cu);
19808       break;
19809     case DW_TAG_pointer_type:
19810       this_type = read_tag_pointer_type (die, cu);
19811       break;
19812     case DW_TAG_ptr_to_member_type:
19813       this_type = read_tag_ptr_to_member_type (die, cu);
19814       break;
19815     case DW_TAG_reference_type:
19816       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19817       break;
19818     case DW_TAG_rvalue_reference_type:
19819       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19820       break;
19821     case DW_TAG_const_type:
19822       this_type = read_tag_const_type (die, cu);
19823       break;
19824     case DW_TAG_volatile_type:
19825       this_type = read_tag_volatile_type (die, cu);
19826       break;
19827     case DW_TAG_restrict_type:
19828       this_type = read_tag_restrict_type (die, cu);
19829       break;
19830     case DW_TAG_string_type:
19831       this_type = read_tag_string_type (die, cu);
19832       break;
19833     case DW_TAG_typedef:
19834       this_type = read_typedef (die, cu);
19835       break;
19836     case DW_TAG_subrange_type:
19837       this_type = read_subrange_type (die, cu);
19838       break;
19839     case DW_TAG_base_type:
19840       this_type = read_base_type (die, cu);
19841       break;
19842     case DW_TAG_unspecified_type:
19843       this_type = read_unspecified_type (die, cu);
19844       break;
19845     case DW_TAG_namespace:
19846       this_type = read_namespace_type (die, cu);
19847       break;
19848     case DW_TAG_module:
19849       this_type = read_module_type (die, cu);
19850       break;
19851     case DW_TAG_atomic_type:
19852       this_type = read_tag_atomic_type (die, cu);
19853       break;
19854     default:
19855       complaint (&symfile_complaints,
19856                  _("unexpected tag in read_type_die: '%s'"),
19857                  dwarf_tag_name (die->tag));
19858       break;
19859     }
19860
19861   return this_type;
19862 }
19863
19864 /* See if we can figure out if the class lives in a namespace.  We do
19865    this by looking for a member function; its demangled name will
19866    contain namespace info, if there is any.
19867    Return the computed name or NULL.
19868    Space for the result is allocated on the objfile's obstack.
19869    This is the full-die version of guess_partial_die_structure_name.
19870    In this case we know DIE has no useful parent.  */
19871
19872 static char *
19873 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19874 {
19875   struct die_info *spec_die;
19876   struct dwarf2_cu *spec_cu;
19877   struct die_info *child;
19878
19879   spec_cu = cu;
19880   spec_die = die_specification (die, &spec_cu);
19881   if (spec_die != NULL)
19882     {
19883       die = spec_die;
19884       cu = spec_cu;
19885     }
19886
19887   for (child = die->child;
19888        child != NULL;
19889        child = child->sibling)
19890     {
19891       if (child->tag == DW_TAG_subprogram)
19892         {
19893           const char *linkage_name = dw2_linkage_name (child, cu);
19894
19895           if (linkage_name != NULL)
19896             {
19897               char *actual_name
19898                 = language_class_name_from_physname (cu->language_defn,
19899                                                      linkage_name);
19900               char *name = NULL;
19901
19902               if (actual_name != NULL)
19903                 {
19904                   const char *die_name = dwarf2_name (die, cu);
19905
19906                   if (die_name != NULL
19907                       && strcmp (die_name, actual_name) != 0)
19908                     {
19909                       /* Strip off the class name from the full name.
19910                          We want the prefix.  */
19911                       int die_name_len = strlen (die_name);
19912                       int actual_name_len = strlen (actual_name);
19913
19914                       /* Test for '::' as a sanity check.  */
19915                       if (actual_name_len > die_name_len + 2
19916                           && actual_name[actual_name_len
19917                                          - die_name_len - 1] == ':')
19918                         name = (char *) obstack_copy0 (
19919                           &cu->objfile->per_bfd->storage_obstack,
19920                           actual_name, actual_name_len - die_name_len - 2);
19921                     }
19922                 }
19923               xfree (actual_name);
19924               return name;
19925             }
19926         }
19927     }
19928
19929   return NULL;
19930 }
19931
19932 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19933    prefix part in such case.  See
19934    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19935
19936 static const char *
19937 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19938 {
19939   struct attribute *attr;
19940   const char *base;
19941
19942   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19943       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19944     return NULL;
19945
19946   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19947     return NULL;
19948
19949   attr = dw2_linkage_name_attr (die, cu);
19950   if (attr == NULL || DW_STRING (attr) == NULL)
19951     return NULL;
19952
19953   /* dwarf2_name had to be already called.  */
19954   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19955
19956   /* Strip the base name, keep any leading namespaces/classes.  */
19957   base = strrchr (DW_STRING (attr), ':');
19958   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19959     return "";
19960
19961   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19962                                  DW_STRING (attr),
19963                                  &base[-1] - DW_STRING (attr));
19964 }
19965
19966 /* Return the name of the namespace/class that DIE is defined within,
19967    or "" if we can't tell.  The caller should not xfree the result.
19968
19969    For example, if we're within the method foo() in the following
19970    code:
19971
19972    namespace N {
19973      class C {
19974        void foo () {
19975        }
19976      };
19977    }
19978
19979    then determine_prefix on foo's die will return "N::C".  */
19980
19981 static const char *
19982 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19983 {
19984   struct die_info *parent, *spec_die;
19985   struct dwarf2_cu *spec_cu;
19986   struct type *parent_type;
19987   const char *retval;
19988
19989   if (cu->language != language_cplus
19990       && cu->language != language_fortran && cu->language != language_d
19991       && cu->language != language_rust)
19992     return "";
19993
19994   retval = anonymous_struct_prefix (die, cu);
19995   if (retval)
19996     return retval;
19997
19998   /* We have to be careful in the presence of DW_AT_specification.
19999      For example, with GCC 3.4, given the code
20000
20001      namespace N {
20002        void foo() {
20003          // Definition of N::foo.
20004        }
20005      }
20006
20007      then we'll have a tree of DIEs like this:
20008
20009      1: DW_TAG_compile_unit
20010        2: DW_TAG_namespace        // N
20011          3: DW_TAG_subprogram     // declaration of N::foo
20012        4: DW_TAG_subprogram       // definition of N::foo
20013             DW_AT_specification   // refers to die #3
20014
20015      Thus, when processing die #4, we have to pretend that we're in
20016      the context of its DW_AT_specification, namely the contex of die
20017      #3.  */
20018   spec_cu = cu;
20019   spec_die = die_specification (die, &spec_cu);
20020   if (spec_die == NULL)
20021     parent = die->parent;
20022   else
20023     {
20024       parent = spec_die->parent;
20025       cu = spec_cu;
20026     }
20027
20028   if (parent == NULL)
20029     return "";
20030   else if (parent->building_fullname)
20031     {
20032       const char *name;
20033       const char *parent_name;
20034
20035       /* It has been seen on RealView 2.2 built binaries,
20036          DW_TAG_template_type_param types actually _defined_ as
20037          children of the parent class:
20038
20039          enum E {};
20040          template class <class Enum> Class{};
20041          Class<enum E> class_e;
20042
20043          1: DW_TAG_class_type (Class)
20044            2: DW_TAG_enumeration_type (E)
20045              3: DW_TAG_enumerator (enum1:0)
20046              3: DW_TAG_enumerator (enum2:1)
20047              ...
20048            2: DW_TAG_template_type_param
20049               DW_AT_type  DW_FORM_ref_udata (E)
20050
20051          Besides being broken debug info, it can put GDB into an
20052          infinite loop.  Consider:
20053
20054          When we're building the full name for Class<E>, we'll start
20055          at Class, and go look over its template type parameters,
20056          finding E.  We'll then try to build the full name of E, and
20057          reach here.  We're now trying to build the full name of E,
20058          and look over the parent DIE for containing scope.  In the
20059          broken case, if we followed the parent DIE of E, we'd again
20060          find Class, and once again go look at its template type
20061          arguments, etc., etc.  Simply don't consider such parent die
20062          as source-level parent of this die (it can't be, the language
20063          doesn't allow it), and break the loop here.  */
20064       name = dwarf2_name (die, cu);
20065       parent_name = dwarf2_name (parent, cu);
20066       complaint (&symfile_complaints,
20067                  _("template param type '%s' defined within parent '%s'"),
20068                  name ? name : "<unknown>",
20069                  parent_name ? parent_name : "<unknown>");
20070       return "";
20071     }
20072   else
20073     switch (parent->tag)
20074       {
20075       case DW_TAG_namespace:
20076         parent_type = read_type_die (parent, cu);
20077         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20078            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20079            Work around this problem here.  */
20080         if (cu->language == language_cplus
20081             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20082           return "";
20083         /* We give a name to even anonymous namespaces.  */
20084         return TYPE_TAG_NAME (parent_type);
20085       case DW_TAG_class_type:
20086       case DW_TAG_interface_type:
20087       case DW_TAG_structure_type:
20088       case DW_TAG_union_type:
20089       case DW_TAG_module:
20090         parent_type = read_type_die (parent, cu);
20091         if (TYPE_TAG_NAME (parent_type) != NULL)
20092           return TYPE_TAG_NAME (parent_type);
20093         else
20094           /* An anonymous structure is only allowed non-static data
20095              members; no typedefs, no member functions, et cetera.
20096              So it does not need a prefix.  */
20097           return "";
20098       case DW_TAG_compile_unit:
20099       case DW_TAG_partial_unit:
20100         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20101         if (cu->language == language_cplus
20102             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20103             && die->child != NULL
20104             && (die->tag == DW_TAG_class_type
20105                 || die->tag == DW_TAG_structure_type
20106                 || die->tag == DW_TAG_union_type))
20107           {
20108             char *name = guess_full_die_structure_name (die, cu);
20109             if (name != NULL)
20110               return name;
20111           }
20112         return "";
20113       case DW_TAG_enumeration_type:
20114         parent_type = read_type_die (parent, cu);
20115         if (TYPE_DECLARED_CLASS (parent_type))
20116           {
20117             if (TYPE_TAG_NAME (parent_type) != NULL)
20118               return TYPE_TAG_NAME (parent_type);
20119             return "";
20120           }
20121         /* Fall through.  */
20122       default:
20123         return determine_prefix (parent, cu);
20124       }
20125 }
20126
20127 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20128    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20129    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20130    an obconcat, otherwise allocate storage for the result.  The CU argument is
20131    used to determine the language and hence, the appropriate separator.  */
20132
20133 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20134
20135 static char *
20136 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20137                  int physname, struct dwarf2_cu *cu)
20138 {
20139   const char *lead = "";
20140   const char *sep;
20141
20142   if (suffix == NULL || suffix[0] == '\0'
20143       || prefix == NULL || prefix[0] == '\0')
20144     sep = "";
20145   else if (cu->language == language_d)
20146     {
20147       /* For D, the 'main' function could be defined in any module, but it
20148          should never be prefixed.  */
20149       if (strcmp (suffix, "D main") == 0)
20150         {
20151           prefix = "";
20152           sep = "";
20153         }
20154       else
20155         sep = ".";
20156     }
20157   else if (cu->language == language_fortran && physname)
20158     {
20159       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20160          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20161
20162       lead = "__";
20163       sep = "_MOD_";
20164     }
20165   else
20166     sep = "::";
20167
20168   if (prefix == NULL)
20169     prefix = "";
20170   if (suffix == NULL)
20171     suffix = "";
20172
20173   if (obs == NULL)
20174     {
20175       char *retval
20176         = ((char *)
20177            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20178
20179       strcpy (retval, lead);
20180       strcat (retval, prefix);
20181       strcat (retval, sep);
20182       strcat (retval, suffix);
20183       return retval;
20184     }
20185   else
20186     {
20187       /* We have an obstack.  */
20188       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20189     }
20190 }
20191
20192 /* Return sibling of die, NULL if no sibling.  */
20193
20194 static struct die_info *
20195 sibling_die (struct die_info *die)
20196 {
20197   return die->sibling;
20198 }
20199
20200 /* Get name of a die, return NULL if not found.  */
20201
20202 static const char *
20203 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20204                           struct obstack *obstack)
20205 {
20206   if (name && cu->language == language_cplus)
20207     {
20208       std::string canon_name = cp_canonicalize_string (name);
20209
20210       if (!canon_name.empty ())
20211         {
20212           if (canon_name != name)
20213             name = (const char *) obstack_copy0 (obstack,
20214                                                  canon_name.c_str (),
20215                                                  canon_name.length ());
20216         }
20217     }
20218
20219   return name;
20220 }
20221
20222 /* Get name of a die, return NULL if not found.
20223    Anonymous namespaces are converted to their magic string.  */
20224
20225 static const char *
20226 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20227 {
20228   struct attribute *attr;
20229
20230   attr = dwarf2_attr (die, DW_AT_name, cu);
20231   if ((!attr || !DW_STRING (attr))
20232       && die->tag != DW_TAG_namespace
20233       && die->tag != DW_TAG_class_type
20234       && die->tag != DW_TAG_interface_type
20235       && die->tag != DW_TAG_structure_type
20236       && die->tag != DW_TAG_union_type)
20237     return NULL;
20238
20239   switch (die->tag)
20240     {
20241     case DW_TAG_compile_unit:
20242     case DW_TAG_partial_unit:
20243       /* Compilation units have a DW_AT_name that is a filename, not
20244          a source language identifier.  */
20245     case DW_TAG_enumeration_type:
20246     case DW_TAG_enumerator:
20247       /* These tags always have simple identifiers already; no need
20248          to canonicalize them.  */
20249       return DW_STRING (attr);
20250
20251     case DW_TAG_namespace:
20252       if (attr != NULL && DW_STRING (attr) != NULL)
20253         return DW_STRING (attr);
20254       return CP_ANONYMOUS_NAMESPACE_STR;
20255
20256     case DW_TAG_class_type:
20257     case DW_TAG_interface_type:
20258     case DW_TAG_structure_type:
20259     case DW_TAG_union_type:
20260       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20261          structures or unions.  These were of the form "._%d" in GCC 4.1,
20262          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20263          and GCC 4.4.  We work around this problem by ignoring these.  */
20264       if (attr && DW_STRING (attr)
20265           && (startswith (DW_STRING (attr), "._")
20266               || startswith (DW_STRING (attr), "<anonymous")))
20267         return NULL;
20268
20269       /* GCC might emit a nameless typedef that has a linkage name.  See
20270          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20271       if (!attr || DW_STRING (attr) == NULL)
20272         {
20273           char *demangled = NULL;
20274
20275           attr = dw2_linkage_name_attr (die, cu);
20276           if (attr == NULL || DW_STRING (attr) == NULL)
20277             return NULL;
20278
20279           /* Avoid demangling DW_STRING (attr) the second time on a second
20280              call for the same DIE.  */
20281           if (!DW_STRING_IS_CANONICAL (attr))
20282             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20283
20284           if (demangled)
20285             {
20286               const char *base;
20287
20288               /* FIXME: we already did this for the partial symbol... */
20289               DW_STRING (attr)
20290                 = ((const char *)
20291                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20292                                   demangled, strlen (demangled)));
20293               DW_STRING_IS_CANONICAL (attr) = 1;
20294               xfree (demangled);
20295
20296               /* Strip any leading namespaces/classes, keep only the base name.
20297                  DW_AT_name for named DIEs does not contain the prefixes.  */
20298               base = strrchr (DW_STRING (attr), ':');
20299               if (base && base > DW_STRING (attr) && base[-1] == ':')
20300                 return &base[1];
20301               else
20302                 return DW_STRING (attr);
20303             }
20304         }
20305       break;
20306
20307     default:
20308       break;
20309     }
20310
20311   if (!DW_STRING_IS_CANONICAL (attr))
20312     {
20313       DW_STRING (attr)
20314         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20315                                     &cu->objfile->per_bfd->storage_obstack);
20316       DW_STRING_IS_CANONICAL (attr) = 1;
20317     }
20318   return DW_STRING (attr);
20319 }
20320
20321 /* Return the die that this die in an extension of, or NULL if there
20322    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20323    containing the return value on output.  */
20324
20325 static struct die_info *
20326 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20327 {
20328   struct attribute *attr;
20329
20330   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20331   if (attr == NULL)
20332     return NULL;
20333
20334   return follow_die_ref (die, attr, ext_cu);
20335 }
20336
20337 /* Convert a DIE tag into its string name.  */
20338
20339 static const char *
20340 dwarf_tag_name (unsigned tag)
20341 {
20342   const char *name = get_DW_TAG_name (tag);
20343
20344   if (name == NULL)
20345     return "DW_TAG_<unknown>";
20346
20347   return name;
20348 }
20349
20350 /* Convert a DWARF attribute code into its string name.  */
20351
20352 static const char *
20353 dwarf_attr_name (unsigned attr)
20354 {
20355   const char *name;
20356
20357 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20358   if (attr == DW_AT_MIPS_fde)
20359     return "DW_AT_MIPS_fde";
20360 #else
20361   if (attr == DW_AT_HP_block_index)
20362     return "DW_AT_HP_block_index";
20363 #endif
20364
20365   name = get_DW_AT_name (attr);
20366
20367   if (name == NULL)
20368     return "DW_AT_<unknown>";
20369
20370   return name;
20371 }
20372
20373 /* Convert a DWARF value form code into its string name.  */
20374
20375 static const char *
20376 dwarf_form_name (unsigned form)
20377 {
20378   const char *name = get_DW_FORM_name (form);
20379
20380   if (name == NULL)
20381     return "DW_FORM_<unknown>";
20382
20383   return name;
20384 }
20385
20386 static const char *
20387 dwarf_bool_name (unsigned mybool)
20388 {
20389   if (mybool)
20390     return "TRUE";
20391   else
20392     return "FALSE";
20393 }
20394
20395 /* Convert a DWARF type code into its string name.  */
20396
20397 static const char *
20398 dwarf_type_encoding_name (unsigned enc)
20399 {
20400   const char *name = get_DW_ATE_name (enc);
20401
20402   if (name == NULL)
20403     return "DW_ATE_<unknown>";
20404
20405   return name;
20406 }
20407
20408 static void
20409 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20410 {
20411   unsigned int i;
20412
20413   print_spaces (indent, f);
20414   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20415                       dwarf_tag_name (die->tag), die->abbrev,
20416                       to_underlying (die->sect_off));
20417
20418   if (die->parent != NULL)
20419     {
20420       print_spaces (indent, f);
20421       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20422                           to_underlying (die->parent->sect_off));
20423     }
20424
20425   print_spaces (indent, f);
20426   fprintf_unfiltered (f, "  has children: %s\n",
20427            dwarf_bool_name (die->child != NULL));
20428
20429   print_spaces (indent, f);
20430   fprintf_unfiltered (f, "  attributes:\n");
20431
20432   for (i = 0; i < die->num_attrs; ++i)
20433     {
20434       print_spaces (indent, f);
20435       fprintf_unfiltered (f, "    %s (%s) ",
20436                dwarf_attr_name (die->attrs[i].name),
20437                dwarf_form_name (die->attrs[i].form));
20438
20439       switch (die->attrs[i].form)
20440         {
20441         case DW_FORM_addr:
20442         case DW_FORM_GNU_addr_index:
20443           fprintf_unfiltered (f, "address: ");
20444           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20445           break;
20446         case DW_FORM_block2:
20447         case DW_FORM_block4:
20448         case DW_FORM_block:
20449         case DW_FORM_block1:
20450           fprintf_unfiltered (f, "block: size %s",
20451                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20452           break;
20453         case DW_FORM_exprloc:
20454           fprintf_unfiltered (f, "expression: size %s",
20455                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20456           break;
20457         case DW_FORM_data16:
20458           fprintf_unfiltered (f, "constant of 16 bytes");
20459           break;
20460         case DW_FORM_ref_addr:
20461           fprintf_unfiltered (f, "ref address: ");
20462           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20463           break;
20464         case DW_FORM_GNU_ref_alt:
20465           fprintf_unfiltered (f, "alt ref address: ");
20466           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20467           break;
20468         case DW_FORM_ref1:
20469         case DW_FORM_ref2:
20470         case DW_FORM_ref4:
20471         case DW_FORM_ref8:
20472         case DW_FORM_ref_udata:
20473           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20474                               (long) (DW_UNSND (&die->attrs[i])));
20475           break;
20476         case DW_FORM_data1:
20477         case DW_FORM_data2:
20478         case DW_FORM_data4:
20479         case DW_FORM_data8:
20480         case DW_FORM_udata:
20481         case DW_FORM_sdata:
20482           fprintf_unfiltered (f, "constant: %s",
20483                               pulongest (DW_UNSND (&die->attrs[i])));
20484           break;
20485         case DW_FORM_sec_offset:
20486           fprintf_unfiltered (f, "section offset: %s",
20487                               pulongest (DW_UNSND (&die->attrs[i])));
20488           break;
20489         case DW_FORM_ref_sig8:
20490           fprintf_unfiltered (f, "signature: %s",
20491                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20492           break;
20493         case DW_FORM_string:
20494         case DW_FORM_strp:
20495         case DW_FORM_line_strp:
20496         case DW_FORM_GNU_str_index:
20497         case DW_FORM_GNU_strp_alt:
20498           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20499                    DW_STRING (&die->attrs[i])
20500                    ? DW_STRING (&die->attrs[i]) : "",
20501                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20502           break;
20503         case DW_FORM_flag:
20504           if (DW_UNSND (&die->attrs[i]))
20505             fprintf_unfiltered (f, "flag: TRUE");
20506           else
20507             fprintf_unfiltered (f, "flag: FALSE");
20508           break;
20509         case DW_FORM_flag_present:
20510           fprintf_unfiltered (f, "flag: TRUE");
20511           break;
20512         case DW_FORM_indirect:
20513           /* The reader will have reduced the indirect form to
20514              the "base form" so this form should not occur.  */
20515           fprintf_unfiltered (f, 
20516                               "unexpected attribute form: DW_FORM_indirect");
20517           break;
20518         case DW_FORM_implicit_const:
20519           fprintf_unfiltered (f, "constant: %s",
20520                               plongest (DW_SND (&die->attrs[i])));
20521           break;
20522         default:
20523           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20524                    die->attrs[i].form);
20525           break;
20526         }
20527       fprintf_unfiltered (f, "\n");
20528     }
20529 }
20530
20531 static void
20532 dump_die_for_error (struct die_info *die)
20533 {
20534   dump_die_shallow (gdb_stderr, 0, die);
20535 }
20536
20537 static void
20538 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20539 {
20540   int indent = level * 4;
20541
20542   gdb_assert (die != NULL);
20543
20544   if (level >= max_level)
20545     return;
20546
20547   dump_die_shallow (f, indent, die);
20548
20549   if (die->child != NULL)
20550     {
20551       print_spaces (indent, f);
20552       fprintf_unfiltered (f, "  Children:");
20553       if (level + 1 < max_level)
20554         {
20555           fprintf_unfiltered (f, "\n");
20556           dump_die_1 (f, level + 1, max_level, die->child);
20557         }
20558       else
20559         {
20560           fprintf_unfiltered (f,
20561                               " [not printed, max nesting level reached]\n");
20562         }
20563     }
20564
20565   if (die->sibling != NULL && level > 0)
20566     {
20567       dump_die_1 (f, level, max_level, die->sibling);
20568     }
20569 }
20570
20571 /* This is called from the pdie macro in gdbinit.in.
20572    It's not static so gcc will keep a copy callable from gdb.  */
20573
20574 void
20575 dump_die (struct die_info *die, int max_level)
20576 {
20577   dump_die_1 (gdb_stdlog, 0, max_level, die);
20578 }
20579
20580 static void
20581 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20582 {
20583   void **slot;
20584
20585   slot = htab_find_slot_with_hash (cu->die_hash, die,
20586                                    to_underlying (die->sect_off),
20587                                    INSERT);
20588
20589   *slot = die;
20590 }
20591
20592 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20593    required kind.  */
20594
20595 static sect_offset
20596 dwarf2_get_ref_die_offset (const struct attribute *attr)
20597 {
20598   if (attr_form_is_ref (attr))
20599     return (sect_offset) DW_UNSND (attr);
20600
20601   complaint (&symfile_complaints,
20602              _("unsupported die ref attribute form: '%s'"),
20603              dwarf_form_name (attr->form));
20604   return {};
20605 }
20606
20607 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20608  * the value held by the attribute is not constant.  */
20609
20610 static LONGEST
20611 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20612 {
20613   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20614     return DW_SND (attr);
20615   else if (attr->form == DW_FORM_udata
20616            || attr->form == DW_FORM_data1
20617            || attr->form == DW_FORM_data2
20618            || attr->form == DW_FORM_data4
20619            || attr->form == DW_FORM_data8)
20620     return DW_UNSND (attr);
20621   else
20622     {
20623       /* For DW_FORM_data16 see attr_form_is_constant.  */
20624       complaint (&symfile_complaints,
20625                  _("Attribute value is not a constant (%s)"),
20626                  dwarf_form_name (attr->form));
20627       return default_value;
20628     }
20629 }
20630
20631 /* Follow reference or signature attribute ATTR of SRC_DIE.
20632    On entry *REF_CU is the CU of SRC_DIE.
20633    On exit *REF_CU is the CU of the result.  */
20634
20635 static struct die_info *
20636 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20637                        struct dwarf2_cu **ref_cu)
20638 {
20639   struct die_info *die;
20640
20641   if (attr_form_is_ref (attr))
20642     die = follow_die_ref (src_die, attr, ref_cu);
20643   else if (attr->form == DW_FORM_ref_sig8)
20644     die = follow_die_sig (src_die, attr, ref_cu);
20645   else
20646     {
20647       dump_die_for_error (src_die);
20648       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20649              objfile_name ((*ref_cu)->objfile));
20650     }
20651
20652   return die;
20653 }
20654
20655 /* Follow reference OFFSET.
20656    On entry *REF_CU is the CU of the source die referencing OFFSET.
20657    On exit *REF_CU is the CU of the result.
20658    Returns NULL if OFFSET is invalid.  */
20659
20660 static struct die_info *
20661 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20662                    struct dwarf2_cu **ref_cu)
20663 {
20664   struct die_info temp_die;
20665   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20666
20667   gdb_assert (cu->per_cu != NULL);
20668
20669   target_cu = cu;
20670
20671   if (cu->per_cu->is_debug_types)
20672     {
20673       /* .debug_types CUs cannot reference anything outside their CU.
20674          If they need to, they have to reference a signatured type via
20675          DW_FORM_ref_sig8.  */
20676       if (!offset_in_cu_p (&cu->header, sect_off))
20677         return NULL;
20678     }
20679   else if (offset_in_dwz != cu->per_cu->is_dwz
20680            || !offset_in_cu_p (&cu->header, sect_off))
20681     {
20682       struct dwarf2_per_cu_data *per_cu;
20683
20684       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20685                                                  cu->objfile);
20686
20687       /* If necessary, add it to the queue and load its DIEs.  */
20688       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20689         load_full_comp_unit (per_cu, cu->language);
20690
20691       target_cu = per_cu->cu;
20692     }
20693   else if (cu->dies == NULL)
20694     {
20695       /* We're loading full DIEs during partial symbol reading.  */
20696       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20697       load_full_comp_unit (cu->per_cu, language_minimal);
20698     }
20699
20700   *ref_cu = target_cu;
20701   temp_die.sect_off = sect_off;
20702   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20703                                                   &temp_die,
20704                                                   to_underlying (sect_off));
20705 }
20706
20707 /* Follow reference attribute ATTR of SRC_DIE.
20708    On entry *REF_CU is the CU of SRC_DIE.
20709    On exit *REF_CU is the CU of the result.  */
20710
20711 static struct die_info *
20712 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20713                 struct dwarf2_cu **ref_cu)
20714 {
20715   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20716   struct dwarf2_cu *cu = *ref_cu;
20717   struct die_info *die;
20718
20719   die = follow_die_offset (sect_off,
20720                            (attr->form == DW_FORM_GNU_ref_alt
20721                             || cu->per_cu->is_dwz),
20722                            ref_cu);
20723   if (!die)
20724     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20725            "at 0x%x [in module %s]"),
20726            to_underlying (sect_off), to_underlying (src_die->sect_off),
20727            objfile_name (cu->objfile));
20728
20729   return die;
20730 }
20731
20732 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20733    Returned value is intended for DW_OP_call*.  Returned
20734    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20735
20736 struct dwarf2_locexpr_baton
20737 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20738                                struct dwarf2_per_cu_data *per_cu,
20739                                CORE_ADDR (*get_frame_pc) (void *baton),
20740                                void *baton)
20741 {
20742   struct dwarf2_cu *cu;
20743   struct die_info *die;
20744   struct attribute *attr;
20745   struct dwarf2_locexpr_baton retval;
20746
20747   dw2_setup (per_cu->objfile);
20748
20749   if (per_cu->cu == NULL)
20750     load_cu (per_cu);
20751   cu = per_cu->cu;
20752   if (cu == NULL)
20753     {
20754       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20755          Instead just throw an error, not much else we can do.  */
20756       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20757              to_underlying (sect_off), objfile_name (per_cu->objfile));
20758     }
20759
20760   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20761   if (!die)
20762     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20763            to_underlying (sect_off), objfile_name (per_cu->objfile));
20764
20765   attr = dwarf2_attr (die, DW_AT_location, cu);
20766   if (!attr)
20767     {
20768       /* DWARF: "If there is no such attribute, then there is no effect.".
20769          DATA is ignored if SIZE is 0.  */
20770
20771       retval.data = NULL;
20772       retval.size = 0;
20773     }
20774   else if (attr_form_is_section_offset (attr))
20775     {
20776       struct dwarf2_loclist_baton loclist_baton;
20777       CORE_ADDR pc = (*get_frame_pc) (baton);
20778       size_t size;
20779
20780       fill_in_loclist_baton (cu, &loclist_baton, attr);
20781
20782       retval.data = dwarf2_find_location_expression (&loclist_baton,
20783                                                      &size, pc);
20784       retval.size = size;
20785     }
20786   else
20787     {
20788       if (!attr_form_is_block (attr))
20789         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20790                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20791                to_underlying (sect_off), objfile_name (per_cu->objfile));
20792
20793       retval.data = DW_BLOCK (attr)->data;
20794       retval.size = DW_BLOCK (attr)->size;
20795     }
20796   retval.per_cu = cu->per_cu;
20797
20798   age_cached_comp_units ();
20799
20800   return retval;
20801 }
20802
20803 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20804    offset.  */
20805
20806 struct dwarf2_locexpr_baton
20807 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20808                              struct dwarf2_per_cu_data *per_cu,
20809                              CORE_ADDR (*get_frame_pc) (void *baton),
20810                              void *baton)
20811 {
20812   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20813
20814   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20815 }
20816
20817 /* Write a constant of a given type as target-ordered bytes into
20818    OBSTACK.  */
20819
20820 static const gdb_byte *
20821 write_constant_as_bytes (struct obstack *obstack,
20822                          enum bfd_endian byte_order,
20823                          struct type *type,
20824                          ULONGEST value,
20825                          LONGEST *len)
20826 {
20827   gdb_byte *result;
20828
20829   *len = TYPE_LENGTH (type);
20830   result = (gdb_byte *) obstack_alloc (obstack, *len);
20831   store_unsigned_integer (result, *len, byte_order, value);
20832
20833   return result;
20834 }
20835
20836 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20837    pointer to the constant bytes and set LEN to the length of the
20838    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20839    does not have a DW_AT_const_value, return NULL.  */
20840
20841 const gdb_byte *
20842 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20843                              struct dwarf2_per_cu_data *per_cu,
20844                              struct obstack *obstack,
20845                              LONGEST *len)
20846 {
20847   struct dwarf2_cu *cu;
20848   struct die_info *die;
20849   struct attribute *attr;
20850   const gdb_byte *result = NULL;
20851   struct type *type;
20852   LONGEST value;
20853   enum bfd_endian byte_order;
20854
20855   dw2_setup (per_cu->objfile);
20856
20857   if (per_cu->cu == NULL)
20858     load_cu (per_cu);
20859   cu = per_cu->cu;
20860   if (cu == NULL)
20861     {
20862       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20863          Instead just throw an error, not much else we can do.  */
20864       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20865              to_underlying (sect_off), objfile_name (per_cu->objfile));
20866     }
20867
20868   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20869   if (!die)
20870     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20871            to_underlying (sect_off), objfile_name (per_cu->objfile));
20872
20873
20874   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20875   if (attr == NULL)
20876     return NULL;
20877
20878   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20879                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20880
20881   switch (attr->form)
20882     {
20883     case DW_FORM_addr:
20884     case DW_FORM_GNU_addr_index:
20885       {
20886         gdb_byte *tem;
20887
20888         *len = cu->header.addr_size;
20889         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20890         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20891         result = tem;
20892       }
20893       break;
20894     case DW_FORM_string:
20895     case DW_FORM_strp:
20896     case DW_FORM_GNU_str_index:
20897     case DW_FORM_GNU_strp_alt:
20898       /* DW_STRING is already allocated on the objfile obstack, point
20899          directly to it.  */
20900       result = (const gdb_byte *) DW_STRING (attr);
20901       *len = strlen (DW_STRING (attr));
20902       break;
20903     case DW_FORM_block1:
20904     case DW_FORM_block2:
20905     case DW_FORM_block4:
20906     case DW_FORM_block:
20907     case DW_FORM_exprloc:
20908     case DW_FORM_data16:
20909       result = DW_BLOCK (attr)->data;
20910       *len = DW_BLOCK (attr)->size;
20911       break;
20912
20913       /* The DW_AT_const_value attributes are supposed to carry the
20914          symbol's value "represented as it would be on the target
20915          architecture."  By the time we get here, it's already been
20916          converted to host endianness, so we just need to sign- or
20917          zero-extend it as appropriate.  */
20918     case DW_FORM_data1:
20919       type = die_type (die, cu);
20920       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20921       if (result == NULL)
20922         result = write_constant_as_bytes (obstack, byte_order,
20923                                           type, value, len);
20924       break;
20925     case DW_FORM_data2:
20926       type = die_type (die, cu);
20927       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20928       if (result == NULL)
20929         result = write_constant_as_bytes (obstack, byte_order,
20930                                           type, value, len);
20931       break;
20932     case DW_FORM_data4:
20933       type = die_type (die, cu);
20934       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20935       if (result == NULL)
20936         result = write_constant_as_bytes (obstack, byte_order,
20937                                           type, value, len);
20938       break;
20939     case DW_FORM_data8:
20940       type = die_type (die, cu);
20941       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20942       if (result == NULL)
20943         result = write_constant_as_bytes (obstack, byte_order,
20944                                           type, value, len);
20945       break;
20946
20947     case DW_FORM_sdata:
20948     case DW_FORM_implicit_const:
20949       type = die_type (die, cu);
20950       result = write_constant_as_bytes (obstack, byte_order,
20951                                         type, DW_SND (attr), len);
20952       break;
20953
20954     case DW_FORM_udata:
20955       type = die_type (die, cu);
20956       result = write_constant_as_bytes (obstack, byte_order,
20957                                         type, DW_UNSND (attr), len);
20958       break;
20959
20960     default:
20961       complaint (&symfile_complaints,
20962                  _("unsupported const value attribute form: '%s'"),
20963                  dwarf_form_name (attr->form));
20964       break;
20965     }
20966
20967   return result;
20968 }
20969
20970 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20971    valid type for this die is found.  */
20972
20973 struct type *
20974 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20975                                 struct dwarf2_per_cu_data *per_cu)
20976 {
20977   struct dwarf2_cu *cu;
20978   struct die_info *die;
20979
20980   dw2_setup (per_cu->objfile);
20981
20982   if (per_cu->cu == NULL)
20983     load_cu (per_cu);
20984   cu = per_cu->cu;
20985   if (!cu)
20986     return NULL;
20987
20988   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20989   if (!die)
20990     return NULL;
20991
20992   return die_type (die, cu);
20993 }
20994
20995 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20996    PER_CU.  */
20997
20998 struct type *
20999 dwarf2_get_die_type (cu_offset die_offset,
21000                      struct dwarf2_per_cu_data *per_cu)
21001 {
21002   dw2_setup (per_cu->objfile);
21003
21004   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21005   return get_die_type_at_offset (die_offset_sect, per_cu);
21006 }
21007
21008 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21009    On entry *REF_CU is the CU of SRC_DIE.
21010    On exit *REF_CU is the CU of the result.
21011    Returns NULL if the referenced DIE isn't found.  */
21012
21013 static struct die_info *
21014 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21015                   struct dwarf2_cu **ref_cu)
21016 {
21017   struct die_info temp_die;
21018   struct dwarf2_cu *sig_cu;
21019   struct die_info *die;
21020
21021   /* While it might be nice to assert sig_type->type == NULL here,
21022      we can get here for DW_AT_imported_declaration where we need
21023      the DIE not the type.  */
21024
21025   /* If necessary, add it to the queue and load its DIEs.  */
21026
21027   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21028     read_signatured_type (sig_type);
21029
21030   sig_cu = sig_type->per_cu.cu;
21031   gdb_assert (sig_cu != NULL);
21032   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21033   temp_die.sect_off = sig_type->type_offset_in_section;
21034   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21035                                                  to_underlying (temp_die.sect_off));
21036   if (die)
21037     {
21038       /* For .gdb_index version 7 keep track of included TUs.
21039          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21040       if (dwarf2_per_objfile->index_table != NULL
21041           && dwarf2_per_objfile->index_table->version <= 7)
21042         {
21043           VEC_safe_push (dwarf2_per_cu_ptr,
21044                          (*ref_cu)->per_cu->imported_symtabs,
21045                          sig_cu->per_cu);
21046         }
21047
21048       *ref_cu = sig_cu;
21049       return die;
21050     }
21051
21052   return NULL;
21053 }
21054
21055 /* Follow signatured type referenced by ATTR in SRC_DIE.
21056    On entry *REF_CU is the CU of SRC_DIE.
21057    On exit *REF_CU is the CU of the result.
21058    The result is the DIE of the type.
21059    If the referenced type cannot be found an error is thrown.  */
21060
21061 static struct die_info *
21062 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21063                 struct dwarf2_cu **ref_cu)
21064 {
21065   ULONGEST signature = DW_SIGNATURE (attr);
21066   struct signatured_type *sig_type;
21067   struct die_info *die;
21068
21069   gdb_assert (attr->form == DW_FORM_ref_sig8);
21070
21071   sig_type = lookup_signatured_type (*ref_cu, signature);
21072   /* sig_type will be NULL if the signatured type is missing from
21073      the debug info.  */
21074   if (sig_type == NULL)
21075     {
21076       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21077                " from DIE at 0x%x [in module %s]"),
21078              hex_string (signature), to_underlying (src_die->sect_off),
21079              objfile_name ((*ref_cu)->objfile));
21080     }
21081
21082   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21083   if (die == NULL)
21084     {
21085       dump_die_for_error (src_die);
21086       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21087                " from DIE at 0x%x [in module %s]"),
21088              hex_string (signature), to_underlying (src_die->sect_off),
21089              objfile_name ((*ref_cu)->objfile));
21090     }
21091
21092   return die;
21093 }
21094
21095 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21096    reading in and processing the type unit if necessary.  */
21097
21098 static struct type *
21099 get_signatured_type (struct die_info *die, ULONGEST signature,
21100                      struct dwarf2_cu *cu)
21101 {
21102   struct signatured_type *sig_type;
21103   struct dwarf2_cu *type_cu;
21104   struct die_info *type_die;
21105   struct type *type;
21106
21107   sig_type = lookup_signatured_type (cu, signature);
21108   /* sig_type will be NULL if the signatured type is missing from
21109      the debug info.  */
21110   if (sig_type == NULL)
21111     {
21112       complaint (&symfile_complaints,
21113                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21114                    " from DIE at 0x%x [in module %s]"),
21115                  hex_string (signature), to_underlying (die->sect_off),
21116                  objfile_name (dwarf2_per_objfile->objfile));
21117       return build_error_marker_type (cu, die);
21118     }
21119
21120   /* If we already know the type we're done.  */
21121   if (sig_type->type != NULL)
21122     return sig_type->type;
21123
21124   type_cu = cu;
21125   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21126   if (type_die != NULL)
21127     {
21128       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21129          is created.  This is important, for example, because for c++ classes
21130          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21131       type = read_type_die (type_die, type_cu);
21132       if (type == NULL)
21133         {
21134           complaint (&symfile_complaints,
21135                      _("Dwarf Error: Cannot build signatured type %s"
21136                        " referenced from DIE at 0x%x [in module %s]"),
21137                      hex_string (signature), to_underlying (die->sect_off),
21138                      objfile_name (dwarf2_per_objfile->objfile));
21139           type = build_error_marker_type (cu, die);
21140         }
21141     }
21142   else
21143     {
21144       complaint (&symfile_complaints,
21145                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21146                    " from DIE at 0x%x [in module %s]"),
21147                  hex_string (signature), to_underlying (die->sect_off),
21148                  objfile_name (dwarf2_per_objfile->objfile));
21149       type = build_error_marker_type (cu, die);
21150     }
21151   sig_type->type = type;
21152
21153   return type;
21154 }
21155
21156 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21157    reading in and processing the type unit if necessary.  */
21158
21159 static struct type *
21160 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21161                           struct dwarf2_cu *cu) /* ARI: editCase function */
21162 {
21163   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21164   if (attr_form_is_ref (attr))
21165     {
21166       struct dwarf2_cu *type_cu = cu;
21167       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21168
21169       return read_type_die (type_die, type_cu);
21170     }
21171   else if (attr->form == DW_FORM_ref_sig8)
21172     {
21173       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21174     }
21175   else
21176     {
21177       complaint (&symfile_complaints,
21178                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21179                    " at 0x%x [in module %s]"),
21180                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21181                  objfile_name (dwarf2_per_objfile->objfile));
21182       return build_error_marker_type (cu, die);
21183     }
21184 }
21185
21186 /* Load the DIEs associated with type unit PER_CU into memory.  */
21187
21188 static void
21189 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21190 {
21191   struct signatured_type *sig_type;
21192
21193   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21194   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21195
21196   /* We have the per_cu, but we need the signatured_type.
21197      Fortunately this is an easy translation.  */
21198   gdb_assert (per_cu->is_debug_types);
21199   sig_type = (struct signatured_type *) per_cu;
21200
21201   gdb_assert (per_cu->cu == NULL);
21202
21203   read_signatured_type (sig_type);
21204
21205   gdb_assert (per_cu->cu != NULL);
21206 }
21207
21208 /* die_reader_func for read_signatured_type.
21209    This is identical to load_full_comp_unit_reader,
21210    but is kept separate for now.  */
21211
21212 static void
21213 read_signatured_type_reader (const struct die_reader_specs *reader,
21214                              const gdb_byte *info_ptr,
21215                              struct die_info *comp_unit_die,
21216                              int has_children,
21217                              void *data)
21218 {
21219   struct dwarf2_cu *cu = reader->cu;
21220
21221   gdb_assert (cu->die_hash == NULL);
21222   cu->die_hash =
21223     htab_create_alloc_ex (cu->header.length / 12,
21224                           die_hash,
21225                           die_eq,
21226                           NULL,
21227                           &cu->comp_unit_obstack,
21228                           hashtab_obstack_allocate,
21229                           dummy_obstack_deallocate);
21230
21231   if (has_children)
21232     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21233                                                   &info_ptr, comp_unit_die);
21234   cu->dies = comp_unit_die;
21235   /* comp_unit_die is not stored in die_hash, no need.  */
21236
21237   /* We try not to read any attributes in this function, because not
21238      all CUs needed for references have been loaded yet, and symbol
21239      table processing isn't initialized.  But we have to set the CU language,
21240      or we won't be able to build types correctly.
21241      Similarly, if we do not read the producer, we can not apply
21242      producer-specific interpretation.  */
21243   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21244 }
21245
21246 /* Read in a signatured type and build its CU and DIEs.
21247    If the type is a stub for the real type in a DWO file,
21248    read in the real type from the DWO file as well.  */
21249
21250 static void
21251 read_signatured_type (struct signatured_type *sig_type)
21252 {
21253   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21254
21255   gdb_assert (per_cu->is_debug_types);
21256   gdb_assert (per_cu->cu == NULL);
21257
21258   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21259                            read_signatured_type_reader, NULL);
21260   sig_type->per_cu.tu_read = 1;
21261 }
21262
21263 /* Decode simple location descriptions.
21264    Given a pointer to a dwarf block that defines a location, compute
21265    the location and return the value.
21266
21267    NOTE drow/2003-11-18: This function is called in two situations
21268    now: for the address of static or global variables (partial symbols
21269    only) and for offsets into structures which are expected to be
21270    (more or less) constant.  The partial symbol case should go away,
21271    and only the constant case should remain.  That will let this
21272    function complain more accurately.  A few special modes are allowed
21273    without complaint for global variables (for instance, global
21274    register values and thread-local values).
21275
21276    A location description containing no operations indicates that the
21277    object is optimized out.  The return value is 0 for that case.
21278    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21279    callers will only want a very basic result and this can become a
21280    complaint.
21281
21282    Note that stack[0] is unused except as a default error return.  */
21283
21284 static CORE_ADDR
21285 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21286 {
21287   struct objfile *objfile = cu->objfile;
21288   size_t i;
21289   size_t size = blk->size;
21290   const gdb_byte *data = blk->data;
21291   CORE_ADDR stack[64];
21292   int stacki;
21293   unsigned int bytes_read, unsnd;
21294   gdb_byte op;
21295
21296   i = 0;
21297   stacki = 0;
21298   stack[stacki] = 0;
21299   stack[++stacki] = 0;
21300
21301   while (i < size)
21302     {
21303       op = data[i++];
21304       switch (op)
21305         {
21306         case DW_OP_lit0:
21307         case DW_OP_lit1:
21308         case DW_OP_lit2:
21309         case DW_OP_lit3:
21310         case DW_OP_lit4:
21311         case DW_OP_lit5:
21312         case DW_OP_lit6:
21313         case DW_OP_lit7:
21314         case DW_OP_lit8:
21315         case DW_OP_lit9:
21316         case DW_OP_lit10:
21317         case DW_OP_lit11:
21318         case DW_OP_lit12:
21319         case DW_OP_lit13:
21320         case DW_OP_lit14:
21321         case DW_OP_lit15:
21322         case DW_OP_lit16:
21323         case DW_OP_lit17:
21324         case DW_OP_lit18:
21325         case DW_OP_lit19:
21326         case DW_OP_lit20:
21327         case DW_OP_lit21:
21328         case DW_OP_lit22:
21329         case DW_OP_lit23:
21330         case DW_OP_lit24:
21331         case DW_OP_lit25:
21332         case DW_OP_lit26:
21333         case DW_OP_lit27:
21334         case DW_OP_lit28:
21335         case DW_OP_lit29:
21336         case DW_OP_lit30:
21337         case DW_OP_lit31:
21338           stack[++stacki] = op - DW_OP_lit0;
21339           break;
21340
21341         case DW_OP_reg0:
21342         case DW_OP_reg1:
21343         case DW_OP_reg2:
21344         case DW_OP_reg3:
21345         case DW_OP_reg4:
21346         case DW_OP_reg5:
21347         case DW_OP_reg6:
21348         case DW_OP_reg7:
21349         case DW_OP_reg8:
21350         case DW_OP_reg9:
21351         case DW_OP_reg10:
21352         case DW_OP_reg11:
21353         case DW_OP_reg12:
21354         case DW_OP_reg13:
21355         case DW_OP_reg14:
21356         case DW_OP_reg15:
21357         case DW_OP_reg16:
21358         case DW_OP_reg17:
21359         case DW_OP_reg18:
21360         case DW_OP_reg19:
21361         case DW_OP_reg20:
21362         case DW_OP_reg21:
21363         case DW_OP_reg22:
21364         case DW_OP_reg23:
21365         case DW_OP_reg24:
21366         case DW_OP_reg25:
21367         case DW_OP_reg26:
21368         case DW_OP_reg27:
21369         case DW_OP_reg28:
21370         case DW_OP_reg29:
21371         case DW_OP_reg30:
21372         case DW_OP_reg31:
21373           stack[++stacki] = op - DW_OP_reg0;
21374           if (i < size)
21375             dwarf2_complex_location_expr_complaint ();
21376           break;
21377
21378         case DW_OP_regx:
21379           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21380           i += bytes_read;
21381           stack[++stacki] = unsnd;
21382           if (i < size)
21383             dwarf2_complex_location_expr_complaint ();
21384           break;
21385
21386         case DW_OP_addr:
21387           stack[++stacki] = read_address (objfile->obfd, &data[i],
21388                                           cu, &bytes_read);
21389           i += bytes_read;
21390           break;
21391
21392         case DW_OP_const1u:
21393           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21394           i += 1;
21395           break;
21396
21397         case DW_OP_const1s:
21398           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21399           i += 1;
21400           break;
21401
21402         case DW_OP_const2u:
21403           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21404           i += 2;
21405           break;
21406
21407         case DW_OP_const2s:
21408           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21409           i += 2;
21410           break;
21411
21412         case DW_OP_const4u:
21413           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21414           i += 4;
21415           break;
21416
21417         case DW_OP_const4s:
21418           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21419           i += 4;
21420           break;
21421
21422         case DW_OP_const8u:
21423           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21424           i += 8;
21425           break;
21426
21427         case DW_OP_constu:
21428           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21429                                                   &bytes_read);
21430           i += bytes_read;
21431           break;
21432
21433         case DW_OP_consts:
21434           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21435           i += bytes_read;
21436           break;
21437
21438         case DW_OP_dup:
21439           stack[stacki + 1] = stack[stacki];
21440           stacki++;
21441           break;
21442
21443         case DW_OP_plus:
21444           stack[stacki - 1] += stack[stacki];
21445           stacki--;
21446           break;
21447
21448         case DW_OP_plus_uconst:
21449           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21450                                                  &bytes_read);
21451           i += bytes_read;
21452           break;
21453
21454         case DW_OP_minus:
21455           stack[stacki - 1] -= stack[stacki];
21456           stacki--;
21457           break;
21458
21459         case DW_OP_deref:
21460           /* If we're not the last op, then we definitely can't encode
21461              this using GDB's address_class enum.  This is valid for partial
21462              global symbols, although the variable's address will be bogus
21463              in the psymtab.  */
21464           if (i < size)
21465             dwarf2_complex_location_expr_complaint ();
21466           break;
21467
21468         case DW_OP_GNU_push_tls_address:
21469         case DW_OP_form_tls_address:
21470           /* The top of the stack has the offset from the beginning
21471              of the thread control block at which the variable is located.  */
21472           /* Nothing should follow this operator, so the top of stack would
21473              be returned.  */
21474           /* This is valid for partial global symbols, but the variable's
21475              address will be bogus in the psymtab.  Make it always at least
21476              non-zero to not look as a variable garbage collected by linker
21477              which have DW_OP_addr 0.  */
21478           if (i < size)
21479             dwarf2_complex_location_expr_complaint ();
21480           stack[stacki]++;
21481           break;
21482
21483         case DW_OP_GNU_uninit:
21484           break;
21485
21486         case DW_OP_GNU_addr_index:
21487         case DW_OP_GNU_const_index:
21488           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21489                                                          &bytes_read);
21490           i += bytes_read;
21491           break;
21492
21493         default:
21494           {
21495             const char *name = get_DW_OP_name (op);
21496
21497             if (name)
21498               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21499                          name);
21500             else
21501               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21502                          op);
21503           }
21504
21505           return (stack[stacki]);
21506         }
21507
21508       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21509          outside of the allocated space.  Also enforce minimum>0.  */
21510       if (stacki >= ARRAY_SIZE (stack) - 1)
21511         {
21512           complaint (&symfile_complaints,
21513                      _("location description stack overflow"));
21514           return 0;
21515         }
21516
21517       if (stacki <= 0)
21518         {
21519           complaint (&symfile_complaints,
21520                      _("location description stack underflow"));
21521           return 0;
21522         }
21523     }
21524   return (stack[stacki]);
21525 }
21526
21527 /* memory allocation interface */
21528
21529 static struct dwarf_block *
21530 dwarf_alloc_block (struct dwarf2_cu *cu)
21531 {
21532   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21533 }
21534
21535 static struct die_info *
21536 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21537 {
21538   struct die_info *die;
21539   size_t size = sizeof (struct die_info);
21540
21541   if (num_attrs > 1)
21542     size += (num_attrs - 1) * sizeof (struct attribute);
21543
21544   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21545   memset (die, 0, sizeof (struct die_info));
21546   return (die);
21547 }
21548
21549 \f
21550 /* Macro support.  */
21551
21552 /* Return file name relative to the compilation directory of file number I in
21553    *LH's file name table.  The result is allocated using xmalloc; the caller is
21554    responsible for freeing it.  */
21555
21556 static char *
21557 file_file_name (int file, struct line_header *lh)
21558 {
21559   /* Is the file number a valid index into the line header's file name
21560      table?  Remember that file numbers start with one, not zero.  */
21561   if (1 <= file && file <= lh->file_names.size ())
21562     {
21563       const file_entry &fe = lh->file_names[file - 1];
21564
21565       if (!IS_ABSOLUTE_PATH (fe.name))
21566         {
21567           const char *dir = fe.include_dir (lh);
21568           if (dir != NULL)
21569             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21570         }
21571       return xstrdup (fe.name);
21572     }
21573   else
21574     {
21575       /* The compiler produced a bogus file number.  We can at least
21576          record the macro definitions made in the file, even if we
21577          won't be able to find the file by name.  */
21578       char fake_name[80];
21579
21580       xsnprintf (fake_name, sizeof (fake_name),
21581                  "<bad macro file number %d>", file);
21582
21583       complaint (&symfile_complaints,
21584                  _("bad file number in macro information (%d)"),
21585                  file);
21586
21587       return xstrdup (fake_name);
21588     }
21589 }
21590
21591 /* Return the full name of file number I in *LH's file name table.
21592    Use COMP_DIR as the name of the current directory of the
21593    compilation.  The result is allocated using xmalloc; the caller is
21594    responsible for freeing it.  */
21595 static char *
21596 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21597 {
21598   /* Is the file number a valid index into the line header's file name
21599      table?  Remember that file numbers start with one, not zero.  */
21600   if (1 <= file && file <= lh->file_names.size ())
21601     {
21602       char *relative = file_file_name (file, lh);
21603
21604       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21605         return relative;
21606       return reconcat (relative, comp_dir, SLASH_STRING,
21607                        relative, (char *) NULL);
21608     }
21609   else
21610     return file_file_name (file, lh);
21611 }
21612
21613
21614 static struct macro_source_file *
21615 macro_start_file (int file, int line,
21616                   struct macro_source_file *current_file,
21617                   struct line_header *lh)
21618 {
21619   /* File name relative to the compilation directory of this source file.  */
21620   char *file_name = file_file_name (file, lh);
21621
21622   if (! current_file)
21623     {
21624       /* Note: We don't create a macro table for this compilation unit
21625          at all until we actually get a filename.  */
21626       struct macro_table *macro_table = get_macro_table ();
21627
21628       /* If we have no current file, then this must be the start_file
21629          directive for the compilation unit's main source file.  */
21630       current_file = macro_set_main (macro_table, file_name);
21631       macro_define_special (macro_table);
21632     }
21633   else
21634     current_file = macro_include (current_file, line, file_name);
21635
21636   xfree (file_name);
21637
21638   return current_file;
21639 }
21640
21641 static const char *
21642 consume_improper_spaces (const char *p, const char *body)
21643 {
21644   if (*p == ' ')
21645     {
21646       complaint (&symfile_complaints,
21647                  _("macro definition contains spaces "
21648                    "in formal argument list:\n`%s'"),
21649                  body);
21650
21651       while (*p == ' ')
21652         p++;
21653     }
21654
21655   return p;
21656 }
21657
21658
21659 static void
21660 parse_macro_definition (struct macro_source_file *file, int line,
21661                         const char *body)
21662 {
21663   const char *p;
21664
21665   /* The body string takes one of two forms.  For object-like macro
21666      definitions, it should be:
21667
21668         <macro name> " " <definition>
21669
21670      For function-like macro definitions, it should be:
21671
21672         <macro name> "() " <definition>
21673      or
21674         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21675
21676      Spaces may appear only where explicitly indicated, and in the
21677      <definition>.
21678
21679      The Dwarf 2 spec says that an object-like macro's name is always
21680      followed by a space, but versions of GCC around March 2002 omit
21681      the space when the macro's definition is the empty string.
21682
21683      The Dwarf 2 spec says that there should be no spaces between the
21684      formal arguments in a function-like macro's formal argument list,
21685      but versions of GCC around March 2002 include spaces after the
21686      commas.  */
21687
21688
21689   /* Find the extent of the macro name.  The macro name is terminated
21690      by either a space or null character (for an object-like macro) or
21691      an opening paren (for a function-like macro).  */
21692   for (p = body; *p; p++)
21693     if (*p == ' ' || *p == '(')
21694       break;
21695
21696   if (*p == ' ' || *p == '\0')
21697     {
21698       /* It's an object-like macro.  */
21699       int name_len = p - body;
21700       char *name = savestring (body, name_len);
21701       const char *replacement;
21702
21703       if (*p == ' ')
21704         replacement = body + name_len + 1;
21705       else
21706         {
21707           dwarf2_macro_malformed_definition_complaint (body);
21708           replacement = body + name_len;
21709         }
21710
21711       macro_define_object (file, line, name, replacement);
21712
21713       xfree (name);
21714     }
21715   else if (*p == '(')
21716     {
21717       /* It's a function-like macro.  */
21718       char *name = savestring (body, p - body);
21719       int argc = 0;
21720       int argv_size = 1;
21721       char **argv = XNEWVEC (char *, argv_size);
21722
21723       p++;
21724
21725       p = consume_improper_spaces (p, body);
21726
21727       /* Parse the formal argument list.  */
21728       while (*p && *p != ')')
21729         {
21730           /* Find the extent of the current argument name.  */
21731           const char *arg_start = p;
21732
21733           while (*p && *p != ',' && *p != ')' && *p != ' ')
21734             p++;
21735
21736           if (! *p || p == arg_start)
21737             dwarf2_macro_malformed_definition_complaint (body);
21738           else
21739             {
21740               /* Make sure argv has room for the new argument.  */
21741               if (argc >= argv_size)
21742                 {
21743                   argv_size *= 2;
21744                   argv = XRESIZEVEC (char *, argv, argv_size);
21745                 }
21746
21747               argv[argc++] = savestring (arg_start, p - arg_start);
21748             }
21749
21750           p = consume_improper_spaces (p, body);
21751
21752           /* Consume the comma, if present.  */
21753           if (*p == ',')
21754             {
21755               p++;
21756
21757               p = consume_improper_spaces (p, body);
21758             }
21759         }
21760
21761       if (*p == ')')
21762         {
21763           p++;
21764
21765           if (*p == ' ')
21766             /* Perfectly formed definition, no complaints.  */
21767             macro_define_function (file, line, name,
21768                                    argc, (const char **) argv,
21769                                    p + 1);
21770           else if (*p == '\0')
21771             {
21772               /* Complain, but do define it.  */
21773               dwarf2_macro_malformed_definition_complaint (body);
21774               macro_define_function (file, line, name,
21775                                      argc, (const char **) argv,
21776                                      p);
21777             }
21778           else
21779             /* Just complain.  */
21780             dwarf2_macro_malformed_definition_complaint (body);
21781         }
21782       else
21783         /* Just complain.  */
21784         dwarf2_macro_malformed_definition_complaint (body);
21785
21786       xfree (name);
21787       {
21788         int i;
21789
21790         for (i = 0; i < argc; i++)
21791           xfree (argv[i]);
21792       }
21793       xfree (argv);
21794     }
21795   else
21796     dwarf2_macro_malformed_definition_complaint (body);
21797 }
21798
21799 /* Skip some bytes from BYTES according to the form given in FORM.
21800    Returns the new pointer.  */
21801
21802 static const gdb_byte *
21803 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21804                  enum dwarf_form form,
21805                  unsigned int offset_size,
21806                  struct dwarf2_section_info *section)
21807 {
21808   unsigned int bytes_read;
21809
21810   switch (form)
21811     {
21812     case DW_FORM_data1:
21813     case DW_FORM_flag:
21814       ++bytes;
21815       break;
21816
21817     case DW_FORM_data2:
21818       bytes += 2;
21819       break;
21820
21821     case DW_FORM_data4:
21822       bytes += 4;
21823       break;
21824
21825     case DW_FORM_data8:
21826       bytes += 8;
21827       break;
21828
21829     case DW_FORM_data16:
21830       bytes += 16;
21831       break;
21832
21833     case DW_FORM_string:
21834       read_direct_string (abfd, bytes, &bytes_read);
21835       bytes += bytes_read;
21836       break;
21837
21838     case DW_FORM_sec_offset:
21839     case DW_FORM_strp:
21840     case DW_FORM_GNU_strp_alt:
21841       bytes += offset_size;
21842       break;
21843
21844     case DW_FORM_block:
21845       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21846       bytes += bytes_read;
21847       break;
21848
21849     case DW_FORM_block1:
21850       bytes += 1 + read_1_byte (abfd, bytes);
21851       break;
21852     case DW_FORM_block2:
21853       bytes += 2 + read_2_bytes (abfd, bytes);
21854       break;
21855     case DW_FORM_block4:
21856       bytes += 4 + read_4_bytes (abfd, bytes);
21857       break;
21858
21859     case DW_FORM_sdata:
21860     case DW_FORM_udata:
21861     case DW_FORM_GNU_addr_index:
21862     case DW_FORM_GNU_str_index:
21863       bytes = gdb_skip_leb128 (bytes, buffer_end);
21864       if (bytes == NULL)
21865         {
21866           dwarf2_section_buffer_overflow_complaint (section);
21867           return NULL;
21868         }
21869       break;
21870
21871     case DW_FORM_implicit_const:
21872       break;
21873
21874     default:
21875       {
21876       complain:
21877         complaint (&symfile_complaints,
21878                    _("invalid form 0x%x in `%s'"),
21879                    form, get_section_name (section));
21880         return NULL;
21881       }
21882     }
21883
21884   return bytes;
21885 }
21886
21887 /* A helper for dwarf_decode_macros that handles skipping an unknown
21888    opcode.  Returns an updated pointer to the macro data buffer; or,
21889    on error, issues a complaint and returns NULL.  */
21890
21891 static const gdb_byte *
21892 skip_unknown_opcode (unsigned int opcode,
21893                      const gdb_byte **opcode_definitions,
21894                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21895                      bfd *abfd,
21896                      unsigned int offset_size,
21897                      struct dwarf2_section_info *section)
21898 {
21899   unsigned int bytes_read, i;
21900   unsigned long arg;
21901   const gdb_byte *defn;
21902
21903   if (opcode_definitions[opcode] == NULL)
21904     {
21905       complaint (&symfile_complaints,
21906                  _("unrecognized DW_MACFINO opcode 0x%x"),
21907                  opcode);
21908       return NULL;
21909     }
21910
21911   defn = opcode_definitions[opcode];
21912   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21913   defn += bytes_read;
21914
21915   for (i = 0; i < arg; ++i)
21916     {
21917       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21918                                  (enum dwarf_form) defn[i], offset_size,
21919                                  section);
21920       if (mac_ptr == NULL)
21921         {
21922           /* skip_form_bytes already issued the complaint.  */
21923           return NULL;
21924         }
21925     }
21926
21927   return mac_ptr;
21928 }
21929
21930 /* A helper function which parses the header of a macro section.
21931    If the macro section is the extended (for now called "GNU") type,
21932    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21933    the header, or issues a complaint and returns NULL on error.  */
21934
21935 static const gdb_byte *
21936 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21937                           bfd *abfd,
21938                           const gdb_byte *mac_ptr,
21939                           unsigned int *offset_size,
21940                           int section_is_gnu)
21941 {
21942   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21943
21944   if (section_is_gnu)
21945     {
21946       unsigned int version, flags;
21947
21948       version = read_2_bytes (abfd, mac_ptr);
21949       if (version != 4 && version != 5)
21950         {
21951           complaint (&symfile_complaints,
21952                      _("unrecognized version `%d' in .debug_macro section"),
21953                      version);
21954           return NULL;
21955         }
21956       mac_ptr += 2;
21957
21958       flags = read_1_byte (abfd, mac_ptr);
21959       ++mac_ptr;
21960       *offset_size = (flags & 1) ? 8 : 4;
21961
21962       if ((flags & 2) != 0)
21963         /* We don't need the line table offset.  */
21964         mac_ptr += *offset_size;
21965
21966       /* Vendor opcode descriptions.  */
21967       if ((flags & 4) != 0)
21968         {
21969           unsigned int i, count;
21970
21971           count = read_1_byte (abfd, mac_ptr);
21972           ++mac_ptr;
21973           for (i = 0; i < count; ++i)
21974             {
21975               unsigned int opcode, bytes_read;
21976               unsigned long arg;
21977
21978               opcode = read_1_byte (abfd, mac_ptr);
21979               ++mac_ptr;
21980               opcode_definitions[opcode] = mac_ptr;
21981               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21982               mac_ptr += bytes_read;
21983               mac_ptr += arg;
21984             }
21985         }
21986     }
21987
21988   return mac_ptr;
21989 }
21990
21991 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21992    including DW_MACRO_import.  */
21993
21994 static void
21995 dwarf_decode_macro_bytes (bfd *abfd,
21996                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21997                           struct macro_source_file *current_file,
21998                           struct line_header *lh,
21999                           struct dwarf2_section_info *section,
22000                           int section_is_gnu, int section_is_dwz,
22001                           unsigned int offset_size,
22002                           htab_t include_hash)
22003 {
22004   struct objfile *objfile = dwarf2_per_objfile->objfile;
22005   enum dwarf_macro_record_type macinfo_type;
22006   int at_commandline;
22007   const gdb_byte *opcode_definitions[256];
22008
22009   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22010                                       &offset_size, section_is_gnu);
22011   if (mac_ptr == NULL)
22012     {
22013       /* We already issued a complaint.  */
22014       return;
22015     }
22016
22017   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22018      GDB is still reading the definitions from command line.  First
22019      DW_MACINFO_start_file will need to be ignored as it was already executed
22020      to create CURRENT_FILE for the main source holding also the command line
22021      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22022      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22023
22024   at_commandline = 1;
22025
22026   do
22027     {
22028       /* Do we at least have room for a macinfo type byte?  */
22029       if (mac_ptr >= mac_end)
22030         {
22031           dwarf2_section_buffer_overflow_complaint (section);
22032           break;
22033         }
22034
22035       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22036       mac_ptr++;
22037
22038       /* Note that we rely on the fact that the corresponding GNU and
22039          DWARF constants are the same.  */
22040       switch (macinfo_type)
22041         {
22042           /* A zero macinfo type indicates the end of the macro
22043              information.  */
22044         case 0:
22045           break;
22046
22047         case DW_MACRO_define:
22048         case DW_MACRO_undef:
22049         case DW_MACRO_define_strp:
22050         case DW_MACRO_undef_strp:
22051         case DW_MACRO_define_sup:
22052         case DW_MACRO_undef_sup:
22053           {
22054             unsigned int bytes_read;
22055             int line;
22056             const char *body;
22057             int is_define;
22058
22059             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22060             mac_ptr += bytes_read;
22061
22062             if (macinfo_type == DW_MACRO_define
22063                 || macinfo_type == DW_MACRO_undef)
22064               {
22065                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22066                 mac_ptr += bytes_read;
22067               }
22068             else
22069               {
22070                 LONGEST str_offset;
22071
22072                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22073                 mac_ptr += offset_size;
22074
22075                 if (macinfo_type == DW_MACRO_define_sup
22076                     || macinfo_type == DW_MACRO_undef_sup
22077                     || section_is_dwz)
22078                   {
22079                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22080
22081                     body = read_indirect_string_from_dwz (dwz, str_offset);
22082                   }
22083                 else
22084                   body = read_indirect_string_at_offset (abfd, str_offset);
22085               }
22086
22087             is_define = (macinfo_type == DW_MACRO_define
22088                          || macinfo_type == DW_MACRO_define_strp
22089                          || macinfo_type == DW_MACRO_define_sup);
22090             if (! current_file)
22091               {
22092                 /* DWARF violation as no main source is present.  */
22093                 complaint (&symfile_complaints,
22094                            _("debug info with no main source gives macro %s "
22095                              "on line %d: %s"),
22096                            is_define ? _("definition") : _("undefinition"),
22097                            line, body);
22098                 break;
22099               }
22100             if ((line == 0 && !at_commandline)
22101                 || (line != 0 && at_commandline))
22102               complaint (&symfile_complaints,
22103                          _("debug info gives %s macro %s with %s line %d: %s"),
22104                          at_commandline ? _("command-line") : _("in-file"),
22105                          is_define ? _("definition") : _("undefinition"),
22106                          line == 0 ? _("zero") : _("non-zero"), line, body);
22107
22108             if (is_define)
22109               parse_macro_definition (current_file, line, body);
22110             else
22111               {
22112                 gdb_assert (macinfo_type == DW_MACRO_undef
22113                             || macinfo_type == DW_MACRO_undef_strp
22114                             || macinfo_type == DW_MACRO_undef_sup);
22115                 macro_undef (current_file, line, body);
22116               }
22117           }
22118           break;
22119
22120         case DW_MACRO_start_file:
22121           {
22122             unsigned int bytes_read;
22123             int line, file;
22124
22125             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22126             mac_ptr += bytes_read;
22127             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22128             mac_ptr += bytes_read;
22129
22130             if ((line == 0 && !at_commandline)
22131                 || (line != 0 && at_commandline))
22132               complaint (&symfile_complaints,
22133                          _("debug info gives source %d included "
22134                            "from %s at %s line %d"),
22135                          file, at_commandline ? _("command-line") : _("file"),
22136                          line == 0 ? _("zero") : _("non-zero"), line);
22137
22138             if (at_commandline)
22139               {
22140                 /* This DW_MACRO_start_file was executed in the
22141                    pass one.  */
22142                 at_commandline = 0;
22143               }
22144             else
22145               current_file = macro_start_file (file, line, current_file, lh);
22146           }
22147           break;
22148
22149         case DW_MACRO_end_file:
22150           if (! current_file)
22151             complaint (&symfile_complaints,
22152                        _("macro debug info has an unmatched "
22153                          "`close_file' directive"));
22154           else
22155             {
22156               current_file = current_file->included_by;
22157               if (! current_file)
22158                 {
22159                   enum dwarf_macro_record_type next_type;
22160
22161                   /* GCC circa March 2002 doesn't produce the zero
22162                      type byte marking the end of the compilation
22163                      unit.  Complain if it's not there, but exit no
22164                      matter what.  */
22165
22166                   /* Do we at least have room for a macinfo type byte?  */
22167                   if (mac_ptr >= mac_end)
22168                     {
22169                       dwarf2_section_buffer_overflow_complaint (section);
22170                       return;
22171                     }
22172
22173                   /* We don't increment mac_ptr here, so this is just
22174                      a look-ahead.  */
22175                   next_type
22176                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22177                                                                   mac_ptr);
22178                   if (next_type != 0)
22179                     complaint (&symfile_complaints,
22180                                _("no terminating 0-type entry for "
22181                                  "macros in `.debug_macinfo' section"));
22182
22183                   return;
22184                 }
22185             }
22186           break;
22187
22188         case DW_MACRO_import:
22189         case DW_MACRO_import_sup:
22190           {
22191             LONGEST offset;
22192             void **slot;
22193             bfd *include_bfd = abfd;
22194             struct dwarf2_section_info *include_section = section;
22195             const gdb_byte *include_mac_end = mac_end;
22196             int is_dwz = section_is_dwz;
22197             const gdb_byte *new_mac_ptr;
22198
22199             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22200             mac_ptr += offset_size;
22201
22202             if (macinfo_type == DW_MACRO_import_sup)
22203               {
22204                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22205
22206                 dwarf2_read_section (objfile, &dwz->macro);
22207
22208                 include_section = &dwz->macro;
22209                 include_bfd = get_section_bfd_owner (include_section);
22210                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22211                 is_dwz = 1;
22212               }
22213
22214             new_mac_ptr = include_section->buffer + offset;
22215             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22216
22217             if (*slot != NULL)
22218               {
22219                 /* This has actually happened; see
22220                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22221                 complaint (&symfile_complaints,
22222                            _("recursive DW_MACRO_import in "
22223                              ".debug_macro section"));
22224               }
22225             else
22226               {
22227                 *slot = (void *) new_mac_ptr;
22228
22229                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22230                                           include_mac_end, current_file, lh,
22231                                           section, section_is_gnu, is_dwz,
22232                                           offset_size, include_hash);
22233
22234                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22235               }
22236           }
22237           break;
22238
22239         case DW_MACINFO_vendor_ext:
22240           if (!section_is_gnu)
22241             {
22242               unsigned int bytes_read;
22243
22244               /* This reads the constant, but since we don't recognize
22245                  any vendor extensions, we ignore it.  */
22246               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22247               mac_ptr += bytes_read;
22248               read_direct_string (abfd, mac_ptr, &bytes_read);
22249               mac_ptr += bytes_read;
22250
22251               /* We don't recognize any vendor extensions.  */
22252               break;
22253             }
22254           /* FALLTHROUGH */
22255
22256         default:
22257           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22258                                          mac_ptr, mac_end, abfd, offset_size,
22259                                          section);
22260           if (mac_ptr == NULL)
22261             return;
22262           break;
22263         }
22264     } while (macinfo_type != 0);
22265 }
22266
22267 static void
22268 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22269                      int section_is_gnu)
22270 {
22271   struct objfile *objfile = dwarf2_per_objfile->objfile;
22272   struct line_header *lh = cu->line_header;
22273   bfd *abfd;
22274   const gdb_byte *mac_ptr, *mac_end;
22275   struct macro_source_file *current_file = 0;
22276   enum dwarf_macro_record_type macinfo_type;
22277   unsigned int offset_size = cu->header.offset_size;
22278   const gdb_byte *opcode_definitions[256];
22279   void **slot;
22280   struct dwarf2_section_info *section;
22281   const char *section_name;
22282
22283   if (cu->dwo_unit != NULL)
22284     {
22285       if (section_is_gnu)
22286         {
22287           section = &cu->dwo_unit->dwo_file->sections.macro;
22288           section_name = ".debug_macro.dwo";
22289         }
22290       else
22291         {
22292           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22293           section_name = ".debug_macinfo.dwo";
22294         }
22295     }
22296   else
22297     {
22298       if (section_is_gnu)
22299         {
22300           section = &dwarf2_per_objfile->macro;
22301           section_name = ".debug_macro";
22302         }
22303       else
22304         {
22305           section = &dwarf2_per_objfile->macinfo;
22306           section_name = ".debug_macinfo";
22307         }
22308     }
22309
22310   dwarf2_read_section (objfile, section);
22311   if (section->buffer == NULL)
22312     {
22313       complaint (&symfile_complaints, _("missing %s section"), section_name);
22314       return;
22315     }
22316   abfd = get_section_bfd_owner (section);
22317
22318   /* First pass: Find the name of the base filename.
22319      This filename is needed in order to process all macros whose definition
22320      (or undefinition) comes from the command line.  These macros are defined
22321      before the first DW_MACINFO_start_file entry, and yet still need to be
22322      associated to the base file.
22323
22324      To determine the base file name, we scan the macro definitions until we
22325      reach the first DW_MACINFO_start_file entry.  We then initialize
22326      CURRENT_FILE accordingly so that any macro definition found before the
22327      first DW_MACINFO_start_file can still be associated to the base file.  */
22328
22329   mac_ptr = section->buffer + offset;
22330   mac_end = section->buffer + section->size;
22331
22332   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22333                                       &offset_size, section_is_gnu);
22334   if (mac_ptr == NULL)
22335     {
22336       /* We already issued a complaint.  */
22337       return;
22338     }
22339
22340   do
22341     {
22342       /* Do we at least have room for a macinfo type byte?  */
22343       if (mac_ptr >= mac_end)
22344         {
22345           /* Complaint is printed during the second pass as GDB will probably
22346              stop the first pass earlier upon finding
22347              DW_MACINFO_start_file.  */
22348           break;
22349         }
22350
22351       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22352       mac_ptr++;
22353
22354       /* Note that we rely on the fact that the corresponding GNU and
22355          DWARF constants are the same.  */
22356       switch (macinfo_type)
22357         {
22358           /* A zero macinfo type indicates the end of the macro
22359              information.  */
22360         case 0:
22361           break;
22362
22363         case DW_MACRO_define:
22364         case DW_MACRO_undef:
22365           /* Only skip the data by MAC_PTR.  */
22366           {
22367             unsigned int bytes_read;
22368
22369             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22370             mac_ptr += bytes_read;
22371             read_direct_string (abfd, mac_ptr, &bytes_read);
22372             mac_ptr += bytes_read;
22373           }
22374           break;
22375
22376         case DW_MACRO_start_file:
22377           {
22378             unsigned int bytes_read;
22379             int line, file;
22380
22381             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22382             mac_ptr += bytes_read;
22383             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22384             mac_ptr += bytes_read;
22385
22386             current_file = macro_start_file (file, line, current_file, lh);
22387           }
22388           break;
22389
22390         case DW_MACRO_end_file:
22391           /* No data to skip by MAC_PTR.  */
22392           break;
22393
22394         case DW_MACRO_define_strp:
22395         case DW_MACRO_undef_strp:
22396         case DW_MACRO_define_sup:
22397         case DW_MACRO_undef_sup:
22398           {
22399             unsigned int bytes_read;
22400
22401             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22402             mac_ptr += bytes_read;
22403             mac_ptr += offset_size;
22404           }
22405           break;
22406
22407         case DW_MACRO_import:
22408         case DW_MACRO_import_sup:
22409           /* Note that, according to the spec, a transparent include
22410              chain cannot call DW_MACRO_start_file.  So, we can just
22411              skip this opcode.  */
22412           mac_ptr += offset_size;
22413           break;
22414
22415         case DW_MACINFO_vendor_ext:
22416           /* Only skip the data by MAC_PTR.  */
22417           if (!section_is_gnu)
22418             {
22419               unsigned int bytes_read;
22420
22421               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22422               mac_ptr += bytes_read;
22423               read_direct_string (abfd, mac_ptr, &bytes_read);
22424               mac_ptr += bytes_read;
22425             }
22426           /* FALLTHROUGH */
22427
22428         default:
22429           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22430                                          mac_ptr, mac_end, abfd, offset_size,
22431                                          section);
22432           if (mac_ptr == NULL)
22433             return;
22434           break;
22435         }
22436     } while (macinfo_type != 0 && current_file == NULL);
22437
22438   /* Second pass: Process all entries.
22439
22440      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22441      command-line macro definitions/undefinitions.  This flag is unset when we
22442      reach the first DW_MACINFO_start_file entry.  */
22443
22444   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22445                                            htab_eq_pointer,
22446                                            NULL, xcalloc, xfree));
22447   mac_ptr = section->buffer + offset;
22448   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22449   *slot = (void *) mac_ptr;
22450   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22451                             current_file, lh, section,
22452                             section_is_gnu, 0, offset_size,
22453                             include_hash.get ());
22454 }
22455
22456 /* Check if the attribute's form is a DW_FORM_block*
22457    if so return true else false.  */
22458
22459 static int
22460 attr_form_is_block (const struct attribute *attr)
22461 {
22462   return (attr == NULL ? 0 :
22463       attr->form == DW_FORM_block1
22464       || attr->form == DW_FORM_block2
22465       || attr->form == DW_FORM_block4
22466       || attr->form == DW_FORM_block
22467       || attr->form == DW_FORM_exprloc);
22468 }
22469
22470 /* Return non-zero if ATTR's value is a section offset --- classes
22471    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22472    You may use DW_UNSND (attr) to retrieve such offsets.
22473
22474    Section 7.5.4, "Attribute Encodings", explains that no attribute
22475    may have a value that belongs to more than one of these classes; it
22476    would be ambiguous if we did, because we use the same forms for all
22477    of them.  */
22478
22479 static int
22480 attr_form_is_section_offset (const struct attribute *attr)
22481 {
22482   return (attr->form == DW_FORM_data4
22483           || attr->form == DW_FORM_data8
22484           || attr->form == DW_FORM_sec_offset);
22485 }
22486
22487 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22488    zero otherwise.  When this function returns true, you can apply
22489    dwarf2_get_attr_constant_value to it.
22490
22491    However, note that for some attributes you must check
22492    attr_form_is_section_offset before using this test.  DW_FORM_data4
22493    and DW_FORM_data8 are members of both the constant class, and of
22494    the classes that contain offsets into other debug sections
22495    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22496    that, if an attribute's can be either a constant or one of the
22497    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22498    taken as section offsets, not constants.
22499
22500    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22501    cannot handle that.  */
22502
22503 static int
22504 attr_form_is_constant (const struct attribute *attr)
22505 {
22506   switch (attr->form)
22507     {
22508     case DW_FORM_sdata:
22509     case DW_FORM_udata:
22510     case DW_FORM_data1:
22511     case DW_FORM_data2:
22512     case DW_FORM_data4:
22513     case DW_FORM_data8:
22514     case DW_FORM_implicit_const:
22515       return 1;
22516     default:
22517       return 0;
22518     }
22519 }
22520
22521
22522 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22523    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22524
22525 static int
22526 attr_form_is_ref (const struct attribute *attr)
22527 {
22528   switch (attr->form)
22529     {
22530     case DW_FORM_ref_addr:
22531     case DW_FORM_ref1:
22532     case DW_FORM_ref2:
22533     case DW_FORM_ref4:
22534     case DW_FORM_ref8:
22535     case DW_FORM_ref_udata:
22536     case DW_FORM_GNU_ref_alt:
22537       return 1;
22538     default:
22539       return 0;
22540     }
22541 }
22542
22543 /* Return the .debug_loc section to use for CU.
22544    For DWO files use .debug_loc.dwo.  */
22545
22546 static struct dwarf2_section_info *
22547 cu_debug_loc_section (struct dwarf2_cu *cu)
22548 {
22549   if (cu->dwo_unit)
22550     {
22551       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22552       
22553       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22554     }
22555   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22556                                   : &dwarf2_per_objfile->loc);
22557 }
22558
22559 /* A helper function that fills in a dwarf2_loclist_baton.  */
22560
22561 static void
22562 fill_in_loclist_baton (struct dwarf2_cu *cu,
22563                        struct dwarf2_loclist_baton *baton,
22564                        const struct attribute *attr)
22565 {
22566   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22567
22568   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22569
22570   baton->per_cu = cu->per_cu;
22571   gdb_assert (baton->per_cu);
22572   /* We don't know how long the location list is, but make sure we
22573      don't run off the edge of the section.  */
22574   baton->size = section->size - DW_UNSND (attr);
22575   baton->data = section->buffer + DW_UNSND (attr);
22576   baton->base_address = cu->base_address;
22577   baton->from_dwo = cu->dwo_unit != NULL;
22578 }
22579
22580 static void
22581 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22582                              struct dwarf2_cu *cu, int is_block)
22583 {
22584   struct objfile *objfile = dwarf2_per_objfile->objfile;
22585   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22586
22587   if (attr_form_is_section_offset (attr)
22588       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22589          the section.  If so, fall through to the complaint in the
22590          other branch.  */
22591       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22592     {
22593       struct dwarf2_loclist_baton *baton;
22594
22595       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22596
22597       fill_in_loclist_baton (cu, baton, attr);
22598
22599       if (cu->base_known == 0)
22600         complaint (&symfile_complaints,
22601                    _("Location list used without "
22602                      "specifying the CU base address."));
22603
22604       SYMBOL_ACLASS_INDEX (sym) = (is_block
22605                                    ? dwarf2_loclist_block_index
22606                                    : dwarf2_loclist_index);
22607       SYMBOL_LOCATION_BATON (sym) = baton;
22608     }
22609   else
22610     {
22611       struct dwarf2_locexpr_baton *baton;
22612
22613       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22614       baton->per_cu = cu->per_cu;
22615       gdb_assert (baton->per_cu);
22616
22617       if (attr_form_is_block (attr))
22618         {
22619           /* Note that we're just copying the block's data pointer
22620              here, not the actual data.  We're still pointing into the
22621              info_buffer for SYM's objfile; right now we never release
22622              that buffer, but when we do clean up properly this may
22623              need to change.  */
22624           baton->size = DW_BLOCK (attr)->size;
22625           baton->data = DW_BLOCK (attr)->data;
22626         }
22627       else
22628         {
22629           dwarf2_invalid_attrib_class_complaint ("location description",
22630                                                  SYMBOL_NATURAL_NAME (sym));
22631           baton->size = 0;
22632         }
22633
22634       SYMBOL_ACLASS_INDEX (sym) = (is_block
22635                                    ? dwarf2_locexpr_block_index
22636                                    : dwarf2_locexpr_index);
22637       SYMBOL_LOCATION_BATON (sym) = baton;
22638     }
22639 }
22640
22641 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22642    came from a separate debuginfo file, then the master objfile is
22643    returned.  */
22644
22645 struct objfile *
22646 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22647 {
22648   struct objfile *objfile = per_cu->objfile;
22649
22650   /* Return the master objfile, so that we can report and look up the
22651      correct file containing this variable.  */
22652   if (objfile->separate_debug_objfile_backlink)
22653     objfile = objfile->separate_debug_objfile_backlink;
22654
22655   return objfile;
22656 }
22657
22658 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22659    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22660    CU_HEADERP first.  */
22661
22662 static const struct comp_unit_head *
22663 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22664                        struct dwarf2_per_cu_data *per_cu)
22665 {
22666   const gdb_byte *info_ptr;
22667
22668   if (per_cu->cu)
22669     return &per_cu->cu->header;
22670
22671   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22672
22673   memset (cu_headerp, 0, sizeof (*cu_headerp));
22674   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22675                        rcuh_kind::COMPILE);
22676
22677   return cu_headerp;
22678 }
22679
22680 /* Return the address size given in the compilation unit header for CU.  */
22681
22682 int
22683 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22684 {
22685   struct comp_unit_head cu_header_local;
22686   const struct comp_unit_head *cu_headerp;
22687
22688   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22689
22690   return cu_headerp->addr_size;
22691 }
22692
22693 /* Return the offset size given in the compilation unit header for CU.  */
22694
22695 int
22696 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22697 {
22698   struct comp_unit_head cu_header_local;
22699   const struct comp_unit_head *cu_headerp;
22700
22701   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22702
22703   return cu_headerp->offset_size;
22704 }
22705
22706 /* See its dwarf2loc.h declaration.  */
22707
22708 int
22709 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22710 {
22711   struct comp_unit_head cu_header_local;
22712   const struct comp_unit_head *cu_headerp;
22713
22714   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22715
22716   if (cu_headerp->version == 2)
22717     return cu_headerp->addr_size;
22718   else
22719     return cu_headerp->offset_size;
22720 }
22721
22722 /* Return the text offset of the CU.  The returned offset comes from
22723    this CU's objfile.  If this objfile came from a separate debuginfo
22724    file, then the offset may be different from the corresponding
22725    offset in the parent objfile.  */
22726
22727 CORE_ADDR
22728 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22729 {
22730   struct objfile *objfile = per_cu->objfile;
22731
22732   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22733 }
22734
22735 /* Return DWARF version number of PER_CU.  */
22736
22737 short
22738 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22739 {
22740   return per_cu->dwarf_version;
22741 }
22742
22743 /* Locate the .debug_info compilation unit from CU's objfile which contains
22744    the DIE at OFFSET.  Raises an error on failure.  */
22745
22746 static struct dwarf2_per_cu_data *
22747 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22748                                   unsigned int offset_in_dwz,
22749                                   struct objfile *objfile)
22750 {
22751   struct dwarf2_per_cu_data *this_cu;
22752   int low, high;
22753   const sect_offset *cu_off;
22754
22755   low = 0;
22756   high = dwarf2_per_objfile->n_comp_units - 1;
22757   while (high > low)
22758     {
22759       struct dwarf2_per_cu_data *mid_cu;
22760       int mid = low + (high - low) / 2;
22761
22762       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22763       cu_off = &mid_cu->sect_off;
22764       if (mid_cu->is_dwz > offset_in_dwz
22765           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22766         high = mid;
22767       else
22768         low = mid + 1;
22769     }
22770   gdb_assert (low == high);
22771   this_cu = dwarf2_per_objfile->all_comp_units[low];
22772   cu_off = &this_cu->sect_off;
22773   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22774     {
22775       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22776         error (_("Dwarf Error: could not find partial DIE containing "
22777                "offset 0x%x [in module %s]"),
22778                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22779
22780       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22781                   <= sect_off);
22782       return dwarf2_per_objfile->all_comp_units[low-1];
22783     }
22784   else
22785     {
22786       this_cu = dwarf2_per_objfile->all_comp_units[low];
22787       if (low == dwarf2_per_objfile->n_comp_units - 1
22788           && sect_off >= this_cu->sect_off + this_cu->length)
22789         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22790       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22791       return this_cu;
22792     }
22793 }
22794
22795 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22796
22797 static void
22798 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22799 {
22800   memset (cu, 0, sizeof (*cu));
22801   per_cu->cu = cu;
22802   cu->per_cu = per_cu;
22803   cu->objfile = per_cu->objfile;
22804   obstack_init (&cu->comp_unit_obstack);
22805 }
22806
22807 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22808
22809 static void
22810 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22811                        enum language pretend_language)
22812 {
22813   struct attribute *attr;
22814
22815   /* Set the language we're debugging.  */
22816   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22817   if (attr)
22818     set_cu_language (DW_UNSND (attr), cu);
22819   else
22820     {
22821       cu->language = pretend_language;
22822       cu->language_defn = language_def (cu->language);
22823     }
22824
22825   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22826 }
22827
22828 /* Release one cached compilation unit, CU.  We unlink it from the tree
22829    of compilation units, but we don't remove it from the read_in_chain;
22830    the caller is responsible for that.
22831    NOTE: DATA is a void * because this function is also used as a
22832    cleanup routine.  */
22833
22834 static void
22835 free_heap_comp_unit (void *data)
22836 {
22837   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22838
22839   gdb_assert (cu->per_cu != NULL);
22840   cu->per_cu->cu = NULL;
22841   cu->per_cu = NULL;
22842
22843   obstack_free (&cu->comp_unit_obstack, NULL);
22844
22845   xfree (cu);
22846 }
22847
22848 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22849    when we're finished with it.  We can't free the pointer itself, but be
22850    sure to unlink it from the cache.  Also release any associated storage.  */
22851
22852 static void
22853 free_stack_comp_unit (void *data)
22854 {
22855   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22856
22857   gdb_assert (cu->per_cu != NULL);
22858   cu->per_cu->cu = NULL;
22859   cu->per_cu = NULL;
22860
22861   obstack_free (&cu->comp_unit_obstack, NULL);
22862   cu->partial_dies = NULL;
22863 }
22864
22865 /* Free all cached compilation units.  */
22866
22867 static void
22868 free_cached_comp_units (void *data)
22869 {
22870   dwarf2_per_objfile->free_cached_comp_units ();
22871 }
22872
22873 /* Increase the age counter on each cached compilation unit, and free
22874    any that are too old.  */
22875
22876 static void
22877 age_cached_comp_units (void)
22878 {
22879   struct dwarf2_per_cu_data *per_cu, **last_chain;
22880
22881   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22882   per_cu = dwarf2_per_objfile->read_in_chain;
22883   while (per_cu != NULL)
22884     {
22885       per_cu->cu->last_used ++;
22886       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22887         dwarf2_mark (per_cu->cu);
22888       per_cu = per_cu->cu->read_in_chain;
22889     }
22890
22891   per_cu = dwarf2_per_objfile->read_in_chain;
22892   last_chain = &dwarf2_per_objfile->read_in_chain;
22893   while (per_cu != NULL)
22894     {
22895       struct dwarf2_per_cu_data *next_cu;
22896
22897       next_cu = per_cu->cu->read_in_chain;
22898
22899       if (!per_cu->cu->mark)
22900         {
22901           free_heap_comp_unit (per_cu->cu);
22902           *last_chain = next_cu;
22903         }
22904       else
22905         last_chain = &per_cu->cu->read_in_chain;
22906
22907       per_cu = next_cu;
22908     }
22909 }
22910
22911 /* Remove a single compilation unit from the cache.  */
22912
22913 static void
22914 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22915 {
22916   struct dwarf2_per_cu_data *per_cu, **last_chain;
22917
22918   per_cu = dwarf2_per_objfile->read_in_chain;
22919   last_chain = &dwarf2_per_objfile->read_in_chain;
22920   while (per_cu != NULL)
22921     {
22922       struct dwarf2_per_cu_data *next_cu;
22923
22924       next_cu = per_cu->cu->read_in_chain;
22925
22926       if (per_cu == target_per_cu)
22927         {
22928           free_heap_comp_unit (per_cu->cu);
22929           per_cu->cu = NULL;
22930           *last_chain = next_cu;
22931           break;
22932         }
22933       else
22934         last_chain = &per_cu->cu->read_in_chain;
22935
22936       per_cu = next_cu;
22937     }
22938 }
22939
22940 /* Release all extra memory associated with OBJFILE.  */
22941
22942 void
22943 dwarf2_free_objfile (struct objfile *objfile)
22944 {
22945   dwarf2_per_objfile
22946     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22947                                                   dwarf2_objfile_data_key);
22948
22949   if (dwarf2_per_objfile == NULL)
22950     return;
22951
22952   dwarf2_per_objfile->~dwarf2_per_objfile ();
22953 }
22954
22955 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22956    We store these in a hash table separate from the DIEs, and preserve them
22957    when the DIEs are flushed out of cache.
22958
22959    The CU "per_cu" pointer is needed because offset alone is not enough to
22960    uniquely identify the type.  A file may have multiple .debug_types sections,
22961    or the type may come from a DWO file.  Furthermore, while it's more logical
22962    to use per_cu->section+offset, with Fission the section with the data is in
22963    the DWO file but we don't know that section at the point we need it.
22964    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22965    because we can enter the lookup routine, get_die_type_at_offset, from
22966    outside this file, and thus won't necessarily have PER_CU->cu.
22967    Fortunately, PER_CU is stable for the life of the objfile.  */
22968
22969 struct dwarf2_per_cu_offset_and_type
22970 {
22971   const struct dwarf2_per_cu_data *per_cu;
22972   sect_offset sect_off;
22973   struct type *type;
22974 };
22975
22976 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22977
22978 static hashval_t
22979 per_cu_offset_and_type_hash (const void *item)
22980 {
22981   const struct dwarf2_per_cu_offset_and_type *ofs
22982     = (const struct dwarf2_per_cu_offset_and_type *) item;
22983
22984   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22985 }
22986
22987 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22988
22989 static int
22990 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22991 {
22992   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22993     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22994   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22995     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22996
22997   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22998           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22999 }
23000
23001 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23002    table if necessary.  For convenience, return TYPE.
23003
23004    The DIEs reading must have careful ordering to:
23005     * Not cause infite loops trying to read in DIEs as a prerequisite for
23006       reading current DIE.
23007     * Not trying to dereference contents of still incompletely read in types
23008       while reading in other DIEs.
23009     * Enable referencing still incompletely read in types just by a pointer to
23010       the type without accessing its fields.
23011
23012    Therefore caller should follow these rules:
23013      * Try to fetch any prerequisite types we may need to build this DIE type
23014        before building the type and calling set_die_type.
23015      * After building type call set_die_type for current DIE as soon as
23016        possible before fetching more types to complete the current type.
23017      * Make the type as complete as possible before fetching more types.  */
23018
23019 static struct type *
23020 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23021 {
23022   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23023   struct objfile *objfile = cu->objfile;
23024   struct attribute *attr;
23025   struct dynamic_prop prop;
23026
23027   /* For Ada types, make sure that the gnat-specific data is always
23028      initialized (if not already set).  There are a few types where
23029      we should not be doing so, because the type-specific area is
23030      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23031      where the type-specific area is used to store the floatformat).
23032      But this is not a problem, because the gnat-specific information
23033      is actually not needed for these types.  */
23034   if (need_gnat_info (cu)
23035       && TYPE_CODE (type) != TYPE_CODE_FUNC
23036       && TYPE_CODE (type) != TYPE_CODE_FLT
23037       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23038       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23039       && TYPE_CODE (type) != TYPE_CODE_METHOD
23040       && !HAVE_GNAT_AUX_INFO (type))
23041     INIT_GNAT_SPECIFIC (type);
23042
23043   /* Read DW_AT_allocated and set in type.  */
23044   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23045   if (attr_form_is_block (attr))
23046     {
23047       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23048         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23049     }
23050   else if (attr != NULL)
23051     {
23052       complaint (&symfile_complaints,
23053                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23054                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23055                  to_underlying (die->sect_off));
23056     }
23057
23058   /* Read DW_AT_associated and set in type.  */
23059   attr = dwarf2_attr (die, DW_AT_associated, cu);
23060   if (attr_form_is_block (attr))
23061     {
23062       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23063         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23064     }
23065   else if (attr != NULL)
23066     {
23067       complaint (&symfile_complaints,
23068                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23069                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23070                  to_underlying (die->sect_off));
23071     }
23072
23073   /* Read DW_AT_data_location and set in type.  */
23074   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23075   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23076     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23077
23078   if (dwarf2_per_objfile->die_type_hash == NULL)
23079     {
23080       dwarf2_per_objfile->die_type_hash =
23081         htab_create_alloc_ex (127,
23082                               per_cu_offset_and_type_hash,
23083                               per_cu_offset_and_type_eq,
23084                               NULL,
23085                               &objfile->objfile_obstack,
23086                               hashtab_obstack_allocate,
23087                               dummy_obstack_deallocate);
23088     }
23089
23090   ofs.per_cu = cu->per_cu;
23091   ofs.sect_off = die->sect_off;
23092   ofs.type = type;
23093   slot = (struct dwarf2_per_cu_offset_and_type **)
23094     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23095   if (*slot)
23096     complaint (&symfile_complaints,
23097                _("A problem internal to GDB: DIE 0x%x has type already set"),
23098                to_underlying (die->sect_off));
23099   *slot = XOBNEW (&objfile->objfile_obstack,
23100                   struct dwarf2_per_cu_offset_and_type);
23101   **slot = ofs;
23102   return type;
23103 }
23104
23105 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23106    or return NULL if the die does not have a saved type.  */
23107
23108 static struct type *
23109 get_die_type_at_offset (sect_offset sect_off,
23110                         struct dwarf2_per_cu_data *per_cu)
23111 {
23112   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23113
23114   if (dwarf2_per_objfile->die_type_hash == NULL)
23115     return NULL;
23116
23117   ofs.per_cu = per_cu;
23118   ofs.sect_off = sect_off;
23119   slot = ((struct dwarf2_per_cu_offset_and_type *)
23120           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23121   if (slot)
23122     return slot->type;
23123   else
23124     return NULL;
23125 }
23126
23127 /* Look up the type for DIE in CU in die_type_hash,
23128    or return NULL if DIE does not have a saved type.  */
23129
23130 static struct type *
23131 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23132 {
23133   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23134 }
23135
23136 /* Add a dependence relationship from CU to REF_PER_CU.  */
23137
23138 static void
23139 dwarf2_add_dependence (struct dwarf2_cu *cu,
23140                        struct dwarf2_per_cu_data *ref_per_cu)
23141 {
23142   void **slot;
23143
23144   if (cu->dependencies == NULL)
23145     cu->dependencies
23146       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23147                               NULL, &cu->comp_unit_obstack,
23148                               hashtab_obstack_allocate,
23149                               dummy_obstack_deallocate);
23150
23151   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23152   if (*slot == NULL)
23153     *slot = ref_per_cu;
23154 }
23155
23156 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23157    Set the mark field in every compilation unit in the
23158    cache that we must keep because we are keeping CU.  */
23159
23160 static int
23161 dwarf2_mark_helper (void **slot, void *data)
23162 {
23163   struct dwarf2_per_cu_data *per_cu;
23164
23165   per_cu = (struct dwarf2_per_cu_data *) *slot;
23166
23167   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23168      reading of the chain.  As such dependencies remain valid it is not much
23169      useful to track and undo them during QUIT cleanups.  */
23170   if (per_cu->cu == NULL)
23171     return 1;
23172
23173   if (per_cu->cu->mark)
23174     return 1;
23175   per_cu->cu->mark = 1;
23176
23177   if (per_cu->cu->dependencies != NULL)
23178     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23179
23180   return 1;
23181 }
23182
23183 /* Set the mark field in CU and in every other compilation unit in the
23184    cache that we must keep because we are keeping CU.  */
23185
23186 static void
23187 dwarf2_mark (struct dwarf2_cu *cu)
23188 {
23189   if (cu->mark)
23190     return;
23191   cu->mark = 1;
23192   if (cu->dependencies != NULL)
23193     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23194 }
23195
23196 static void
23197 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23198 {
23199   while (per_cu)
23200     {
23201       per_cu->cu->mark = 0;
23202       per_cu = per_cu->cu->read_in_chain;
23203     }
23204 }
23205
23206 /* Trivial hash function for partial_die_info: the hash value of a DIE
23207    is its offset in .debug_info for this objfile.  */
23208
23209 static hashval_t
23210 partial_die_hash (const void *item)
23211 {
23212   const struct partial_die_info *part_die
23213     = (const struct partial_die_info *) item;
23214
23215   return to_underlying (part_die->sect_off);
23216 }
23217
23218 /* Trivial comparison function for partial_die_info structures: two DIEs
23219    are equal if they have the same offset.  */
23220
23221 static int
23222 partial_die_eq (const void *item_lhs, const void *item_rhs)
23223 {
23224   const struct partial_die_info *part_die_lhs
23225     = (const struct partial_die_info *) item_lhs;
23226   const struct partial_die_info *part_die_rhs
23227     = (const struct partial_die_info *) item_rhs;
23228
23229   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23230 }
23231
23232 static struct cmd_list_element *set_dwarf_cmdlist;
23233 static struct cmd_list_element *show_dwarf_cmdlist;
23234
23235 static void
23236 set_dwarf_cmd (const char *args, int from_tty)
23237 {
23238   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23239              gdb_stdout);
23240 }
23241
23242 static void
23243 show_dwarf_cmd (const char *args, int from_tty)
23244 {
23245   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23246 }
23247
23248 /* Free data associated with OBJFILE, if necessary.  */
23249
23250 static void
23251 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23252 {
23253   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23254   int ix;
23255
23256   /* Make sure we don't accidentally use dwarf2_per_objfile while
23257      cleaning up.  */
23258   dwarf2_per_objfile = NULL;
23259
23260   for (ix = 0; ix < data->n_comp_units; ++ix)
23261    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23262
23263   for (ix = 0; ix < data->n_type_units; ++ix)
23264     VEC_free (dwarf2_per_cu_ptr,
23265               data->all_type_units[ix]->per_cu.imported_symtabs);
23266   xfree (data->all_type_units);
23267
23268   VEC_free (dwarf2_section_info_def, data->types);
23269
23270   if (data->dwo_files)
23271     free_dwo_files (data->dwo_files, objfile);
23272   if (data->dwp_file)
23273     gdb_bfd_unref (data->dwp_file->dbfd);
23274
23275   if (data->dwz_file && data->dwz_file->dwz_bfd)
23276     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23277 }
23278
23279 \f
23280 /* The "save gdb-index" command.  */
23281
23282 /* In-memory buffer to prepare data to be written later to a file.  */
23283 class data_buf
23284 {
23285 public:
23286   /* Copy DATA to the end of the buffer.  */
23287   template<typename T>
23288   void append_data (const T &data)
23289   {
23290     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23291                reinterpret_cast<const gdb_byte *> (&data + 1),
23292                grow (sizeof (data)));
23293   }
23294
23295   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23296      terminating zero is appended too.  */
23297   void append_cstr0 (const char *cstr)
23298   {
23299     const size_t size = strlen (cstr) + 1;
23300     std::copy (cstr, cstr + size, grow (size));
23301   }
23302
23303   /* Accept a host-format integer in VAL and append it to the buffer
23304      as a target-format integer which is LEN bytes long.  */
23305   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23306   {
23307     ::store_unsigned_integer (grow (len), len, byte_order, val);
23308   }
23309
23310   /* Return the size of the buffer.  */
23311   size_t size () const
23312   {
23313     return m_vec.size ();
23314   }
23315
23316   /* Write the buffer to FILE.  */
23317   void file_write (FILE *file) const
23318   {
23319     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23320       error (_("couldn't write data to file"));
23321   }
23322
23323 private:
23324   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23325      the start of the new block.  */
23326   gdb_byte *grow (size_t size)
23327   {
23328     m_vec.resize (m_vec.size () + size);
23329     return &*m_vec.end () - size;
23330   }
23331
23332   gdb::byte_vector m_vec;
23333 };
23334
23335 /* An entry in the symbol table.  */
23336 struct symtab_index_entry
23337 {
23338   /* The name of the symbol.  */
23339   const char *name;
23340   /* The offset of the name in the constant pool.  */
23341   offset_type index_offset;
23342   /* A sorted vector of the indices of all the CUs that hold an object
23343      of this name.  */
23344   std::vector<offset_type> cu_indices;
23345 };
23346
23347 /* The symbol table.  This is a power-of-2-sized hash table.  */
23348 struct mapped_symtab
23349 {
23350   mapped_symtab ()
23351   {
23352     data.resize (1024);
23353   }
23354
23355   offset_type n_elements = 0;
23356   std::vector<symtab_index_entry> data;
23357 };
23358
23359 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23360    the slot.
23361    
23362    Function is used only during write_hash_table so no index format backward
23363    compatibility is needed.  */
23364
23365 static symtab_index_entry &
23366 find_slot (struct mapped_symtab *symtab, const char *name)
23367 {
23368   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23369
23370   index = hash & (symtab->data.size () - 1);
23371   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23372
23373   for (;;)
23374     {
23375       if (symtab->data[index].name == NULL
23376           || strcmp (name, symtab->data[index].name) == 0)
23377         return symtab->data[index];
23378       index = (index + step) & (symtab->data.size () - 1);
23379     }
23380 }
23381
23382 /* Expand SYMTAB's hash table.  */
23383
23384 static void
23385 hash_expand (struct mapped_symtab *symtab)
23386 {
23387   auto old_entries = std::move (symtab->data);
23388
23389   symtab->data.clear ();
23390   symtab->data.resize (old_entries.size () * 2);
23391
23392   for (auto &it : old_entries)
23393     if (it.name != NULL)
23394       {
23395         auto &ref = find_slot (symtab, it.name);
23396         ref = std::move (it);
23397       }
23398 }
23399
23400 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23401    CU_INDEX is the index of the CU in which the symbol appears.
23402    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23403
23404 static void
23405 add_index_entry (struct mapped_symtab *symtab, const char *name,
23406                  int is_static, gdb_index_symbol_kind kind,
23407                  offset_type cu_index)
23408 {
23409   offset_type cu_index_and_attrs;
23410
23411   ++symtab->n_elements;
23412   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23413     hash_expand (symtab);
23414
23415   symtab_index_entry &slot = find_slot (symtab, name);
23416   if (slot.name == NULL)
23417     {
23418       slot.name = name;
23419       /* index_offset is set later.  */
23420     }
23421
23422   cu_index_and_attrs = 0;
23423   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23424   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23425   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23426
23427   /* We don't want to record an index value twice as we want to avoid the
23428      duplication.
23429      We process all global symbols and then all static symbols
23430      (which would allow us to avoid the duplication by only having to check
23431      the last entry pushed), but a symbol could have multiple kinds in one CU.
23432      To keep things simple we don't worry about the duplication here and
23433      sort and uniqufy the list after we've processed all symbols.  */
23434   slot.cu_indices.push_back (cu_index_and_attrs);
23435 }
23436
23437 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23438
23439 static void
23440 uniquify_cu_indices (struct mapped_symtab *symtab)
23441 {
23442   for (auto &entry : symtab->data)
23443     {
23444       if (entry.name != NULL && !entry.cu_indices.empty ())
23445         {
23446           auto &cu_indices = entry.cu_indices;
23447           std::sort (cu_indices.begin (), cu_indices.end ());
23448           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23449           cu_indices.erase (from, cu_indices.end ());
23450         }
23451     }
23452 }
23453
23454 /* A form of 'const char *' suitable for container keys.  Only the
23455    pointer is stored.  The strings themselves are compared, not the
23456    pointers.  */
23457 class c_str_view
23458 {
23459 public:
23460   c_str_view (const char *cstr)
23461     : m_cstr (cstr)
23462   {}
23463
23464   bool operator== (const c_str_view &other) const
23465   {
23466     return strcmp (m_cstr, other.m_cstr) == 0;
23467   }
23468
23469 private:
23470   friend class c_str_view_hasher;
23471   const char *const m_cstr;
23472 };
23473
23474 /* A std::unordered_map::hasher for c_str_view that uses the right
23475    hash function for strings in a mapped index.  */
23476 class c_str_view_hasher
23477 {
23478 public:
23479   size_t operator () (const c_str_view &x) const
23480   {
23481     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23482   }
23483 };
23484
23485 /* A std::unordered_map::hasher for std::vector<>.  */
23486 template<typename T>
23487 class vector_hasher
23488 {
23489 public:
23490   size_t operator () (const std::vector<T> &key) const
23491   {
23492     return iterative_hash (key.data (),
23493                            sizeof (key.front ()) * key.size (), 0);
23494   }
23495 };
23496
23497 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23498    constant pool entries going into the data buffer CPOOL.  */
23499
23500 static void
23501 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23502 {
23503   {
23504     /* Elements are sorted vectors of the indices of all the CUs that
23505        hold an object of this name.  */
23506     std::unordered_map<std::vector<offset_type>, offset_type,
23507                        vector_hasher<offset_type>>
23508       symbol_hash_table;
23509
23510     /* We add all the index vectors to the constant pool first, to
23511        ensure alignment is ok.  */
23512     for (symtab_index_entry &entry : symtab->data)
23513       {
23514         if (entry.name == NULL)
23515           continue;
23516         gdb_assert (entry.index_offset == 0);
23517
23518         /* Finding before inserting is faster than always trying to
23519            insert, because inserting always allocates a node, does the
23520            lookup, and then destroys the new node if another node
23521            already had the same key.  C++17 try_emplace will avoid
23522            this.  */
23523         const auto found
23524           = symbol_hash_table.find (entry.cu_indices);
23525         if (found != symbol_hash_table.end ())
23526           {
23527             entry.index_offset = found->second;
23528             continue;
23529           }
23530
23531         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23532         entry.index_offset = cpool.size ();
23533         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23534         for (const auto index : entry.cu_indices)
23535           cpool.append_data (MAYBE_SWAP (index));
23536       }
23537   }
23538
23539   /* Now write out the hash table.  */
23540   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23541   for (const auto &entry : symtab->data)
23542     {
23543       offset_type str_off, vec_off;
23544
23545       if (entry.name != NULL)
23546         {
23547           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23548           if (insertpair.second)
23549             cpool.append_cstr0 (entry.name);
23550           str_off = insertpair.first->second;
23551           vec_off = entry.index_offset;
23552         }
23553       else
23554         {
23555           /* While 0 is a valid constant pool index, it is not valid
23556              to have 0 for both offsets.  */
23557           str_off = 0;
23558           vec_off = 0;
23559         }
23560
23561       output.append_data (MAYBE_SWAP (str_off));
23562       output.append_data (MAYBE_SWAP (vec_off));
23563     }
23564 }
23565
23566 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23567
23568 /* Helper struct for building the address table.  */
23569 struct addrmap_index_data
23570 {
23571   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23572     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23573   {}
23574
23575   struct objfile *objfile;
23576   data_buf &addr_vec;
23577   psym_index_map &cu_index_htab;
23578
23579   /* Non-zero if the previous_* fields are valid.
23580      We can't write an entry until we see the next entry (since it is only then
23581      that we know the end of the entry).  */
23582   int previous_valid;
23583   /* Index of the CU in the table of all CUs in the index file.  */
23584   unsigned int previous_cu_index;
23585   /* Start address of the CU.  */
23586   CORE_ADDR previous_cu_start;
23587 };
23588
23589 /* Write an address entry to ADDR_VEC.  */
23590
23591 static void
23592 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23593                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23594 {
23595   CORE_ADDR baseaddr;
23596
23597   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23598
23599   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23600   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23601   addr_vec.append_data (MAYBE_SWAP (cu_index));
23602 }
23603
23604 /* Worker function for traversing an addrmap to build the address table.  */
23605
23606 static int
23607 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23608 {
23609   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23610   struct partial_symtab *pst = (struct partial_symtab *) obj;
23611
23612   if (data->previous_valid)
23613     add_address_entry (data->objfile, data->addr_vec,
23614                        data->previous_cu_start, start_addr,
23615                        data->previous_cu_index);
23616
23617   data->previous_cu_start = start_addr;
23618   if (pst != NULL)
23619     {
23620       const auto it = data->cu_index_htab.find (pst);
23621       gdb_assert (it != data->cu_index_htab.cend ());
23622       data->previous_cu_index = it->second;
23623       data->previous_valid = 1;
23624     }
23625   else
23626     data->previous_valid = 0;
23627
23628   return 0;
23629 }
23630
23631 /* Write OBJFILE's address map to ADDR_VEC.
23632    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23633    in the index file.  */
23634
23635 static void
23636 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23637                    psym_index_map &cu_index_htab)
23638 {
23639   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23640
23641   /* When writing the address table, we have to cope with the fact that
23642      the addrmap iterator only provides the start of a region; we have to
23643      wait until the next invocation to get the start of the next region.  */
23644
23645   addrmap_index_data.objfile = objfile;
23646   addrmap_index_data.previous_valid = 0;
23647
23648   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23649                    &addrmap_index_data);
23650
23651   /* It's highly unlikely the last entry (end address = 0xff...ff)
23652      is valid, but we should still handle it.
23653      The end address is recorded as the start of the next region, but that
23654      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23655      anyway.  */
23656   if (addrmap_index_data.previous_valid)
23657     add_address_entry (objfile, addr_vec,
23658                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23659                        addrmap_index_data.previous_cu_index);
23660 }
23661
23662 /* Return the symbol kind of PSYM.  */
23663
23664 static gdb_index_symbol_kind
23665 symbol_kind (struct partial_symbol *psym)
23666 {
23667   domain_enum domain = PSYMBOL_DOMAIN (psym);
23668   enum address_class aclass = PSYMBOL_CLASS (psym);
23669
23670   switch (domain)
23671     {
23672     case VAR_DOMAIN:
23673       switch (aclass)
23674         {
23675         case LOC_BLOCK:
23676           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23677         case LOC_TYPEDEF:
23678           return GDB_INDEX_SYMBOL_KIND_TYPE;
23679         case LOC_COMPUTED:
23680         case LOC_CONST_BYTES:
23681         case LOC_OPTIMIZED_OUT:
23682         case LOC_STATIC:
23683           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23684         case LOC_CONST:
23685           /* Note: It's currently impossible to recognize psyms as enum values
23686              short of reading the type info.  For now punt.  */
23687           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23688         default:
23689           /* There are other LOC_FOO values that one might want to classify
23690              as variables, but dwarf2read.c doesn't currently use them.  */
23691           return GDB_INDEX_SYMBOL_KIND_OTHER;
23692         }
23693     case STRUCT_DOMAIN:
23694       return GDB_INDEX_SYMBOL_KIND_TYPE;
23695     default:
23696       return GDB_INDEX_SYMBOL_KIND_OTHER;
23697     }
23698 }
23699
23700 /* Add a list of partial symbols to SYMTAB.  */
23701
23702 static void
23703 write_psymbols (struct mapped_symtab *symtab,
23704                 std::unordered_set<partial_symbol *> &psyms_seen,
23705                 struct partial_symbol **psymp,
23706                 int count,
23707                 offset_type cu_index,
23708                 int is_static)
23709 {
23710   for (; count-- > 0; ++psymp)
23711     {
23712       struct partial_symbol *psym = *psymp;
23713
23714       if (SYMBOL_LANGUAGE (psym) == language_ada)
23715         error (_("Ada is not currently supported by the index"));
23716
23717       /* Only add a given psymbol once.  */
23718       if (psyms_seen.insert (psym).second)
23719         {
23720           gdb_index_symbol_kind kind = symbol_kind (psym);
23721
23722           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23723                            is_static, kind, cu_index);
23724         }
23725     }
23726 }
23727
23728 /* A helper struct used when iterating over debug_types.  */
23729 struct signatured_type_index_data
23730 {
23731   signatured_type_index_data (data_buf &types_list_,
23732                               std::unordered_set<partial_symbol *> &psyms_seen_)
23733     : types_list (types_list_), psyms_seen (psyms_seen_)
23734   {}
23735
23736   struct objfile *objfile;
23737   struct mapped_symtab *symtab;
23738   data_buf &types_list;
23739   std::unordered_set<partial_symbol *> &psyms_seen;
23740   int cu_index;
23741 };
23742
23743 /* A helper function that writes a single signatured_type to an
23744    obstack.  */
23745
23746 static int
23747 write_one_signatured_type (void **slot, void *d)
23748 {
23749   struct signatured_type_index_data *info
23750     = (struct signatured_type_index_data *) d;
23751   struct signatured_type *entry = (struct signatured_type *) *slot;
23752   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23753
23754   write_psymbols (info->symtab,
23755                   info->psyms_seen,
23756                   &info->objfile->global_psymbols[psymtab->globals_offset],
23757                   psymtab->n_global_syms, info->cu_index,
23758                   0);
23759   write_psymbols (info->symtab,
23760                   info->psyms_seen,
23761                   &info->objfile->static_psymbols[psymtab->statics_offset],
23762                   psymtab->n_static_syms, info->cu_index,
23763                   1);
23764
23765   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23766                                 to_underlying (entry->per_cu.sect_off));
23767   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23768                                 to_underlying (entry->type_offset_in_tu));
23769   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23770
23771   ++info->cu_index;
23772
23773   return 1;
23774 }
23775
23776 /* Recurse into all "included" dependencies and count their symbols as
23777    if they appeared in this psymtab.  */
23778
23779 static void
23780 recursively_count_psymbols (struct partial_symtab *psymtab,
23781                             size_t &psyms_seen)
23782 {
23783   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23784     if (psymtab->dependencies[i]->user != NULL)
23785       recursively_count_psymbols (psymtab->dependencies[i],
23786                                   psyms_seen);
23787
23788   psyms_seen += psymtab->n_global_syms;
23789   psyms_seen += psymtab->n_static_syms;
23790 }
23791
23792 /* Recurse into all "included" dependencies and write their symbols as
23793    if they appeared in this psymtab.  */
23794
23795 static void
23796 recursively_write_psymbols (struct objfile *objfile,
23797                             struct partial_symtab *psymtab,
23798                             struct mapped_symtab *symtab,
23799                             std::unordered_set<partial_symbol *> &psyms_seen,
23800                             offset_type cu_index)
23801 {
23802   int i;
23803
23804   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23805     if (psymtab->dependencies[i]->user != NULL)
23806       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23807                                   symtab, psyms_seen, cu_index);
23808
23809   write_psymbols (symtab,
23810                   psyms_seen,
23811                   &objfile->global_psymbols[psymtab->globals_offset],
23812                   psymtab->n_global_syms, cu_index,
23813                   0);
23814   write_psymbols (symtab,
23815                   psyms_seen,
23816                   &objfile->static_psymbols[psymtab->statics_offset],
23817                   psymtab->n_static_syms, cu_index,
23818                   1);
23819 }
23820
23821 /* Create an index file for OBJFILE in the directory DIR.  */
23822
23823 static void
23824 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23825 {
23826   if (dwarf2_per_objfile->using_index)
23827     error (_("Cannot use an index to create the index"));
23828
23829   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23830     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23831
23832   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23833     return;
23834
23835   struct stat st;
23836   if (stat (objfile_name (objfile), &st) < 0)
23837     perror_with_name (objfile_name (objfile));
23838
23839   std::string filename (std::string (dir) + SLASH_STRING
23840                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23841
23842   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23843   if (!out_file)
23844     error (_("Can't open `%s' for writing"), filename.c_str ());
23845
23846   /* Order matters here; we want FILE to be closed before FILENAME is
23847      unlinked, because on MS-Windows one cannot delete a file that is
23848      still open.  (Don't call anything here that might throw until
23849      file_closer is created.)  */
23850   gdb::unlinker unlink_file (filename.c_str ());
23851   gdb_file_up close_out_file (out_file);
23852
23853   mapped_symtab symtab;
23854   data_buf cu_list;
23855
23856   /* While we're scanning CU's create a table that maps a psymtab pointer
23857      (which is what addrmap records) to its index (which is what is recorded
23858      in the index file).  This will later be needed to write the address
23859      table.  */
23860   psym_index_map cu_index_htab;
23861   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23862
23863   /* The CU list is already sorted, so we don't need to do additional
23864      work here.  Also, the debug_types entries do not appear in
23865      all_comp_units, but only in their own hash table.  */
23866
23867   /* The psyms_seen set is potentially going to be largish (~40k
23868      elements when indexing a -g3 build of GDB itself).  Estimate the
23869      number of elements in order to avoid too many rehashes, which
23870      require rebuilding buckets and thus many trips to
23871      malloc/free.  */
23872   size_t psyms_count = 0;
23873   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23874     {
23875       struct dwarf2_per_cu_data *per_cu
23876         = dwarf2_per_objfile->all_comp_units[i];
23877       struct partial_symtab *psymtab = per_cu->v.psymtab;
23878
23879       if (psymtab != NULL && psymtab->user == NULL)
23880         recursively_count_psymbols (psymtab, psyms_count);
23881     }
23882   /* Generating an index for gdb itself shows a ratio of
23883      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23884   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23885   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23886     {
23887       struct dwarf2_per_cu_data *per_cu
23888         = dwarf2_per_objfile->all_comp_units[i];
23889       struct partial_symtab *psymtab = per_cu->v.psymtab;
23890
23891       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23892          It may be referenced from a local scope but in such case it does not
23893          need to be present in .gdb_index.  */
23894       if (psymtab == NULL)
23895         continue;
23896
23897       if (psymtab->user == NULL)
23898         recursively_write_psymbols (objfile, psymtab, &symtab,
23899                                     psyms_seen, i);
23900
23901       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23902       gdb_assert (insertpair.second);
23903
23904       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23905                            to_underlying (per_cu->sect_off));
23906       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23907     }
23908
23909   /* Dump the address map.  */
23910   data_buf addr_vec;
23911   write_address_map (objfile, addr_vec, cu_index_htab);
23912
23913   /* Write out the .debug_type entries, if any.  */
23914   data_buf types_cu_list;
23915   if (dwarf2_per_objfile->signatured_types)
23916     {
23917       signatured_type_index_data sig_data (types_cu_list,
23918                                            psyms_seen);
23919
23920       sig_data.objfile = objfile;
23921       sig_data.symtab = &symtab;
23922       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23923       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23924                               write_one_signatured_type, &sig_data);
23925     }
23926
23927   /* Now that we've processed all symbols we can shrink their cu_indices
23928      lists.  */
23929   uniquify_cu_indices (&symtab);
23930
23931   data_buf symtab_vec, constant_pool;
23932   write_hash_table (&symtab, symtab_vec, constant_pool);
23933
23934   data_buf contents;
23935   const offset_type size_of_contents = 6 * sizeof (offset_type);
23936   offset_type total_len = size_of_contents;
23937
23938   /* The version number.  */
23939   contents.append_data (MAYBE_SWAP (8));
23940
23941   /* The offset of the CU list from the start of the file.  */
23942   contents.append_data (MAYBE_SWAP (total_len));
23943   total_len += cu_list.size ();
23944
23945   /* The offset of the types CU list from the start of the file.  */
23946   contents.append_data (MAYBE_SWAP (total_len));
23947   total_len += types_cu_list.size ();
23948
23949   /* The offset of the address table from the start of the file.  */
23950   contents.append_data (MAYBE_SWAP (total_len));
23951   total_len += addr_vec.size ();
23952
23953   /* The offset of the symbol table from the start of the file.  */
23954   contents.append_data (MAYBE_SWAP (total_len));
23955   total_len += symtab_vec.size ();
23956
23957   /* The offset of the constant pool from the start of the file.  */
23958   contents.append_data (MAYBE_SWAP (total_len));
23959   total_len += constant_pool.size ();
23960
23961   gdb_assert (contents.size () == size_of_contents);
23962
23963   contents.file_write (out_file);
23964   cu_list.file_write (out_file);
23965   types_cu_list.file_write (out_file);
23966   addr_vec.file_write (out_file);
23967   symtab_vec.file_write (out_file);
23968   constant_pool.file_write (out_file);
23969
23970   /* We want to keep the file.  */
23971   unlink_file.keep ();
23972 }
23973
23974 /* Implementation of the `save gdb-index' command.
23975    
23976    Note that the file format used by this command is documented in the
23977    GDB manual.  Any changes here must be documented there.  */
23978
23979 static void
23980 save_gdb_index_command (const char *arg, int from_tty)
23981 {
23982   struct objfile *objfile;
23983
23984   if (!arg || !*arg)
23985     error (_("usage: save gdb-index DIRECTORY"));
23986
23987   ALL_OBJFILES (objfile)
23988   {
23989     struct stat st;
23990
23991     /* If the objfile does not correspond to an actual file, skip it.  */
23992     if (stat (objfile_name (objfile), &st) < 0)
23993       continue;
23994
23995     dwarf2_per_objfile
23996       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23997                                                     dwarf2_objfile_data_key);
23998     if (dwarf2_per_objfile)
23999       {
24000
24001         TRY
24002           {
24003             write_psymtabs_to_index (objfile, arg);
24004           }
24005         CATCH (except, RETURN_MASK_ERROR)
24006           {
24007             exception_fprintf (gdb_stderr, except,
24008                                _("Error while writing index for `%s': "),
24009                                objfile_name (objfile));
24010           }
24011         END_CATCH
24012       }
24013   }
24014 }
24015
24016 \f
24017
24018 int dwarf_always_disassemble;
24019
24020 static void
24021 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24022                                struct cmd_list_element *c, const char *value)
24023 {
24024   fprintf_filtered (file,
24025                     _("Whether to always disassemble "
24026                       "DWARF expressions is %s.\n"),
24027                     value);
24028 }
24029
24030 static void
24031 show_check_physname (struct ui_file *file, int from_tty,
24032                      struct cmd_list_element *c, const char *value)
24033 {
24034   fprintf_filtered (file,
24035                     _("Whether to check \"physname\" is %s.\n"),
24036                     value);
24037 }
24038
24039 void
24040 _initialize_dwarf2_read (void)
24041 {
24042   struct cmd_list_element *c;
24043
24044   dwarf2_objfile_data_key
24045     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24046
24047   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24048 Set DWARF specific variables.\n\
24049 Configure DWARF variables such as the cache size"),
24050                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24051                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24052
24053   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24054 Show DWARF specific variables\n\
24055 Show DWARF variables such as the cache size"),
24056                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24057                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24058
24059   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24060                             &dwarf_max_cache_age, _("\
24061 Set the upper bound on the age of cached DWARF compilation units."), _("\
24062 Show the upper bound on the age of cached DWARF compilation units."), _("\
24063 A higher limit means that cached compilation units will be stored\n\
24064 in memory longer, and more total memory will be used.  Zero disables\n\
24065 caching, which can slow down startup."),
24066                             NULL,
24067                             show_dwarf_max_cache_age,
24068                             &set_dwarf_cmdlist,
24069                             &show_dwarf_cmdlist);
24070
24071   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24072                            &dwarf_always_disassemble, _("\
24073 Set whether `info address' always disassembles DWARF expressions."), _("\
24074 Show whether `info address' always disassembles DWARF expressions."), _("\
24075 When enabled, DWARF expressions are always printed in an assembly-like\n\
24076 syntax.  When disabled, expressions will be printed in a more\n\
24077 conversational style, when possible."),
24078                            NULL,
24079                            show_dwarf_always_disassemble,
24080                            &set_dwarf_cmdlist,
24081                            &show_dwarf_cmdlist);
24082
24083   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24084 Set debugging of the DWARF reader."), _("\
24085 Show debugging of the DWARF reader."), _("\
24086 When enabled (non-zero), debugging messages are printed during DWARF\n\
24087 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24088 information.  A value greater than 1 provides more verbose information."),
24089                             NULL,
24090                             NULL,
24091                             &setdebuglist, &showdebuglist);
24092
24093   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24094 Set debugging of the DWARF DIE reader."), _("\
24095 Show debugging of the DWARF DIE reader."), _("\
24096 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24097 The value is the maximum depth to print."),
24098                              NULL,
24099                              NULL,
24100                              &setdebuglist, &showdebuglist);
24101
24102   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24103 Set debugging of the dwarf line reader."), _("\
24104 Show debugging of the dwarf line reader."), _("\
24105 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24106 A value of 1 (one) provides basic information.\n\
24107 A value greater than 1 provides more verbose information."),
24108                              NULL,
24109                              NULL,
24110                              &setdebuglist, &showdebuglist);
24111
24112   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24113 Set cross-checking of \"physname\" code against demangler."), _("\
24114 Show cross-checking of \"physname\" code against demangler."), _("\
24115 When enabled, GDB's internal \"physname\" code is checked against\n\
24116 the demangler."),
24117                            NULL, show_check_physname,
24118                            &setdebuglist, &showdebuglist);
24119
24120   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24121                            no_class, &use_deprecated_index_sections, _("\
24122 Set whether to use deprecated gdb_index sections."), _("\
24123 Show whether to use deprecated gdb_index sections."), _("\
24124 When enabled, deprecated .gdb_index sections are used anyway.\n\
24125 Normally they are ignored either because of a missing feature or\n\
24126 performance issue.\n\
24127 Warning: This option must be enabled before gdb reads the file."),
24128                            NULL,
24129                            NULL,
24130                            &setlist, &showlist);
24131
24132   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24133                _("\
24134 Save a gdb-index file.\n\
24135 Usage: save gdb-index DIRECTORY"),
24136                &save_cmdlist);
24137   set_cmd_completer (c, filename_completer);
24138
24139   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24140                                                         &dwarf2_locexpr_funcs);
24141   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24142                                                         &dwarf2_loclist_funcs);
24143
24144   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24145                                         &dwarf2_block_frame_base_locexpr_funcs);
24146   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24147                                         &dwarf2_block_frame_base_loclist_funcs);
24148 }