Constify add_prefix_cmd
[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.size == 0 && objfile->static_psymbols.size == 0)
4460     {
4461       init_psymbol_list (objfile, 1024);
4462     }
4463
4464   TRY
4465     {
4466       /* This isn't really ideal: all the data we allocate on the
4467          objfile's obstack is still uselessly kept around.  However,
4468          freeing it seems unsafe.  */
4469       psymtab_discarder psymtabs (objfile);
4470       dwarf2_build_psymtabs_hard (objfile);
4471       psymtabs.keep ();
4472     }
4473   CATCH (except, RETURN_MASK_ERROR)
4474     {
4475       exception_print (gdb_stderr, except);
4476     }
4477   END_CATCH
4478 }
4479
4480 /* Return the total length of the CU described by HEADER.  */
4481
4482 static unsigned int
4483 get_cu_length (const struct comp_unit_head *header)
4484 {
4485   return header->initial_length_size + header->length;
4486 }
4487
4488 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4489
4490 static inline bool
4491 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4492 {
4493   sect_offset bottom = cu_header->sect_off;
4494   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4495
4496   return sect_off >= bottom && sect_off < top;
4497 }
4498
4499 /* Find the base address of the compilation unit for range lists and
4500    location lists.  It will normally be specified by DW_AT_low_pc.
4501    In DWARF-3 draft 4, the base address could be overridden by
4502    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4503    compilation units with discontinuous ranges.  */
4504
4505 static void
4506 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4507 {
4508   struct attribute *attr;
4509
4510   cu->base_known = 0;
4511   cu->base_address = 0;
4512
4513   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4514   if (attr)
4515     {
4516       cu->base_address = attr_value_as_address (attr);
4517       cu->base_known = 1;
4518     }
4519   else
4520     {
4521       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4522       if (attr)
4523         {
4524           cu->base_address = attr_value_as_address (attr);
4525           cu->base_known = 1;
4526         }
4527     }
4528 }
4529
4530 /* Read in the comp unit header information from the debug_info at info_ptr.
4531    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4532    NOTE: This leaves members offset, first_die_offset to be filled in
4533    by the caller.  */
4534
4535 static const gdb_byte *
4536 read_comp_unit_head (struct comp_unit_head *cu_header,
4537                      const gdb_byte *info_ptr,
4538                      struct dwarf2_section_info *section,
4539                      rcuh_kind section_kind)
4540 {
4541   int signed_addr;
4542   unsigned int bytes_read;
4543   const char *filename = get_section_file_name (section);
4544   bfd *abfd = get_section_bfd_owner (section);
4545
4546   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4547   cu_header->initial_length_size = bytes_read;
4548   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4549   info_ptr += bytes_read;
4550   cu_header->version = read_2_bytes (abfd, info_ptr);
4551   info_ptr += 2;
4552   if (cu_header->version < 5)
4553     switch (section_kind)
4554       {
4555       case rcuh_kind::COMPILE:
4556         cu_header->unit_type = DW_UT_compile;
4557         break;
4558       case rcuh_kind::TYPE:
4559         cu_header->unit_type = DW_UT_type;
4560         break;
4561       default:
4562         internal_error (__FILE__, __LINE__,
4563                         _("read_comp_unit_head: invalid section_kind"));
4564       }
4565   else
4566     {
4567       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4568                                                  (read_1_byte (abfd, info_ptr));
4569       info_ptr += 1;
4570       switch (cu_header->unit_type)
4571         {
4572         case DW_UT_compile:
4573           if (section_kind != rcuh_kind::COMPILE)
4574             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4575                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4576                    filename);
4577           break;
4578         case DW_UT_type:
4579           section_kind = rcuh_kind::TYPE;
4580           break;
4581         default:
4582           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4583                  "(is %d, should be %d or %d) [in module %s]"),
4584                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4585         }
4586
4587       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4588       info_ptr += 1;
4589     }
4590   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4591                                                           cu_header,
4592                                                           &bytes_read);
4593   info_ptr += bytes_read;
4594   if (cu_header->version < 5)
4595     {
4596       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4597       info_ptr += 1;
4598     }
4599   signed_addr = bfd_get_sign_extend_vma (abfd);
4600   if (signed_addr < 0)
4601     internal_error (__FILE__, __LINE__,
4602                     _("read_comp_unit_head: dwarf from non elf file"));
4603   cu_header->signed_addr_p = signed_addr;
4604
4605   if (section_kind == rcuh_kind::TYPE)
4606     {
4607       LONGEST type_offset;
4608
4609       cu_header->signature = read_8_bytes (abfd, info_ptr);
4610       info_ptr += 8;
4611
4612       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4613       info_ptr += bytes_read;
4614       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4615       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4616         error (_("Dwarf Error: Too big type_offset in compilation unit "
4617                "header (is %s) [in module %s]"), plongest (type_offset),
4618                filename);
4619     }
4620
4621   return info_ptr;
4622 }
4623
4624 /* Helper function that returns the proper abbrev section for
4625    THIS_CU.  */
4626
4627 static struct dwarf2_section_info *
4628 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4629 {
4630   struct dwarf2_section_info *abbrev;
4631
4632   if (this_cu->is_dwz)
4633     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4634   else
4635     abbrev = &dwarf2_per_objfile->abbrev;
4636
4637   return abbrev;
4638 }
4639
4640 /* Subroutine of read_and_check_comp_unit_head and
4641    read_and_check_type_unit_head to simplify them.
4642    Perform various error checking on the header.  */
4643
4644 static void
4645 error_check_comp_unit_head (struct comp_unit_head *header,
4646                             struct dwarf2_section_info *section,
4647                             struct dwarf2_section_info *abbrev_section)
4648 {
4649   const char *filename = get_section_file_name (section);
4650
4651   if (header->version < 2 || header->version > 5)
4652     error (_("Dwarf Error: wrong version in compilation unit header "
4653            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4654            filename);
4655
4656   if (to_underlying (header->abbrev_sect_off)
4657       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4658     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4659            "(offset 0x%x + 6) [in module %s]"),
4660            to_underlying (header->abbrev_sect_off),
4661            to_underlying (header->sect_off),
4662            filename);
4663
4664   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4665      avoid potential 32-bit overflow.  */
4666   if (((ULONGEST) header->sect_off + get_cu_length (header))
4667       > section->size)
4668     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4669            "(offset 0x%x + 0) [in module %s]"),
4670            header->length, to_underlying (header->sect_off),
4671            filename);
4672 }
4673
4674 /* Read in a CU/TU header and perform some basic error checking.
4675    The contents of the header are stored in HEADER.
4676    The result is a pointer to the start of the first DIE.  */
4677
4678 static const gdb_byte *
4679 read_and_check_comp_unit_head (struct comp_unit_head *header,
4680                                struct dwarf2_section_info *section,
4681                                struct dwarf2_section_info *abbrev_section,
4682                                const gdb_byte *info_ptr,
4683                                rcuh_kind section_kind)
4684 {
4685   const gdb_byte *beg_of_comp_unit = info_ptr;
4686   bfd *abfd = get_section_bfd_owner (section);
4687
4688   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4689
4690   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4691
4692   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
4693
4694   error_check_comp_unit_head (header, section, abbrev_section);
4695
4696   return info_ptr;
4697 }
4698
4699 /* Fetch the abbreviation table offset from a comp or type unit header.  */
4700
4701 static sect_offset
4702 read_abbrev_offset (struct dwarf2_section_info *section,
4703                     sect_offset sect_off)
4704 {
4705   bfd *abfd = get_section_bfd_owner (section);
4706   const gdb_byte *info_ptr;
4707   unsigned int initial_length_size, offset_size;
4708   uint16_t version;
4709
4710   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
4711   info_ptr = section->buffer + to_underlying (sect_off);
4712   read_initial_length (abfd, info_ptr, &initial_length_size);
4713   offset_size = initial_length_size == 4 ? 4 : 8;
4714   info_ptr += initial_length_size;
4715
4716   version = read_2_bytes (abfd, info_ptr);
4717   info_ptr += 2;
4718   if (version >= 5)
4719     {
4720       /* Skip unit type and address size.  */
4721       info_ptr += 2;
4722     }
4723
4724   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
4725 }
4726
4727 /* Allocate a new partial symtab for file named NAME and mark this new
4728    partial symtab as being an include of PST.  */
4729
4730 static void
4731 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
4732                                struct objfile *objfile)
4733 {
4734   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
4735
4736   if (!IS_ABSOLUTE_PATH (subpst->filename))
4737     {
4738       /* It shares objfile->objfile_obstack.  */
4739       subpst->dirname = pst->dirname;
4740     }
4741
4742   subpst->textlow = 0;
4743   subpst->texthigh = 0;
4744
4745   subpst->dependencies
4746     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
4747   subpst->dependencies[0] = pst;
4748   subpst->number_of_dependencies = 1;
4749
4750   subpst->globals_offset = 0;
4751   subpst->n_global_syms = 0;
4752   subpst->statics_offset = 0;
4753   subpst->n_static_syms = 0;
4754   subpst->compunit_symtab = NULL;
4755   subpst->read_symtab = pst->read_symtab;
4756   subpst->readin = 0;
4757
4758   /* No private part is necessary for include psymtabs.  This property
4759      can be used to differentiate between such include psymtabs and
4760      the regular ones.  */
4761   subpst->read_symtab_private = NULL;
4762 }
4763
4764 /* Read the Line Number Program data and extract the list of files
4765    included by the source file represented by PST.  Build an include
4766    partial symtab for each of these included files.  */
4767
4768 static void
4769 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
4770                                struct die_info *die,
4771                                struct partial_symtab *pst)
4772 {
4773   line_header_up lh;
4774   struct attribute *attr;
4775
4776   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
4777   if (attr)
4778     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
4779   if (lh == NULL)
4780     return;  /* No linetable, so no includes.  */
4781
4782   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
4783   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
4784 }
4785
4786 static hashval_t
4787 hash_signatured_type (const void *item)
4788 {
4789   const struct signatured_type *sig_type
4790     = (const struct signatured_type *) item;
4791
4792   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
4793   return sig_type->signature;
4794 }
4795
4796 static int
4797 eq_signatured_type (const void *item_lhs, const void *item_rhs)
4798 {
4799   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
4800   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
4801
4802   return lhs->signature == rhs->signature;
4803 }
4804
4805 /* Allocate a hash table for signatured types.  */
4806
4807 static htab_t
4808 allocate_signatured_type_table (struct objfile *objfile)
4809 {
4810   return htab_create_alloc_ex (41,
4811                                hash_signatured_type,
4812                                eq_signatured_type,
4813                                NULL,
4814                                &objfile->objfile_obstack,
4815                                hashtab_obstack_allocate,
4816                                dummy_obstack_deallocate);
4817 }
4818
4819 /* A helper function to add a signatured type CU to a table.  */
4820
4821 static int
4822 add_signatured_type_cu_to_table (void **slot, void *datum)
4823 {
4824   struct signatured_type *sigt = (struct signatured_type *) *slot;
4825   struct signatured_type ***datap = (struct signatured_type ***) datum;
4826
4827   **datap = sigt;
4828   ++*datap;
4829
4830   return 1;
4831 }
4832
4833 /* A helper for create_debug_types_hash_table.  Read types from SECTION
4834    and fill them into TYPES_HTAB.  It will process only type units,
4835    therefore DW_UT_type.  */
4836
4837 static void
4838 create_debug_type_hash_table (struct dwo_file *dwo_file,
4839                               dwarf2_section_info *section, htab_t &types_htab,
4840                               rcuh_kind section_kind)
4841 {
4842   struct objfile *objfile = dwarf2_per_objfile->objfile;
4843   struct dwarf2_section_info *abbrev_section;
4844   bfd *abfd;
4845   const gdb_byte *info_ptr, *end_ptr;
4846
4847   abbrev_section = (dwo_file != NULL
4848                     ? &dwo_file->sections.abbrev
4849                     : &dwarf2_per_objfile->abbrev);
4850
4851   if (dwarf_read_debug)
4852     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
4853                         get_section_name (section),
4854                         get_section_file_name (abbrev_section));
4855
4856   dwarf2_read_section (objfile, section);
4857   info_ptr = section->buffer;
4858
4859   if (info_ptr == NULL)
4860     return;
4861
4862   /* We can't set abfd until now because the section may be empty or
4863      not present, in which case the bfd is unknown.  */
4864   abfd = get_section_bfd_owner (section);
4865
4866   /* We don't use init_cutu_and_read_dies_simple, or some such, here
4867      because we don't need to read any dies: the signature is in the
4868      header.  */
4869
4870   end_ptr = info_ptr + section->size;
4871   while (info_ptr < end_ptr)
4872     {
4873       struct signatured_type *sig_type;
4874       struct dwo_unit *dwo_tu;
4875       void **slot;
4876       const gdb_byte *ptr = info_ptr;
4877       struct comp_unit_head header;
4878       unsigned int length;
4879
4880       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
4881
4882       /* Initialize it due to a false compiler warning.  */
4883       header.signature = -1;
4884       header.type_cu_offset_in_tu = (cu_offset) -1;
4885
4886       /* We need to read the type's signature in order to build the hash
4887          table, but we don't need anything else just yet.  */
4888
4889       ptr = read_and_check_comp_unit_head (&header, section,
4890                                            abbrev_section, ptr, section_kind);
4891
4892       length = get_cu_length (&header);
4893
4894       /* Skip dummy type units.  */
4895       if (ptr >= info_ptr + length
4896           || peek_abbrev_code (abfd, ptr) == 0
4897           || header.unit_type != DW_UT_type)
4898         {
4899           info_ptr += length;
4900           continue;
4901         }
4902
4903       if (types_htab == NULL)
4904         {
4905           if (dwo_file)
4906             types_htab = allocate_dwo_unit_table (objfile);
4907           else
4908             types_htab = allocate_signatured_type_table (objfile);
4909         }
4910
4911       if (dwo_file)
4912         {
4913           sig_type = NULL;
4914           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4915                                    struct dwo_unit);
4916           dwo_tu->dwo_file = dwo_file;
4917           dwo_tu->signature = header.signature;
4918           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
4919           dwo_tu->section = section;
4920           dwo_tu->sect_off = sect_off;
4921           dwo_tu->length = length;
4922         }
4923       else
4924         {
4925           /* N.B.: type_offset is not usable if this type uses a DWO file.
4926              The real type_offset is in the DWO file.  */
4927           dwo_tu = NULL;
4928           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4929                                      struct signatured_type);
4930           sig_type->signature = header.signature;
4931           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
4932           sig_type->per_cu.objfile = objfile;
4933           sig_type->per_cu.is_debug_types = 1;
4934           sig_type->per_cu.section = section;
4935           sig_type->per_cu.sect_off = sect_off;
4936           sig_type->per_cu.length = length;
4937         }
4938
4939       slot = htab_find_slot (types_htab,
4940                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
4941                              INSERT);
4942       gdb_assert (slot != NULL);
4943       if (*slot != NULL)
4944         {
4945           sect_offset dup_sect_off;
4946
4947           if (dwo_file)
4948             {
4949               const struct dwo_unit *dup_tu
4950                 = (const struct dwo_unit *) *slot;
4951
4952               dup_sect_off = dup_tu->sect_off;
4953             }
4954           else
4955             {
4956               const struct signatured_type *dup_tu
4957                 = (const struct signatured_type *) *slot;
4958
4959               dup_sect_off = dup_tu->per_cu.sect_off;
4960             }
4961
4962           complaint (&symfile_complaints,
4963                      _("debug type entry at offset 0x%x is duplicate to"
4964                        " the entry at offset 0x%x, signature %s"),
4965                      to_underlying (sect_off), to_underlying (dup_sect_off),
4966                      hex_string (header.signature));
4967         }
4968       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
4969
4970       if (dwarf_read_debug > 1)
4971         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
4972                             to_underlying (sect_off),
4973                             hex_string (header.signature));
4974
4975       info_ptr += length;
4976     }
4977 }
4978
4979 /* Create the hash table of all entries in the .debug_types
4980    (or .debug_types.dwo) section(s).
4981    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
4982    otherwise it is NULL.
4983
4984    The result is a pointer to the hash table or NULL if there are no types.
4985
4986    Note: This function processes DWO files only, not DWP files.  */
4987
4988 static void
4989 create_debug_types_hash_table (struct dwo_file *dwo_file,
4990                                VEC (dwarf2_section_info_def) *types,
4991                                htab_t &types_htab)
4992 {
4993   int ix;
4994   struct dwarf2_section_info *section;
4995
4996   if (VEC_empty (dwarf2_section_info_def, types))
4997     return;
4998
4999   for (ix = 0;
5000        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5001        ++ix)
5002     create_debug_type_hash_table (dwo_file, section, types_htab,
5003                                   rcuh_kind::TYPE);
5004 }
5005
5006 /* Create the hash table of all entries in the .debug_types section,
5007    and initialize all_type_units.
5008    The result is zero if there is an error (e.g. missing .debug_types section),
5009    otherwise non-zero.  */
5010
5011 static int
5012 create_all_type_units (struct objfile *objfile)
5013 {
5014   htab_t types_htab = NULL;
5015   struct signatured_type **iter;
5016
5017   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5018                                 rcuh_kind::COMPILE);
5019   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5020   if (types_htab == NULL)
5021     {
5022       dwarf2_per_objfile->signatured_types = NULL;
5023       return 0;
5024     }
5025
5026   dwarf2_per_objfile->signatured_types = types_htab;
5027
5028   dwarf2_per_objfile->n_type_units
5029     = dwarf2_per_objfile->n_allocated_type_units
5030     = htab_elements (types_htab);
5031   dwarf2_per_objfile->all_type_units =
5032     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5033   iter = &dwarf2_per_objfile->all_type_units[0];
5034   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5035   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5036               == dwarf2_per_objfile->n_type_units);
5037
5038   return 1;
5039 }
5040
5041 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5042    If SLOT is non-NULL, it is the entry to use in the hash table.
5043    Otherwise we find one.  */
5044
5045 static struct signatured_type *
5046 add_type_unit (ULONGEST sig, void **slot)
5047 {
5048   struct objfile *objfile = dwarf2_per_objfile->objfile;
5049   int n_type_units = dwarf2_per_objfile->n_type_units;
5050   struct signatured_type *sig_type;
5051
5052   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5053   ++n_type_units;
5054   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5055     {
5056       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5057         dwarf2_per_objfile->n_allocated_type_units = 1;
5058       dwarf2_per_objfile->n_allocated_type_units *= 2;
5059       dwarf2_per_objfile->all_type_units
5060         = XRESIZEVEC (struct signatured_type *,
5061                       dwarf2_per_objfile->all_type_units,
5062                       dwarf2_per_objfile->n_allocated_type_units);
5063       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5064     }
5065   dwarf2_per_objfile->n_type_units = n_type_units;
5066
5067   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5068                              struct signatured_type);
5069   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5070   sig_type->signature = sig;
5071   sig_type->per_cu.is_debug_types = 1;
5072   if (dwarf2_per_objfile->using_index)
5073     {
5074       sig_type->per_cu.v.quick =
5075         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5076                         struct dwarf2_per_cu_quick_data);
5077     }
5078
5079   if (slot == NULL)
5080     {
5081       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5082                              sig_type, INSERT);
5083     }
5084   gdb_assert (*slot == NULL);
5085   *slot = sig_type;
5086   /* The rest of sig_type must be filled in by the caller.  */
5087   return sig_type;
5088 }
5089
5090 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5091    Fill in SIG_ENTRY with DWO_ENTRY.  */
5092
5093 static void
5094 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5095                                   struct signatured_type *sig_entry,
5096                                   struct dwo_unit *dwo_entry)
5097 {
5098   /* Make sure we're not clobbering something we don't expect to.  */
5099   gdb_assert (! sig_entry->per_cu.queued);
5100   gdb_assert (sig_entry->per_cu.cu == NULL);
5101   if (dwarf2_per_objfile->using_index)
5102     {
5103       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5104       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5105     }
5106   else
5107       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5108   gdb_assert (sig_entry->signature == dwo_entry->signature);
5109   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5110   gdb_assert (sig_entry->type_unit_group == NULL);
5111   gdb_assert (sig_entry->dwo_unit == NULL);
5112
5113   sig_entry->per_cu.section = dwo_entry->section;
5114   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5115   sig_entry->per_cu.length = dwo_entry->length;
5116   sig_entry->per_cu.reading_dwo_directly = 1;
5117   sig_entry->per_cu.objfile = objfile;
5118   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5119   sig_entry->dwo_unit = dwo_entry;
5120 }
5121
5122 /* Subroutine of lookup_signatured_type.
5123    If we haven't read the TU yet, create the signatured_type data structure
5124    for a TU to be read in directly from a DWO file, bypassing the stub.
5125    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5126    using .gdb_index, then when reading a CU we want to stay in the DWO file
5127    containing that CU.  Otherwise we could end up reading several other DWO
5128    files (due to comdat folding) to process the transitive closure of all the
5129    mentioned TUs, and that can be slow.  The current DWO file will have every
5130    type signature that it needs.
5131    We only do this for .gdb_index because in the psymtab case we already have
5132    to read all the DWOs to build the type unit groups.  */
5133
5134 static struct signatured_type *
5135 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5136 {
5137   struct objfile *objfile = dwarf2_per_objfile->objfile;
5138   struct dwo_file *dwo_file;
5139   struct dwo_unit find_dwo_entry, *dwo_entry;
5140   struct signatured_type find_sig_entry, *sig_entry;
5141   void **slot;
5142
5143   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5144
5145   /* If TU skeletons have been removed then we may not have read in any
5146      TUs yet.  */
5147   if (dwarf2_per_objfile->signatured_types == NULL)
5148     {
5149       dwarf2_per_objfile->signatured_types
5150         = allocate_signatured_type_table (objfile);
5151     }
5152
5153   /* We only ever need to read in one copy of a signatured type.
5154      Use the global signatured_types array to do our own comdat-folding
5155      of types.  If this is the first time we're reading this TU, and
5156      the TU has an entry in .gdb_index, replace the recorded data from
5157      .gdb_index with this TU.  */
5158
5159   find_sig_entry.signature = sig;
5160   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5161                          &find_sig_entry, INSERT);
5162   sig_entry = (struct signatured_type *) *slot;
5163
5164   /* We can get here with the TU already read, *or* in the process of being
5165      read.  Don't reassign the global entry to point to this DWO if that's
5166      the case.  Also note that if the TU is already being read, it may not
5167      have come from a DWO, the program may be a mix of Fission-compiled
5168      code and non-Fission-compiled code.  */
5169
5170   /* Have we already tried to read this TU?
5171      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5172      needn't exist in the global table yet).  */
5173   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5174     return sig_entry;
5175
5176   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5177      dwo_unit of the TU itself.  */
5178   dwo_file = cu->dwo_unit->dwo_file;
5179
5180   /* Ok, this is the first time we're reading this TU.  */
5181   if (dwo_file->tus == NULL)
5182     return NULL;
5183   find_dwo_entry.signature = sig;
5184   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5185   if (dwo_entry == NULL)
5186     return NULL;
5187
5188   /* If the global table doesn't have an entry for this TU, add one.  */
5189   if (sig_entry == NULL)
5190     sig_entry = add_type_unit (sig, slot);
5191
5192   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5193   sig_entry->per_cu.tu_read = 1;
5194   return sig_entry;
5195 }
5196
5197 /* Subroutine of lookup_signatured_type.
5198    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5199    then try the DWP file.  If the TU stub (skeleton) has been removed then
5200    it won't be in .gdb_index.  */
5201
5202 static struct signatured_type *
5203 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5204 {
5205   struct objfile *objfile = dwarf2_per_objfile->objfile;
5206   struct dwp_file *dwp_file = get_dwp_file ();
5207   struct dwo_unit *dwo_entry;
5208   struct signatured_type find_sig_entry, *sig_entry;
5209   void **slot;
5210
5211   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5212   gdb_assert (dwp_file != NULL);
5213
5214   /* If TU skeletons have been removed then we may not have read in any
5215      TUs yet.  */
5216   if (dwarf2_per_objfile->signatured_types == NULL)
5217     {
5218       dwarf2_per_objfile->signatured_types
5219         = allocate_signatured_type_table (objfile);
5220     }
5221
5222   find_sig_entry.signature = sig;
5223   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5224                          &find_sig_entry, INSERT);
5225   sig_entry = (struct signatured_type *) *slot;
5226
5227   /* Have we already tried to read this TU?
5228      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5229      needn't exist in the global table yet).  */
5230   if (sig_entry != NULL)
5231     return sig_entry;
5232
5233   if (dwp_file->tus == NULL)
5234     return NULL;
5235   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5236                                       sig, 1 /* is_debug_types */);
5237   if (dwo_entry == NULL)
5238     return NULL;
5239
5240   sig_entry = add_type_unit (sig, slot);
5241   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5242
5243   return sig_entry;
5244 }
5245
5246 /* Lookup a signature based type for DW_FORM_ref_sig8.
5247    Returns NULL if signature SIG is not present in the table.
5248    It is up to the caller to complain about this.  */
5249
5250 static struct signatured_type *
5251 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5252 {
5253   if (cu->dwo_unit
5254       && dwarf2_per_objfile->using_index)
5255     {
5256       /* We're in a DWO/DWP file, and we're using .gdb_index.
5257          These cases require special processing.  */
5258       if (get_dwp_file () == NULL)
5259         return lookup_dwo_signatured_type (cu, sig);
5260       else
5261         return lookup_dwp_signatured_type (cu, sig);
5262     }
5263   else
5264     {
5265       struct signatured_type find_entry, *entry;
5266
5267       if (dwarf2_per_objfile->signatured_types == NULL)
5268         return NULL;
5269       find_entry.signature = sig;
5270       entry = ((struct signatured_type *)
5271                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5272       return entry;
5273     }
5274 }
5275 \f
5276 /* Low level DIE reading support.  */
5277
5278 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5279
5280 static void
5281 init_cu_die_reader (struct die_reader_specs *reader,
5282                     struct dwarf2_cu *cu,
5283                     struct dwarf2_section_info *section,
5284                     struct dwo_file *dwo_file)
5285 {
5286   gdb_assert (section->readin && section->buffer != NULL);
5287   reader->abfd = get_section_bfd_owner (section);
5288   reader->cu = cu;
5289   reader->dwo_file = dwo_file;
5290   reader->die_section = section;
5291   reader->buffer = section->buffer;
5292   reader->buffer_end = section->buffer + section->size;
5293   reader->comp_dir = NULL;
5294 }
5295
5296 /* Subroutine of init_cutu_and_read_dies to simplify it.
5297    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5298    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5299    already.
5300
5301    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5302    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5303    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5304    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5305    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5306    STUB_COMP_DIR may be non-NULL.
5307    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5308    are filled in with the info of the DIE from the DWO file.
5309    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5310    provided an abbrev table to use.
5311    The result is non-zero if a valid (non-dummy) DIE was found.  */
5312
5313 static int
5314 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5315                         struct dwo_unit *dwo_unit,
5316                         int abbrev_table_provided,
5317                         struct die_info *stub_comp_unit_die,
5318                         const char *stub_comp_dir,
5319                         struct die_reader_specs *result_reader,
5320                         const gdb_byte **result_info_ptr,
5321                         struct die_info **result_comp_unit_die,
5322                         int *result_has_children)
5323 {
5324   struct objfile *objfile = dwarf2_per_objfile->objfile;
5325   struct dwarf2_cu *cu = this_cu->cu;
5326   struct dwarf2_section_info *section;
5327   bfd *abfd;
5328   const gdb_byte *begin_info_ptr, *info_ptr;
5329   ULONGEST signature; /* Or dwo_id.  */
5330   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5331   int i,num_extra_attrs;
5332   struct dwarf2_section_info *dwo_abbrev_section;
5333   struct attribute *attr;
5334   struct die_info *comp_unit_die;
5335
5336   /* At most one of these may be provided.  */
5337   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5338
5339   /* These attributes aren't processed until later:
5340      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5341      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5342      referenced later.  However, these attributes are found in the stub
5343      which we won't have later.  In order to not impose this complication
5344      on the rest of the code, we read them here and copy them to the
5345      DWO CU/TU die.  */
5346
5347   stmt_list = NULL;
5348   low_pc = NULL;
5349   high_pc = NULL;
5350   ranges = NULL;
5351   comp_dir = NULL;
5352
5353   if (stub_comp_unit_die != NULL)
5354     {
5355       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5356          DWO file.  */
5357       if (! this_cu->is_debug_types)
5358         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5359       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5360       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5361       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5362       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5363
5364       /* There should be a DW_AT_addr_base attribute here (if needed).
5365          We need the value before we can process DW_FORM_GNU_addr_index.  */
5366       cu->addr_base = 0;
5367       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5368       if (attr)
5369         cu->addr_base = DW_UNSND (attr);
5370
5371       /* There should be a DW_AT_ranges_base attribute here (if needed).
5372          We need the value before we can process DW_AT_ranges.  */
5373       cu->ranges_base = 0;
5374       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5375       if (attr)
5376         cu->ranges_base = DW_UNSND (attr);
5377     }
5378   else if (stub_comp_dir != NULL)
5379     {
5380       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5381       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5382       comp_dir->name = DW_AT_comp_dir;
5383       comp_dir->form = DW_FORM_string;
5384       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5385       DW_STRING (comp_dir) = stub_comp_dir;
5386     }
5387
5388   /* Set up for reading the DWO CU/TU.  */
5389   cu->dwo_unit = dwo_unit;
5390   section = dwo_unit->section;
5391   dwarf2_read_section (objfile, section);
5392   abfd = get_section_bfd_owner (section);
5393   begin_info_ptr = info_ptr = (section->buffer
5394                                + to_underlying (dwo_unit->sect_off));
5395   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5396   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5397
5398   if (this_cu->is_debug_types)
5399     {
5400       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5401
5402       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5403                                                 dwo_abbrev_section,
5404                                                 info_ptr, rcuh_kind::TYPE);
5405       /* This is not an assert because it can be caused by bad debug info.  */
5406       if (sig_type->signature != cu->header.signature)
5407         {
5408           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5409                    " TU at offset 0x%x [in module %s]"),
5410                  hex_string (sig_type->signature),
5411                  hex_string (cu->header.signature),
5412                  to_underlying (dwo_unit->sect_off),
5413                  bfd_get_filename (abfd));
5414         }
5415       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5416       /* For DWOs coming from DWP files, we don't know the CU length
5417          nor the type's offset in the TU until now.  */
5418       dwo_unit->length = get_cu_length (&cu->header);
5419       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5420
5421       /* Establish the type offset that can be used to lookup the type.
5422          For DWO files, we don't know it until now.  */
5423       sig_type->type_offset_in_section
5424         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5425     }
5426   else
5427     {
5428       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5429                                                 dwo_abbrev_section,
5430                                                 info_ptr, rcuh_kind::COMPILE);
5431       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5432       /* For DWOs coming from DWP files, we don't know the CU length
5433          until now.  */
5434       dwo_unit->length = get_cu_length (&cu->header);
5435     }
5436
5437   /* Replace the CU's original abbrev table with the DWO's.
5438      Reminder: We can't read the abbrev table until we've read the header.  */
5439   if (abbrev_table_provided)
5440     {
5441       /* Don't free the provided abbrev table, the caller of
5442          init_cutu_and_read_dies owns it.  */
5443       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5444       /* Ensure the DWO abbrev table gets freed.  */
5445       make_cleanup (dwarf2_free_abbrev_table, cu);
5446     }
5447   else
5448     {
5449       dwarf2_free_abbrev_table (cu);
5450       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5451       /* Leave any existing abbrev table cleanup as is.  */
5452     }
5453
5454   /* Read in the die, but leave space to copy over the attributes
5455      from the stub.  This has the benefit of simplifying the rest of
5456      the code - all the work to maintain the illusion of a single
5457      DW_TAG_{compile,type}_unit DIE is done here.  */
5458   num_extra_attrs = ((stmt_list != NULL)
5459                      + (low_pc != NULL)
5460                      + (high_pc != NULL)
5461                      + (ranges != NULL)
5462                      + (comp_dir != NULL));
5463   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5464                               result_has_children, num_extra_attrs);
5465
5466   /* Copy over the attributes from the stub to the DIE we just read in.  */
5467   comp_unit_die = *result_comp_unit_die;
5468   i = comp_unit_die->num_attrs;
5469   if (stmt_list != NULL)
5470     comp_unit_die->attrs[i++] = *stmt_list;
5471   if (low_pc != NULL)
5472     comp_unit_die->attrs[i++] = *low_pc;
5473   if (high_pc != NULL)
5474     comp_unit_die->attrs[i++] = *high_pc;
5475   if (ranges != NULL)
5476     comp_unit_die->attrs[i++] = *ranges;
5477   if (comp_dir != NULL)
5478     comp_unit_die->attrs[i++] = *comp_dir;
5479   comp_unit_die->num_attrs += num_extra_attrs;
5480
5481   if (dwarf_die_debug)
5482     {
5483       fprintf_unfiltered (gdb_stdlog,
5484                           "Read die from %s@0x%x of %s:\n",
5485                           get_section_name (section),
5486                           (unsigned) (begin_info_ptr - section->buffer),
5487                           bfd_get_filename (abfd));
5488       dump_die (comp_unit_die, dwarf_die_debug);
5489     }
5490
5491   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5492      TUs by skipping the stub and going directly to the entry in the DWO file.
5493      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5494      to get it via circuitous means.  Blech.  */
5495   if (comp_dir != NULL)
5496     result_reader->comp_dir = DW_STRING (comp_dir);
5497
5498   /* Skip dummy compilation units.  */
5499   if (info_ptr >= begin_info_ptr + dwo_unit->length
5500       || peek_abbrev_code (abfd, info_ptr) == 0)
5501     return 0;
5502
5503   *result_info_ptr = info_ptr;
5504   return 1;
5505 }
5506
5507 /* Subroutine of init_cutu_and_read_dies to simplify it.
5508    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5509    Returns NULL if the specified DWO unit cannot be found.  */
5510
5511 static struct dwo_unit *
5512 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5513                  struct die_info *comp_unit_die)
5514 {
5515   struct dwarf2_cu *cu = this_cu->cu;
5516   struct attribute *attr;
5517   ULONGEST signature;
5518   struct dwo_unit *dwo_unit;
5519   const char *comp_dir, *dwo_name;
5520
5521   gdb_assert (cu != NULL);
5522
5523   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5524   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5525   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5526
5527   if (this_cu->is_debug_types)
5528     {
5529       struct signatured_type *sig_type;
5530
5531       /* Since this_cu is the first member of struct signatured_type,
5532          we can go from a pointer to one to a pointer to the other.  */
5533       sig_type = (struct signatured_type *) this_cu;
5534       signature = sig_type->signature;
5535       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5536     }
5537   else
5538     {
5539       struct attribute *attr;
5540
5541       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5542       if (! attr)
5543         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5544                  " [in module %s]"),
5545                dwo_name, objfile_name (this_cu->objfile));
5546       signature = DW_UNSND (attr);
5547       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5548                                        signature);
5549     }
5550
5551   return dwo_unit;
5552 }
5553
5554 /* Subroutine of init_cutu_and_read_dies to simplify it.
5555    See it for a description of the parameters.
5556    Read a TU directly from a DWO file, bypassing the stub.
5557
5558    Note: This function could be a little bit simpler if we shared cleanups
5559    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5560    to do, so we keep this function self-contained.  Or we could move this
5561    into our caller, but it's complex enough already.  */
5562
5563 static void
5564 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5565                            int use_existing_cu, int keep,
5566                            die_reader_func_ftype *die_reader_func,
5567                            void *data)
5568 {
5569   struct dwarf2_cu *cu;
5570   struct signatured_type *sig_type;
5571   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5572   struct die_reader_specs reader;
5573   const gdb_byte *info_ptr;
5574   struct die_info *comp_unit_die;
5575   int has_children;
5576
5577   /* Verify we can do the following downcast, and that we have the
5578      data we need.  */
5579   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5580   sig_type = (struct signatured_type *) this_cu;
5581   gdb_assert (sig_type->dwo_unit != NULL);
5582
5583   cleanups = make_cleanup (null_cleanup, NULL);
5584
5585   if (use_existing_cu && this_cu->cu != NULL)
5586     {
5587       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5588       cu = this_cu->cu;
5589       /* There's no need to do the rereading_dwo_cu handling that
5590          init_cutu_and_read_dies does since we don't read the stub.  */
5591     }
5592   else
5593     {
5594       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5595       gdb_assert (this_cu->cu == NULL);
5596       cu = XNEW (struct dwarf2_cu);
5597       init_one_comp_unit (cu, this_cu);
5598       /* If an error occurs while loading, release our storage.  */
5599       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5600     }
5601
5602   /* A future optimization, if needed, would be to use an existing
5603      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5604      could share abbrev tables.  */
5605
5606   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5607                               0 /* abbrev_table_provided */,
5608                               NULL /* stub_comp_unit_die */,
5609                               sig_type->dwo_unit->dwo_file->comp_dir,
5610                               &reader, &info_ptr,
5611                               &comp_unit_die, &has_children) == 0)
5612     {
5613       /* Dummy die.  */
5614       do_cleanups (cleanups);
5615       return;
5616     }
5617
5618   /* All the "real" work is done here.  */
5619   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5620
5621   /* This duplicates the code in init_cutu_and_read_dies,
5622      but the alternative is making the latter more complex.
5623      This function is only for the special case of using DWO files directly:
5624      no point in overly complicating the general case just to handle this.  */
5625   if (free_cu_cleanup != NULL)
5626     {
5627       if (keep)
5628         {
5629           /* We've successfully allocated this compilation unit.  Let our
5630              caller clean it up when finished with it.  */
5631           discard_cleanups (free_cu_cleanup);
5632
5633           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5634              So we have to manually free the abbrev table.  */
5635           dwarf2_free_abbrev_table (cu);
5636
5637           /* Link this CU into read_in_chain.  */
5638           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5639           dwarf2_per_objfile->read_in_chain = this_cu;
5640         }
5641       else
5642         do_cleanups (free_cu_cleanup);
5643     }
5644
5645   do_cleanups (cleanups);
5646 }
5647
5648 /* Initialize a CU (or TU) and read its DIEs.
5649    If the CU defers to a DWO file, read the DWO file as well.
5650
5651    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5652    Otherwise the table specified in the comp unit header is read in and used.
5653    This is an optimization for when we already have the abbrev table.
5654
5655    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5656    Otherwise, a new CU is allocated with xmalloc.
5657
5658    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5659    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5660
5661    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5662    linker) then DIE_READER_FUNC will not get called.  */
5663
5664 static void
5665 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5666                          struct abbrev_table *abbrev_table,
5667                          int use_existing_cu, int keep,
5668                          die_reader_func_ftype *die_reader_func,
5669                          void *data)
5670 {
5671   struct objfile *objfile = dwarf2_per_objfile->objfile;
5672   struct dwarf2_section_info *section = this_cu->section;
5673   bfd *abfd = get_section_bfd_owner (section);
5674   struct dwarf2_cu *cu;
5675   const gdb_byte *begin_info_ptr, *info_ptr;
5676   struct die_reader_specs reader;
5677   struct die_info *comp_unit_die;
5678   int has_children;
5679   struct attribute *attr;
5680   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5681   struct signatured_type *sig_type = NULL;
5682   struct dwarf2_section_info *abbrev_section;
5683   /* Non-zero if CU currently points to a DWO file and we need to
5684      reread it.  When this happens we need to reread the skeleton die
5685      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5686   int rereading_dwo_cu = 0;
5687
5688   if (dwarf_die_debug)
5689     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5690                         this_cu->is_debug_types ? "type" : "comp",
5691                         to_underlying (this_cu->sect_off));
5692
5693   if (use_existing_cu)
5694     gdb_assert (keep);
5695
5696   /* If we're reading a TU directly from a DWO file, including a virtual DWO
5697      file (instead of going through the stub), short-circuit all of this.  */
5698   if (this_cu->reading_dwo_directly)
5699     {
5700       /* Narrow down the scope of possibilities to have to understand.  */
5701       gdb_assert (this_cu->is_debug_types);
5702       gdb_assert (abbrev_table == NULL);
5703       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
5704                                  die_reader_func, data);
5705       return;
5706     }
5707
5708   cleanups = make_cleanup (null_cleanup, NULL);
5709
5710   /* This is cheap if the section is already read in.  */
5711   dwarf2_read_section (objfile, section);
5712
5713   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5714
5715   abbrev_section = get_abbrev_section_for_cu (this_cu);
5716
5717   if (use_existing_cu && this_cu->cu != NULL)
5718     {
5719       cu = this_cu->cu;
5720       /* If this CU is from a DWO file we need to start over, we need to
5721          refetch the attributes from the skeleton CU.
5722          This could be optimized by retrieving those attributes from when we
5723          were here the first time: the previous comp_unit_die was stored in
5724          comp_unit_obstack.  But there's no data yet that we need this
5725          optimization.  */
5726       if (cu->dwo_unit != NULL)
5727         rereading_dwo_cu = 1;
5728     }
5729   else
5730     {
5731       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5732       gdb_assert (this_cu->cu == NULL);
5733       cu = XNEW (struct dwarf2_cu);
5734       init_one_comp_unit (cu, this_cu);
5735       /* If an error occurs while loading, release our storage.  */
5736       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5737     }
5738
5739   /* Get the header.  */
5740   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
5741     {
5742       /* We already have the header, there's no need to read it in again.  */
5743       info_ptr += to_underlying (cu->header.first_die_cu_offset);
5744     }
5745   else
5746     {
5747       if (this_cu->is_debug_types)
5748         {
5749           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5750                                                     abbrev_section, info_ptr,
5751                                                     rcuh_kind::TYPE);
5752
5753           /* Since per_cu is the first member of struct signatured_type,
5754              we can go from a pointer to one to a pointer to the other.  */
5755           sig_type = (struct signatured_type *) this_cu;
5756           gdb_assert (sig_type->signature == cu->header.signature);
5757           gdb_assert (sig_type->type_offset_in_tu
5758                       == cu->header.type_cu_offset_in_tu);
5759           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5760
5761           /* LENGTH has not been set yet for type units if we're
5762              using .gdb_index.  */
5763           this_cu->length = get_cu_length (&cu->header);
5764
5765           /* Establish the type offset that can be used to lookup the type.  */
5766           sig_type->type_offset_in_section =
5767             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
5768
5769           this_cu->dwarf_version = cu->header.version;
5770         }
5771       else
5772         {
5773           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5774                                                     abbrev_section,
5775                                                     info_ptr,
5776                                                     rcuh_kind::COMPILE);
5777
5778           gdb_assert (this_cu->sect_off == cu->header.sect_off);
5779           gdb_assert (this_cu->length == get_cu_length (&cu->header));
5780           this_cu->dwarf_version = cu->header.version;
5781         }
5782     }
5783
5784   /* Skip dummy compilation units.  */
5785   if (info_ptr >= begin_info_ptr + this_cu->length
5786       || peek_abbrev_code (abfd, info_ptr) == 0)
5787     {
5788       do_cleanups (cleanups);
5789       return;
5790     }
5791
5792   /* If we don't have them yet, read the abbrevs for this compilation unit.
5793      And if we need to read them now, make sure they're freed when we're
5794      done.  Note that it's important that if the CU had an abbrev table
5795      on entry we don't free it when we're done: Somewhere up the call stack
5796      it may be in use.  */
5797   if (abbrev_table != NULL)
5798     {
5799       gdb_assert (cu->abbrev_table == NULL);
5800       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
5801       cu->abbrev_table = abbrev_table;
5802     }
5803   else if (cu->abbrev_table == NULL)
5804     {
5805       dwarf2_read_abbrevs (cu, abbrev_section);
5806       make_cleanup (dwarf2_free_abbrev_table, cu);
5807     }
5808   else if (rereading_dwo_cu)
5809     {
5810       dwarf2_free_abbrev_table (cu);
5811       dwarf2_read_abbrevs (cu, abbrev_section);
5812     }
5813
5814   /* Read the top level CU/TU die.  */
5815   init_cu_die_reader (&reader, cu, section, NULL);
5816   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5817
5818   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
5819      from the DWO file.
5820      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
5821      DWO CU, that this test will fail (the attribute will not be present).  */
5822   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5823   if (attr)
5824     {
5825       struct dwo_unit *dwo_unit;
5826       struct die_info *dwo_comp_unit_die;
5827
5828       if (has_children)
5829         {
5830           complaint (&symfile_complaints,
5831                      _("compilation unit with DW_AT_GNU_dwo_name"
5832                        " has children (offset 0x%x) [in module %s]"),
5833                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
5834         }
5835       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
5836       if (dwo_unit != NULL)
5837         {
5838           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
5839                                       abbrev_table != NULL,
5840                                       comp_unit_die, NULL,
5841                                       &reader, &info_ptr,
5842                                       &dwo_comp_unit_die, &has_children) == 0)
5843             {
5844               /* Dummy die.  */
5845               do_cleanups (cleanups);
5846               return;
5847             }
5848           comp_unit_die = dwo_comp_unit_die;
5849         }
5850       else
5851         {
5852           /* Yikes, we couldn't find the rest of the DIE, we only have
5853              the stub.  A complaint has already been logged.  There's
5854              not much more we can do except pass on the stub DIE to
5855              die_reader_func.  We don't want to throw an error on bad
5856              debug info.  */
5857         }
5858     }
5859
5860   /* All of the above is setup for this call.  Yikes.  */
5861   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5862
5863   /* Done, clean up.  */
5864   if (free_cu_cleanup != NULL)
5865     {
5866       if (keep)
5867         {
5868           /* We've successfully allocated this compilation unit.  Let our
5869              caller clean it up when finished with it.  */
5870           discard_cleanups (free_cu_cleanup);
5871
5872           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5873              So we have to manually free the abbrev table.  */
5874           dwarf2_free_abbrev_table (cu);
5875
5876           /* Link this CU into read_in_chain.  */
5877           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5878           dwarf2_per_objfile->read_in_chain = this_cu;
5879         }
5880       else
5881         do_cleanups (free_cu_cleanup);
5882     }
5883
5884   do_cleanups (cleanups);
5885 }
5886
5887 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
5888    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
5889    to have already done the lookup to find the DWO file).
5890
5891    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
5892    THIS_CU->is_debug_types, but nothing else.
5893
5894    We fill in THIS_CU->length.
5895
5896    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5897    linker) then DIE_READER_FUNC will not get called.
5898
5899    THIS_CU->cu is always freed when done.
5900    This is done in order to not leave THIS_CU->cu in a state where we have
5901    to care whether it refers to the "main" CU or the DWO CU.  */
5902
5903 static void
5904 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
5905                                    struct dwo_file *dwo_file,
5906                                    die_reader_func_ftype *die_reader_func,
5907                                    void *data)
5908 {
5909   struct objfile *objfile = dwarf2_per_objfile->objfile;
5910   struct dwarf2_section_info *section = this_cu->section;
5911   bfd *abfd = get_section_bfd_owner (section);
5912   struct dwarf2_section_info *abbrev_section;
5913   struct dwarf2_cu cu;
5914   const gdb_byte *begin_info_ptr, *info_ptr;
5915   struct die_reader_specs reader;
5916   struct cleanup *cleanups;
5917   struct die_info *comp_unit_die;
5918   int has_children;
5919
5920   if (dwarf_die_debug)
5921     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5922                         this_cu->is_debug_types ? "type" : "comp",
5923                         to_underlying (this_cu->sect_off));
5924
5925   gdb_assert (this_cu->cu == NULL);
5926
5927   abbrev_section = (dwo_file != NULL
5928                     ? &dwo_file->sections.abbrev
5929                     : get_abbrev_section_for_cu (this_cu));
5930
5931   /* This is cheap if the section is already read in.  */
5932   dwarf2_read_section (objfile, section);
5933
5934   init_one_comp_unit (&cu, this_cu);
5935
5936   cleanups = make_cleanup (free_stack_comp_unit, &cu);
5937
5938   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
5939   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
5940                                             abbrev_section, info_ptr,
5941                                             (this_cu->is_debug_types
5942                                              ? rcuh_kind::TYPE
5943                                              : rcuh_kind::COMPILE));
5944
5945   this_cu->length = get_cu_length (&cu.header);
5946
5947   /* Skip dummy compilation units.  */
5948   if (info_ptr >= begin_info_ptr + this_cu->length
5949       || peek_abbrev_code (abfd, info_ptr) == 0)
5950     {
5951       do_cleanups (cleanups);
5952       return;
5953     }
5954
5955   dwarf2_read_abbrevs (&cu, abbrev_section);
5956   make_cleanup (dwarf2_free_abbrev_table, &cu);
5957
5958   init_cu_die_reader (&reader, &cu, section, dwo_file);
5959   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
5960
5961   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5962
5963   do_cleanups (cleanups);
5964 }
5965
5966 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
5967    does not lookup the specified DWO file.
5968    This cannot be used to read DWO files.
5969
5970    THIS_CU->cu is always freed when done.
5971    This is done in order to not leave THIS_CU->cu in a state where we have
5972    to care whether it refers to the "main" CU or the DWO CU.
5973    We can revisit this if the data shows there's a performance issue.  */
5974
5975 static void
5976 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
5977                                 die_reader_func_ftype *die_reader_func,
5978                                 void *data)
5979 {
5980   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
5981 }
5982 \f
5983 /* Type Unit Groups.
5984
5985    Type Unit Groups are a way to collapse the set of all TUs (type units) into
5986    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
5987    so that all types coming from the same compilation (.o file) are grouped
5988    together.  A future step could be to put the types in the same symtab as
5989    the CU the types ultimately came from.  */
5990
5991 static hashval_t
5992 hash_type_unit_group (const void *item)
5993 {
5994   const struct type_unit_group *tu_group
5995     = (const struct type_unit_group *) item;
5996
5997   return hash_stmt_list_entry (&tu_group->hash);
5998 }
5999
6000 static int
6001 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6002 {
6003   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6004   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6005
6006   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6007 }
6008
6009 /* Allocate a hash table for type unit groups.  */
6010
6011 static htab_t
6012 allocate_type_unit_groups_table (void)
6013 {
6014   return htab_create_alloc_ex (3,
6015                                hash_type_unit_group,
6016                                eq_type_unit_group,
6017                                NULL,
6018                                &dwarf2_per_objfile->objfile->objfile_obstack,
6019                                hashtab_obstack_allocate,
6020                                dummy_obstack_deallocate);
6021 }
6022
6023 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6024    partial symtabs.  We combine several TUs per psymtab to not let the size
6025    of any one psymtab grow too big.  */
6026 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6027 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6028
6029 /* Helper routine for get_type_unit_group.
6030    Create the type_unit_group object used to hold one or more TUs.  */
6031
6032 static struct type_unit_group *
6033 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6034 {
6035   struct objfile *objfile = dwarf2_per_objfile->objfile;
6036   struct dwarf2_per_cu_data *per_cu;
6037   struct type_unit_group *tu_group;
6038
6039   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6040                              struct type_unit_group);
6041   per_cu = &tu_group->per_cu;
6042   per_cu->objfile = objfile;
6043
6044   if (dwarf2_per_objfile->using_index)
6045     {
6046       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6047                                         struct dwarf2_per_cu_quick_data);
6048     }
6049   else
6050     {
6051       unsigned int line_offset = to_underlying (line_offset_struct);
6052       struct partial_symtab *pst;
6053       char *name;
6054
6055       /* Give the symtab a useful name for debug purposes.  */
6056       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6057         name = xstrprintf ("<type_units_%d>",
6058                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6059       else
6060         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6061
6062       pst = create_partial_symtab (per_cu, name);
6063       pst->anonymous = 1;
6064
6065       xfree (name);
6066     }
6067
6068   tu_group->hash.dwo_unit = cu->dwo_unit;
6069   tu_group->hash.line_sect_off = line_offset_struct;
6070
6071   return tu_group;
6072 }
6073
6074 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6075    STMT_LIST is a DW_AT_stmt_list attribute.  */
6076
6077 static struct type_unit_group *
6078 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6079 {
6080   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6081   struct type_unit_group *tu_group;
6082   void **slot;
6083   unsigned int line_offset;
6084   struct type_unit_group type_unit_group_for_lookup;
6085
6086   if (dwarf2_per_objfile->type_unit_groups == NULL)
6087     {
6088       dwarf2_per_objfile->type_unit_groups =
6089         allocate_type_unit_groups_table ();
6090     }
6091
6092   /* Do we need to create a new group, or can we use an existing one?  */
6093
6094   if (stmt_list)
6095     {
6096       line_offset = DW_UNSND (stmt_list);
6097       ++tu_stats->nr_symtab_sharers;
6098     }
6099   else
6100     {
6101       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6102          We can do various things here like create one group per TU or
6103          spread them over multiple groups to split up the expansion work.
6104          To avoid worst case scenarios (too many groups or too large groups)
6105          we, umm, group them in bunches.  */
6106       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6107                      | (tu_stats->nr_stmt_less_type_units
6108                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6109       ++tu_stats->nr_stmt_less_type_units;
6110     }
6111
6112   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6113   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6114   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6115                          &type_unit_group_for_lookup, INSERT);
6116   if (*slot != NULL)
6117     {
6118       tu_group = (struct type_unit_group *) *slot;
6119       gdb_assert (tu_group != NULL);
6120     }
6121   else
6122     {
6123       sect_offset line_offset_struct = (sect_offset) line_offset;
6124       tu_group = create_type_unit_group (cu, line_offset_struct);
6125       *slot = tu_group;
6126       ++tu_stats->nr_symtabs;
6127     }
6128
6129   return tu_group;
6130 }
6131 \f
6132 /* Partial symbol tables.  */
6133
6134 /* Create a psymtab named NAME and assign it to PER_CU.
6135
6136    The caller must fill in the following details:
6137    dirname, textlow, texthigh.  */
6138
6139 static struct partial_symtab *
6140 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6141 {
6142   struct objfile *objfile = per_cu->objfile;
6143   struct partial_symtab *pst;
6144
6145   pst = start_psymtab_common (objfile, name, 0,
6146                               objfile->global_psymbols.next,
6147                               objfile->static_psymbols.next);
6148
6149   pst->psymtabs_addrmap_supported = 1;
6150
6151   /* This is the glue that links PST into GDB's symbol API.  */
6152   pst->read_symtab_private = per_cu;
6153   pst->read_symtab = dwarf2_read_symtab;
6154   per_cu->v.psymtab = pst;
6155
6156   return pst;
6157 }
6158
6159 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6160    type.  */
6161
6162 struct process_psymtab_comp_unit_data
6163 {
6164   /* True if we are reading a DW_TAG_partial_unit.  */
6165
6166   int want_partial_unit;
6167
6168   /* The "pretend" language that is used if the CU doesn't declare a
6169      language.  */
6170
6171   enum language pretend_language;
6172 };
6173
6174 /* die_reader_func for process_psymtab_comp_unit.  */
6175
6176 static void
6177 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6178                                   const gdb_byte *info_ptr,
6179                                   struct die_info *comp_unit_die,
6180                                   int has_children,
6181                                   void *data)
6182 {
6183   struct dwarf2_cu *cu = reader->cu;
6184   struct objfile *objfile = cu->objfile;
6185   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6186   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6187   CORE_ADDR baseaddr;
6188   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6189   struct partial_symtab *pst;
6190   enum pc_bounds_kind cu_bounds_kind;
6191   const char *filename;
6192   struct process_psymtab_comp_unit_data *info
6193     = (struct process_psymtab_comp_unit_data *) data;
6194
6195   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6196     return;
6197
6198   gdb_assert (! per_cu->is_debug_types);
6199
6200   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6201
6202   cu->list_in_scope = &file_symbols;
6203
6204   /* Allocate a new partial symbol table structure.  */
6205   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6206   if (filename == NULL)
6207     filename = "";
6208
6209   pst = create_partial_symtab (per_cu, filename);
6210
6211   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6212   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6213
6214   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6215
6216   dwarf2_find_base_address (comp_unit_die, cu);
6217
6218   /* Possibly set the default values of LOWPC and HIGHPC from
6219      `DW_AT_ranges'.  */
6220   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6221                                          &best_highpc, cu, pst);
6222   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6223     /* Store the contiguous range if it is not empty; it can be empty for
6224        CUs with no code.  */
6225     addrmap_set_empty (objfile->psymtabs_addrmap,
6226                        gdbarch_adjust_dwarf2_addr (gdbarch,
6227                                                    best_lowpc + baseaddr),
6228                        gdbarch_adjust_dwarf2_addr (gdbarch,
6229                                                    best_highpc + baseaddr) - 1,
6230                        pst);
6231
6232   /* Check if comp unit has_children.
6233      If so, read the rest of the partial symbols from this comp unit.
6234      If not, there's no more debug_info for this comp unit.  */
6235   if (has_children)
6236     {
6237       struct partial_die_info *first_die;
6238       CORE_ADDR lowpc, highpc;
6239
6240       lowpc = ((CORE_ADDR) -1);
6241       highpc = ((CORE_ADDR) 0);
6242
6243       first_die = load_partial_dies (reader, info_ptr, 1);
6244
6245       scan_partial_symbols (first_die, &lowpc, &highpc,
6246                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6247
6248       /* If we didn't find a lowpc, set it to highpc to avoid
6249          complaints from `maint check'.  */
6250       if (lowpc == ((CORE_ADDR) -1))
6251         lowpc = highpc;
6252
6253       /* If the compilation unit didn't have an explicit address range,
6254          then use the information extracted from its child dies.  */
6255       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6256         {
6257           best_lowpc = lowpc;
6258           best_highpc = highpc;
6259         }
6260     }
6261   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6262   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6263
6264   end_psymtab_common (objfile, pst);
6265
6266   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6267     {
6268       int i;
6269       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6270       struct dwarf2_per_cu_data *iter;
6271
6272       /* Fill in 'dependencies' here; we fill in 'users' in a
6273          post-pass.  */
6274       pst->number_of_dependencies = len;
6275       pst->dependencies =
6276         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6277       for (i = 0;
6278            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6279                         i, iter);
6280            ++i)
6281         pst->dependencies[i] = iter->v.psymtab;
6282
6283       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6284     }
6285
6286   /* Get the list of files included in the current compilation unit,
6287      and build a psymtab for each of them.  */
6288   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6289
6290   if (dwarf_read_debug)
6291     {
6292       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6293
6294       fprintf_unfiltered (gdb_stdlog,
6295                           "Psymtab for %s unit @0x%x: %s - %s"
6296                           ", %d global, %d static syms\n",
6297                           per_cu->is_debug_types ? "type" : "comp",
6298                           to_underlying (per_cu->sect_off),
6299                           paddress (gdbarch, pst->textlow),
6300                           paddress (gdbarch, pst->texthigh),
6301                           pst->n_global_syms, pst->n_static_syms);
6302     }
6303 }
6304
6305 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6306    Process compilation unit THIS_CU for a psymtab.  */
6307
6308 static void
6309 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6310                            int want_partial_unit,
6311                            enum language pretend_language)
6312 {
6313   /* If this compilation unit was already read in, free the
6314      cached copy in order to read it in again.  This is
6315      necessary because we skipped some symbols when we first
6316      read in the compilation unit (see load_partial_dies).
6317      This problem could be avoided, but the benefit is unclear.  */
6318   if (this_cu->cu != NULL)
6319     free_one_cached_comp_unit (this_cu);
6320
6321   if (this_cu->is_debug_types)
6322     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6323                              NULL);
6324   else
6325     {
6326       process_psymtab_comp_unit_data info;
6327       info.want_partial_unit = want_partial_unit;
6328       info.pretend_language = pretend_language;
6329       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6330                                process_psymtab_comp_unit_reader, &info);
6331     }
6332
6333   /* Age out any secondary CUs.  */
6334   age_cached_comp_units ();
6335 }
6336
6337 /* Reader function for build_type_psymtabs.  */
6338
6339 static void
6340 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6341                             const gdb_byte *info_ptr,
6342                             struct die_info *type_unit_die,
6343                             int has_children,
6344                             void *data)
6345 {
6346   struct objfile *objfile = dwarf2_per_objfile->objfile;
6347   struct dwarf2_cu *cu = reader->cu;
6348   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6349   struct signatured_type *sig_type;
6350   struct type_unit_group *tu_group;
6351   struct attribute *attr;
6352   struct partial_die_info *first_die;
6353   CORE_ADDR lowpc, highpc;
6354   struct partial_symtab *pst;
6355
6356   gdb_assert (data == NULL);
6357   gdb_assert (per_cu->is_debug_types);
6358   sig_type = (struct signatured_type *) per_cu;
6359
6360   if (! has_children)
6361     return;
6362
6363   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6364   tu_group = get_type_unit_group (cu, attr);
6365
6366   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6367
6368   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6369   cu->list_in_scope = &file_symbols;
6370   pst = create_partial_symtab (per_cu, "");
6371   pst->anonymous = 1;
6372
6373   first_die = load_partial_dies (reader, info_ptr, 1);
6374
6375   lowpc = (CORE_ADDR) -1;
6376   highpc = (CORE_ADDR) 0;
6377   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6378
6379   end_psymtab_common (objfile, pst);
6380 }
6381
6382 /* Struct used to sort TUs by their abbreviation table offset.  */
6383
6384 struct tu_abbrev_offset
6385 {
6386   struct signatured_type *sig_type;
6387   sect_offset abbrev_offset;
6388 };
6389
6390 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6391
6392 static int
6393 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6394 {
6395   const struct tu_abbrev_offset * const *a
6396     = (const struct tu_abbrev_offset * const*) ap;
6397   const struct tu_abbrev_offset * const *b
6398     = (const struct tu_abbrev_offset * const*) bp;
6399   sect_offset aoff = (*a)->abbrev_offset;
6400   sect_offset boff = (*b)->abbrev_offset;
6401
6402   return (aoff > boff) - (aoff < boff);
6403 }
6404
6405 /* Efficiently read all the type units.
6406    This does the bulk of the work for build_type_psymtabs.
6407
6408    The efficiency is because we sort TUs by the abbrev table they use and
6409    only read each abbrev table once.  In one program there are 200K TUs
6410    sharing 8K abbrev tables.
6411
6412    The main purpose of this function is to support building the
6413    dwarf2_per_objfile->type_unit_groups table.
6414    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6415    can collapse the search space by grouping them by stmt_list.
6416    The savings can be significant, in the same program from above the 200K TUs
6417    share 8K stmt_list tables.
6418
6419    FUNC is expected to call get_type_unit_group, which will create the
6420    struct type_unit_group if necessary and add it to
6421    dwarf2_per_objfile->type_unit_groups.  */
6422
6423 static void
6424 build_type_psymtabs_1 (void)
6425 {
6426   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6427   struct cleanup *cleanups;
6428   struct abbrev_table *abbrev_table;
6429   sect_offset abbrev_offset;
6430   struct tu_abbrev_offset *sorted_by_abbrev;
6431   int i;
6432
6433   /* It's up to the caller to not call us multiple times.  */
6434   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6435
6436   if (dwarf2_per_objfile->n_type_units == 0)
6437     return;
6438
6439   /* TUs typically share abbrev tables, and there can be way more TUs than
6440      abbrev tables.  Sort by abbrev table to reduce the number of times we
6441      read each abbrev table in.
6442      Alternatives are to punt or to maintain a cache of abbrev tables.
6443      This is simpler and efficient enough for now.
6444
6445      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6446      symtab to use).  Typically TUs with the same abbrev offset have the same
6447      stmt_list value too so in practice this should work well.
6448
6449      The basic algorithm here is:
6450
6451       sort TUs by abbrev table
6452       for each TU with same abbrev table:
6453         read abbrev table if first user
6454         read TU top level DIE
6455           [IWBN if DWO skeletons had DW_AT_stmt_list]
6456         call FUNC  */
6457
6458   if (dwarf_read_debug)
6459     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6460
6461   /* Sort in a separate table to maintain the order of all_type_units
6462      for .gdb_index: TU indices directly index all_type_units.  */
6463   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6464                               dwarf2_per_objfile->n_type_units);
6465   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6466     {
6467       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6468
6469       sorted_by_abbrev[i].sig_type = sig_type;
6470       sorted_by_abbrev[i].abbrev_offset =
6471         read_abbrev_offset (sig_type->per_cu.section,
6472                             sig_type->per_cu.sect_off);
6473     }
6474   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6475   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6476          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6477
6478   abbrev_offset = (sect_offset) ~(unsigned) 0;
6479   abbrev_table = NULL;
6480   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6481
6482   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6483     {
6484       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6485
6486       /* Switch to the next abbrev table if necessary.  */
6487       if (abbrev_table == NULL
6488           || tu->abbrev_offset != abbrev_offset)
6489         {
6490           if (abbrev_table != NULL)
6491             {
6492               abbrev_table_free (abbrev_table);
6493               /* Reset to NULL in case abbrev_table_read_table throws
6494                  an error: abbrev_table_free_cleanup will get called.  */
6495               abbrev_table = NULL;
6496             }
6497           abbrev_offset = tu->abbrev_offset;
6498           abbrev_table =
6499             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6500                                      abbrev_offset);
6501           ++tu_stats->nr_uniq_abbrev_tables;
6502         }
6503
6504       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6505                                build_type_psymtabs_reader, NULL);
6506     }
6507
6508   do_cleanups (cleanups);
6509 }
6510
6511 /* Print collected type unit statistics.  */
6512
6513 static void
6514 print_tu_stats (void)
6515 {
6516   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6517
6518   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6519   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6520                       dwarf2_per_objfile->n_type_units);
6521   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6522                       tu_stats->nr_uniq_abbrev_tables);
6523   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6524                       tu_stats->nr_symtabs);
6525   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6526                       tu_stats->nr_symtab_sharers);
6527   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6528                       tu_stats->nr_stmt_less_type_units);
6529   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6530                       tu_stats->nr_all_type_units_reallocs);
6531 }
6532
6533 /* Traversal function for build_type_psymtabs.  */
6534
6535 static int
6536 build_type_psymtab_dependencies (void **slot, void *info)
6537 {
6538   struct objfile *objfile = dwarf2_per_objfile->objfile;
6539   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6540   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6541   struct partial_symtab *pst = per_cu->v.psymtab;
6542   int len = VEC_length (sig_type_ptr, tu_group->tus);
6543   struct signatured_type *iter;
6544   int i;
6545
6546   gdb_assert (len > 0);
6547   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6548
6549   pst->number_of_dependencies = len;
6550   pst->dependencies =
6551     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6552   for (i = 0;
6553        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6554        ++i)
6555     {
6556       gdb_assert (iter->per_cu.is_debug_types);
6557       pst->dependencies[i] = iter->per_cu.v.psymtab;
6558       iter->type_unit_group = tu_group;
6559     }
6560
6561   VEC_free (sig_type_ptr, tu_group->tus);
6562
6563   return 1;
6564 }
6565
6566 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6567    Build partial symbol tables for the .debug_types comp-units.  */
6568
6569 static void
6570 build_type_psymtabs (struct objfile *objfile)
6571 {
6572   if (! create_all_type_units (objfile))
6573     return;
6574
6575   build_type_psymtabs_1 ();
6576 }
6577
6578 /* Traversal function for process_skeletonless_type_unit.
6579    Read a TU in a DWO file and build partial symbols for it.  */
6580
6581 static int
6582 process_skeletonless_type_unit (void **slot, void *info)
6583 {
6584   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6585   struct objfile *objfile = (struct objfile *) info;
6586   struct signatured_type find_entry, *entry;
6587
6588   /* If this TU doesn't exist in the global table, add it and read it in.  */
6589
6590   if (dwarf2_per_objfile->signatured_types == NULL)
6591     {
6592       dwarf2_per_objfile->signatured_types
6593         = allocate_signatured_type_table (objfile);
6594     }
6595
6596   find_entry.signature = dwo_unit->signature;
6597   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6598                          INSERT);
6599   /* If we've already seen this type there's nothing to do.  What's happening
6600      is we're doing our own version of comdat-folding here.  */
6601   if (*slot != NULL)
6602     return 1;
6603
6604   /* This does the job that create_all_type_units would have done for
6605      this TU.  */
6606   entry = add_type_unit (dwo_unit->signature, slot);
6607   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6608   *slot = entry;
6609
6610   /* This does the job that build_type_psymtabs_1 would have done.  */
6611   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6612                            build_type_psymtabs_reader, NULL);
6613
6614   return 1;
6615 }
6616
6617 /* Traversal function for process_skeletonless_type_units.  */
6618
6619 static int
6620 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6621 {
6622   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6623
6624   if (dwo_file->tus != NULL)
6625     {
6626       htab_traverse_noresize (dwo_file->tus,
6627                               process_skeletonless_type_unit, info);
6628     }
6629
6630   return 1;
6631 }
6632
6633 /* Scan all TUs of DWO files, verifying we've processed them.
6634    This is needed in case a TU was emitted without its skeleton.
6635    Note: This can't be done until we know what all the DWO files are.  */
6636
6637 static void
6638 process_skeletonless_type_units (struct objfile *objfile)
6639 {
6640   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6641   if (get_dwp_file () == NULL
6642       && dwarf2_per_objfile->dwo_files != NULL)
6643     {
6644       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6645                               process_dwo_file_for_skeletonless_type_units,
6646                               objfile);
6647     }
6648 }
6649
6650 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6651
6652 static void
6653 set_partial_user (struct objfile *objfile)
6654 {
6655   int i;
6656
6657   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6658     {
6659       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6660       struct partial_symtab *pst = per_cu->v.psymtab;
6661       int j;
6662
6663       if (pst == NULL)
6664         continue;
6665
6666       for (j = 0; j < pst->number_of_dependencies; ++j)
6667         {
6668           /* Set the 'user' field only if it is not already set.  */
6669           if (pst->dependencies[j]->user == NULL)
6670             pst->dependencies[j]->user = pst;
6671         }
6672     }
6673 }
6674
6675 /* Build the partial symbol table by doing a quick pass through the
6676    .debug_info and .debug_abbrev sections.  */
6677
6678 static void
6679 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6680 {
6681   struct cleanup *back_to;
6682   int i;
6683
6684   if (dwarf_read_debug)
6685     {
6686       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6687                           objfile_name (objfile));
6688     }
6689
6690   dwarf2_per_objfile->reading_partial_symbols = 1;
6691
6692   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
6693
6694   /* Any cached compilation units will be linked by the per-objfile
6695      read_in_chain.  Make sure to free them when we're done.  */
6696   back_to = make_cleanup (free_cached_comp_units, NULL);
6697
6698   build_type_psymtabs (objfile);
6699
6700   create_all_comp_units (objfile);
6701
6702   /* Create a temporary address map on a temporary obstack.  We later
6703      copy this to the final obstack.  */
6704   auto_obstack temp_obstack;
6705
6706   scoped_restore save_psymtabs_addrmap
6707     = make_scoped_restore (&objfile->psymtabs_addrmap,
6708                            addrmap_create_mutable (&temp_obstack));
6709
6710   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6711     {
6712       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6713
6714       process_psymtab_comp_unit (per_cu, 0, language_minimal);
6715     }
6716
6717   /* This has to wait until we read the CUs, we need the list of DWOs.  */
6718   process_skeletonless_type_units (objfile);
6719
6720   /* Now that all TUs have been processed we can fill in the dependencies.  */
6721   if (dwarf2_per_objfile->type_unit_groups != NULL)
6722     {
6723       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
6724                               build_type_psymtab_dependencies, NULL);
6725     }
6726
6727   if (dwarf_read_debug)
6728     print_tu_stats ();
6729
6730   set_partial_user (objfile);
6731
6732   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
6733                                                     &objfile->objfile_obstack);
6734   /* At this point we want to keep the address map.  */
6735   save_psymtabs_addrmap.release ();
6736
6737   do_cleanups (back_to);
6738
6739   if (dwarf_read_debug)
6740     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
6741                         objfile_name (objfile));
6742 }
6743
6744 /* die_reader_func for load_partial_comp_unit.  */
6745
6746 static void
6747 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
6748                                const gdb_byte *info_ptr,
6749                                struct die_info *comp_unit_die,
6750                                int has_children,
6751                                void *data)
6752 {
6753   struct dwarf2_cu *cu = reader->cu;
6754
6755   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
6756
6757   /* Check if comp unit has_children.
6758      If so, read the rest of the partial symbols from this comp unit.
6759      If not, there's no more debug_info for this comp unit.  */
6760   if (has_children)
6761     load_partial_dies (reader, info_ptr, 0);
6762 }
6763
6764 /* Load the partial DIEs for a secondary CU into memory.
6765    This is also used when rereading a primary CU with load_all_dies.  */
6766
6767 static void
6768 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
6769 {
6770   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
6771                            load_partial_comp_unit_reader, NULL);
6772 }
6773
6774 static void
6775 read_comp_units_from_section (struct objfile *objfile,
6776                               struct dwarf2_section_info *section,
6777                               struct dwarf2_section_info *abbrev_section,
6778                               unsigned int is_dwz,
6779                               int *n_allocated,
6780                               int *n_comp_units,
6781                               struct dwarf2_per_cu_data ***all_comp_units)
6782 {
6783   const gdb_byte *info_ptr;
6784   bfd *abfd = get_section_bfd_owner (section);
6785
6786   if (dwarf_read_debug)
6787     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
6788                         get_section_name (section),
6789                         get_section_file_name (section));
6790
6791   dwarf2_read_section (objfile, section);
6792
6793   info_ptr = section->buffer;
6794
6795   while (info_ptr < section->buffer + section->size)
6796     {
6797       struct dwarf2_per_cu_data *this_cu;
6798
6799       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
6800
6801       comp_unit_head cu_header;
6802       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
6803                                      info_ptr, rcuh_kind::COMPILE);
6804
6805       /* Save the compilation unit for later lookup.  */
6806       if (cu_header.unit_type != DW_UT_type)
6807         {
6808           this_cu = XOBNEW (&objfile->objfile_obstack,
6809                             struct dwarf2_per_cu_data);
6810           memset (this_cu, 0, sizeof (*this_cu));
6811         }
6812       else
6813         {
6814           auto sig_type = XOBNEW (&objfile->objfile_obstack,
6815                                   struct signatured_type);
6816           memset (sig_type, 0, sizeof (*sig_type));
6817           sig_type->signature = cu_header.signature;
6818           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
6819           this_cu = &sig_type->per_cu;
6820         }
6821       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
6822       this_cu->sect_off = sect_off;
6823       this_cu->length = cu_header.length + cu_header.initial_length_size;
6824       this_cu->is_dwz = is_dwz;
6825       this_cu->objfile = objfile;
6826       this_cu->section = section;
6827
6828       if (*n_comp_units == *n_allocated)
6829         {
6830           *n_allocated *= 2;
6831           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
6832                                         *all_comp_units, *n_allocated);
6833         }
6834       (*all_comp_units)[*n_comp_units] = this_cu;
6835       ++*n_comp_units;
6836
6837       info_ptr = info_ptr + this_cu->length;
6838     }
6839 }
6840
6841 /* Create a list of all compilation units in OBJFILE.
6842    This is only done for -readnow and building partial symtabs.  */
6843
6844 static void
6845 create_all_comp_units (struct objfile *objfile)
6846 {
6847   int n_allocated;
6848   int n_comp_units;
6849   struct dwarf2_per_cu_data **all_comp_units;
6850   struct dwz_file *dwz;
6851
6852   n_comp_units = 0;
6853   n_allocated = 10;
6854   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
6855
6856   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
6857                                 &dwarf2_per_objfile->abbrev, 0,
6858                                 &n_allocated, &n_comp_units, &all_comp_units);
6859
6860   dwz = dwarf2_get_dwz_file ();
6861   if (dwz != NULL)
6862     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
6863                                   &n_allocated, &n_comp_units,
6864                                   &all_comp_units);
6865
6866   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
6867                                                   struct dwarf2_per_cu_data *,
6868                                                   n_comp_units);
6869   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
6870           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
6871   xfree (all_comp_units);
6872   dwarf2_per_objfile->n_comp_units = n_comp_units;
6873 }
6874
6875 /* Process all loaded DIEs for compilation unit CU, starting at
6876    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
6877    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
6878    DW_AT_ranges).  See the comments of add_partial_subprogram on how
6879    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
6880
6881 static void
6882 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
6883                       CORE_ADDR *highpc, int set_addrmap,
6884                       struct dwarf2_cu *cu)
6885 {
6886   struct partial_die_info *pdi;
6887
6888   /* Now, march along the PDI's, descending into ones which have
6889      interesting children but skipping the children of the other ones,
6890      until we reach the end of the compilation unit.  */
6891
6892   pdi = first_die;
6893
6894   while (pdi != NULL)
6895     {
6896       fixup_partial_die (pdi, cu);
6897
6898       /* Anonymous namespaces or modules have no name but have interesting
6899          children, so we need to look at them.  Ditto for anonymous
6900          enums.  */
6901
6902       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
6903           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
6904           || pdi->tag == DW_TAG_imported_unit)
6905         {
6906           switch (pdi->tag)
6907             {
6908             case DW_TAG_subprogram:
6909               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
6910               break;
6911             case DW_TAG_constant:
6912             case DW_TAG_variable:
6913             case DW_TAG_typedef:
6914             case DW_TAG_union_type:
6915               if (!pdi->is_declaration)
6916                 {
6917                   add_partial_symbol (pdi, cu);
6918                 }
6919               break;
6920             case DW_TAG_class_type:
6921             case DW_TAG_interface_type:
6922             case DW_TAG_structure_type:
6923               if (!pdi->is_declaration)
6924                 {
6925                   add_partial_symbol (pdi, cu);
6926                 }
6927               if (cu->language == language_rust && pdi->has_children)
6928                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
6929                                       set_addrmap, cu);
6930               break;
6931             case DW_TAG_enumeration_type:
6932               if (!pdi->is_declaration)
6933                 add_partial_enumeration (pdi, cu);
6934               break;
6935             case DW_TAG_base_type:
6936             case DW_TAG_subrange_type:
6937               /* File scope base type definitions are added to the partial
6938                  symbol table.  */
6939               add_partial_symbol (pdi, cu);
6940               break;
6941             case DW_TAG_namespace:
6942               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
6943               break;
6944             case DW_TAG_module:
6945               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
6946               break;
6947             case DW_TAG_imported_unit:
6948               {
6949                 struct dwarf2_per_cu_data *per_cu;
6950
6951                 /* For now we don't handle imported units in type units.  */
6952                 if (cu->per_cu->is_debug_types)
6953                   {
6954                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
6955                              " supported in type units [in module %s]"),
6956                            objfile_name (cu->objfile));
6957                   }
6958
6959                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
6960                                                            pdi->is_dwz,
6961                                                            cu->objfile);
6962
6963                 /* Go read the partial unit, if needed.  */
6964                 if (per_cu->v.psymtab == NULL)
6965                   process_psymtab_comp_unit (per_cu, 1, cu->language);
6966
6967                 VEC_safe_push (dwarf2_per_cu_ptr,
6968                                cu->per_cu->imported_symtabs, per_cu);
6969               }
6970               break;
6971             case DW_TAG_imported_declaration:
6972               add_partial_symbol (pdi, cu);
6973               break;
6974             default:
6975               break;
6976             }
6977         }
6978
6979       /* If the die has a sibling, skip to the sibling.  */
6980
6981       pdi = pdi->die_sibling;
6982     }
6983 }
6984
6985 /* Functions used to compute the fully scoped name of a partial DIE.
6986
6987    Normally, this is simple.  For C++, the parent DIE's fully scoped
6988    name is concatenated with "::" and the partial DIE's name.
6989    Enumerators are an exception; they use the scope of their parent
6990    enumeration type, i.e. the name of the enumeration type is not
6991    prepended to the enumerator.
6992
6993    There are two complexities.  One is DW_AT_specification; in this
6994    case "parent" means the parent of the target of the specification,
6995    instead of the direct parent of the DIE.  The other is compilers
6996    which do not emit DW_TAG_namespace; in this case we try to guess
6997    the fully qualified name of structure types from their members'
6998    linkage names.  This must be done using the DIE's children rather
6999    than the children of any DW_AT_specification target.  We only need
7000    to do this for structures at the top level, i.e. if the target of
7001    any DW_AT_specification (if any; otherwise the DIE itself) does not
7002    have a parent.  */
7003
7004 /* Compute the scope prefix associated with PDI's parent, in
7005    compilation unit CU.  The result will be allocated on CU's
7006    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7007    field.  NULL is returned if no prefix is necessary.  */
7008 static const char *
7009 partial_die_parent_scope (struct partial_die_info *pdi,
7010                           struct dwarf2_cu *cu)
7011 {
7012   const char *grandparent_scope;
7013   struct partial_die_info *parent, *real_pdi;
7014
7015   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7016      then this means the parent of the specification DIE.  */
7017
7018   real_pdi = pdi;
7019   while (real_pdi->has_specification)
7020     real_pdi = find_partial_die (real_pdi->spec_offset,
7021                                  real_pdi->spec_is_dwz, cu);
7022
7023   parent = real_pdi->die_parent;
7024   if (parent == NULL)
7025     return NULL;
7026
7027   if (parent->scope_set)
7028     return parent->scope;
7029
7030   fixup_partial_die (parent, cu);
7031
7032   grandparent_scope = partial_die_parent_scope (parent, cu);
7033
7034   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7035      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7036      Work around this problem here.  */
7037   if (cu->language == language_cplus
7038       && parent->tag == DW_TAG_namespace
7039       && strcmp (parent->name, "::") == 0
7040       && grandparent_scope == NULL)
7041     {
7042       parent->scope = NULL;
7043       parent->scope_set = 1;
7044       return NULL;
7045     }
7046
7047   if (pdi->tag == DW_TAG_enumerator)
7048     /* Enumerators should not get the name of the enumeration as a prefix.  */
7049     parent->scope = grandparent_scope;
7050   else if (parent->tag == DW_TAG_namespace
7051       || parent->tag == DW_TAG_module
7052       || parent->tag == DW_TAG_structure_type
7053       || parent->tag == DW_TAG_class_type
7054       || parent->tag == DW_TAG_interface_type
7055       || parent->tag == DW_TAG_union_type
7056       || parent->tag == DW_TAG_enumeration_type)
7057     {
7058       if (grandparent_scope == NULL)
7059         parent->scope = parent->name;
7060       else
7061         parent->scope = typename_concat (&cu->comp_unit_obstack,
7062                                          grandparent_scope,
7063                                          parent->name, 0, cu);
7064     }
7065   else
7066     {
7067       /* FIXME drow/2004-04-01: What should we be doing with
7068          function-local names?  For partial symbols, we should probably be
7069          ignoring them.  */
7070       complaint (&symfile_complaints,
7071                  _("unhandled containing DIE tag %d for DIE at %d"),
7072                  parent->tag, to_underlying (pdi->sect_off));
7073       parent->scope = grandparent_scope;
7074     }
7075
7076   parent->scope_set = 1;
7077   return parent->scope;
7078 }
7079
7080 /* Return the fully scoped name associated with PDI, from compilation unit
7081    CU.  The result will be allocated with malloc.  */
7082
7083 static char *
7084 partial_die_full_name (struct partial_die_info *pdi,
7085                        struct dwarf2_cu *cu)
7086 {
7087   const char *parent_scope;
7088
7089   /* If this is a template instantiation, we can not work out the
7090      template arguments from partial DIEs.  So, unfortunately, we have
7091      to go through the full DIEs.  At least any work we do building
7092      types here will be reused if full symbols are loaded later.  */
7093   if (pdi->has_template_arguments)
7094     {
7095       fixup_partial_die (pdi, cu);
7096
7097       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7098         {
7099           struct die_info *die;
7100           struct attribute attr;
7101           struct dwarf2_cu *ref_cu = cu;
7102
7103           /* DW_FORM_ref_addr is using section offset.  */
7104           attr.name = (enum dwarf_attribute) 0;
7105           attr.form = DW_FORM_ref_addr;
7106           attr.u.unsnd = to_underlying (pdi->sect_off);
7107           die = follow_die_ref (NULL, &attr, &ref_cu);
7108
7109           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7110         }
7111     }
7112
7113   parent_scope = partial_die_parent_scope (pdi, cu);
7114   if (parent_scope == NULL)
7115     return NULL;
7116   else
7117     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7118 }
7119
7120 static void
7121 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7122 {
7123   struct objfile *objfile = cu->objfile;
7124   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7125   CORE_ADDR addr = 0;
7126   const char *actual_name = NULL;
7127   CORE_ADDR baseaddr;
7128   char *built_actual_name;
7129
7130   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7131
7132   built_actual_name = partial_die_full_name (pdi, cu);
7133   if (built_actual_name != NULL)
7134     actual_name = built_actual_name;
7135
7136   if (actual_name == NULL)
7137     actual_name = pdi->name;
7138
7139   switch (pdi->tag)
7140     {
7141     case DW_TAG_subprogram:
7142       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7143       if (pdi->is_external || cu->language == language_ada)
7144         {
7145           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7146              of the global scope.  But in Ada, we want to be able to access
7147              nested procedures globally.  So all Ada subprograms are stored
7148              in the global scope.  */
7149           add_psymbol_to_list (actual_name, strlen (actual_name),
7150                                built_actual_name != NULL,
7151                                VAR_DOMAIN, LOC_BLOCK,
7152                                &objfile->global_psymbols,
7153                                addr, cu->language, objfile);
7154         }
7155       else
7156         {
7157           add_psymbol_to_list (actual_name, strlen (actual_name),
7158                                built_actual_name != NULL,
7159                                VAR_DOMAIN, LOC_BLOCK,
7160                                &objfile->static_psymbols,
7161                                addr, cu->language, objfile);
7162         }
7163
7164       if (pdi->main_subprogram && actual_name != NULL)
7165         set_objfile_main_name (objfile, actual_name, cu->language);
7166       break;
7167     case DW_TAG_constant:
7168       {
7169         struct psymbol_allocation_list *list;
7170
7171         if (pdi->is_external)
7172           list = &objfile->global_psymbols;
7173         else
7174           list = &objfile->static_psymbols;
7175         add_psymbol_to_list (actual_name, strlen (actual_name),
7176                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7177                              list, 0, cu->language, objfile);
7178       }
7179       break;
7180     case DW_TAG_variable:
7181       if (pdi->d.locdesc)
7182         addr = decode_locdesc (pdi->d.locdesc, cu);
7183
7184       if (pdi->d.locdesc
7185           && addr == 0
7186           && !dwarf2_per_objfile->has_section_at_zero)
7187         {
7188           /* A global or static variable may also have been stripped
7189              out by the linker if unused, in which case its address
7190              will be nullified; do not add such variables into partial
7191              symbol table then.  */
7192         }
7193       else if (pdi->is_external)
7194         {
7195           /* Global Variable.
7196              Don't enter into the minimal symbol tables as there is
7197              a minimal symbol table entry from the ELF symbols already.
7198              Enter into partial symbol table if it has a location
7199              descriptor or a type.
7200              If the location descriptor is missing, new_symbol will create
7201              a LOC_UNRESOLVED symbol, the address of the variable will then
7202              be determined from the minimal symbol table whenever the variable
7203              is referenced.
7204              The address for the partial symbol table entry is not
7205              used by GDB, but it comes in handy for debugging partial symbol
7206              table building.  */
7207
7208           if (pdi->d.locdesc || pdi->has_type)
7209             add_psymbol_to_list (actual_name, strlen (actual_name),
7210                                  built_actual_name != NULL,
7211                                  VAR_DOMAIN, LOC_STATIC,
7212                                  &objfile->global_psymbols,
7213                                  addr + baseaddr,
7214                                  cu->language, objfile);
7215         }
7216       else
7217         {
7218           int has_loc = pdi->d.locdesc != NULL;
7219
7220           /* Static Variable.  Skip symbols whose value we cannot know (those
7221              without location descriptors or constant values).  */
7222           if (!has_loc && !pdi->has_const_value)
7223             {
7224               xfree (built_actual_name);
7225               return;
7226             }
7227
7228           add_psymbol_to_list (actual_name, strlen (actual_name),
7229                                built_actual_name != NULL,
7230                                VAR_DOMAIN, LOC_STATIC,
7231                                &objfile->static_psymbols,
7232                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7233                                cu->language, objfile);
7234         }
7235       break;
7236     case DW_TAG_typedef:
7237     case DW_TAG_base_type:
7238     case DW_TAG_subrange_type:
7239       add_psymbol_to_list (actual_name, strlen (actual_name),
7240                            built_actual_name != NULL,
7241                            VAR_DOMAIN, LOC_TYPEDEF,
7242                            &objfile->static_psymbols,
7243                            0, cu->language, objfile);
7244       break;
7245     case DW_TAG_imported_declaration:
7246     case DW_TAG_namespace:
7247       add_psymbol_to_list (actual_name, strlen (actual_name),
7248                            built_actual_name != NULL,
7249                            VAR_DOMAIN, LOC_TYPEDEF,
7250                            &objfile->global_psymbols,
7251                            0, cu->language, objfile);
7252       break;
7253     case DW_TAG_module:
7254       add_psymbol_to_list (actual_name, strlen (actual_name),
7255                            built_actual_name != NULL,
7256                            MODULE_DOMAIN, LOC_TYPEDEF,
7257                            &objfile->global_psymbols,
7258                            0, cu->language, objfile);
7259       break;
7260     case DW_TAG_class_type:
7261     case DW_TAG_interface_type:
7262     case DW_TAG_structure_type:
7263     case DW_TAG_union_type:
7264     case DW_TAG_enumeration_type:
7265       /* Skip external references.  The DWARF standard says in the section
7266          about "Structure, Union, and Class Type Entries": "An incomplete
7267          structure, union or class type is represented by a structure,
7268          union or class entry that does not have a byte size attribute
7269          and that has a DW_AT_declaration attribute."  */
7270       if (!pdi->has_byte_size && pdi->is_declaration)
7271         {
7272           xfree (built_actual_name);
7273           return;
7274         }
7275
7276       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7277          static vs. global.  */
7278       add_psymbol_to_list (actual_name, strlen (actual_name),
7279                            built_actual_name != NULL,
7280                            STRUCT_DOMAIN, LOC_TYPEDEF,
7281                            cu->language == language_cplus
7282                            ? &objfile->global_psymbols
7283                            : &objfile->static_psymbols,
7284                            0, cu->language, objfile);
7285
7286       break;
7287     case DW_TAG_enumerator:
7288       add_psymbol_to_list (actual_name, strlen (actual_name),
7289                            built_actual_name != NULL,
7290                            VAR_DOMAIN, LOC_CONST,
7291                            cu->language == language_cplus
7292                            ? &objfile->global_psymbols
7293                            : &objfile->static_psymbols,
7294                            0, cu->language, objfile);
7295       break;
7296     default:
7297       break;
7298     }
7299
7300   xfree (built_actual_name);
7301 }
7302
7303 /* Read a partial die corresponding to a namespace; also, add a symbol
7304    corresponding to that namespace to the symbol table.  NAMESPACE is
7305    the name of the enclosing namespace.  */
7306
7307 static void
7308 add_partial_namespace (struct partial_die_info *pdi,
7309                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7310                        int set_addrmap, struct dwarf2_cu *cu)
7311 {
7312   /* Add a symbol for the namespace.  */
7313
7314   add_partial_symbol (pdi, cu);
7315
7316   /* Now scan partial symbols in that namespace.  */
7317
7318   if (pdi->has_children)
7319     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7320 }
7321
7322 /* Read a partial die corresponding to a Fortran module.  */
7323
7324 static void
7325 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7326                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7327 {
7328   /* Add a symbol for the namespace.  */
7329
7330   add_partial_symbol (pdi, cu);
7331
7332   /* Now scan partial symbols in that module.  */
7333
7334   if (pdi->has_children)
7335     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7336 }
7337
7338 /* Read a partial die corresponding to a subprogram and create a partial
7339    symbol for that subprogram.  When the CU language allows it, this
7340    routine also defines a partial symbol for each nested subprogram
7341    that this subprogram contains.  If SET_ADDRMAP is true, record the
7342    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7343    and highest PC values found in PDI.
7344
7345    PDI may also be a lexical block, in which case we simply search
7346    recursively for subprograms defined inside that lexical block.
7347    Again, this is only performed when the CU language allows this
7348    type of definitions.  */
7349
7350 static void
7351 add_partial_subprogram (struct partial_die_info *pdi,
7352                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7353                         int set_addrmap, struct dwarf2_cu *cu)
7354 {
7355   if (pdi->tag == DW_TAG_subprogram)
7356     {
7357       if (pdi->has_pc_info)
7358         {
7359           if (pdi->lowpc < *lowpc)
7360             *lowpc = pdi->lowpc;
7361           if (pdi->highpc > *highpc)
7362             *highpc = pdi->highpc;
7363           if (set_addrmap)
7364             {
7365               struct objfile *objfile = cu->objfile;
7366               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7367               CORE_ADDR baseaddr;
7368               CORE_ADDR highpc;
7369               CORE_ADDR lowpc;
7370
7371               baseaddr = ANOFFSET (objfile->section_offsets,
7372                                    SECT_OFF_TEXT (objfile));
7373               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7374                                                   pdi->lowpc + baseaddr);
7375               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7376                                                    pdi->highpc + baseaddr);
7377               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7378                                  cu->per_cu->v.psymtab);
7379             }
7380         }
7381
7382       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7383         {
7384           if (!pdi->is_declaration)
7385             /* Ignore subprogram DIEs that do not have a name, they are
7386                illegal.  Do not emit a complaint at this point, we will
7387                do so when we convert this psymtab into a symtab.  */
7388             if (pdi->name)
7389               add_partial_symbol (pdi, cu);
7390         }
7391     }
7392
7393   if (! pdi->has_children)
7394     return;
7395
7396   if (cu->language == language_ada)
7397     {
7398       pdi = pdi->die_child;
7399       while (pdi != NULL)
7400         {
7401           fixup_partial_die (pdi, cu);
7402           if (pdi->tag == DW_TAG_subprogram
7403               || pdi->tag == DW_TAG_lexical_block)
7404             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7405           pdi = pdi->die_sibling;
7406         }
7407     }
7408 }
7409
7410 /* Read a partial die corresponding to an enumeration type.  */
7411
7412 static void
7413 add_partial_enumeration (struct partial_die_info *enum_pdi,
7414                          struct dwarf2_cu *cu)
7415 {
7416   struct partial_die_info *pdi;
7417
7418   if (enum_pdi->name != NULL)
7419     add_partial_symbol (enum_pdi, cu);
7420
7421   pdi = enum_pdi->die_child;
7422   while (pdi)
7423     {
7424       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7425         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7426       else
7427         add_partial_symbol (pdi, cu);
7428       pdi = pdi->die_sibling;
7429     }
7430 }
7431
7432 /* Return the initial uleb128 in the die at INFO_PTR.  */
7433
7434 static unsigned int
7435 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7436 {
7437   unsigned int bytes_read;
7438
7439   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7440 }
7441
7442 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7443    Return the corresponding abbrev, or NULL if the number is zero (indicating
7444    an empty DIE).  In either case *BYTES_READ will be set to the length of
7445    the initial number.  */
7446
7447 static struct abbrev_info *
7448 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7449                  struct dwarf2_cu *cu)
7450 {
7451   bfd *abfd = cu->objfile->obfd;
7452   unsigned int abbrev_number;
7453   struct abbrev_info *abbrev;
7454
7455   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7456
7457   if (abbrev_number == 0)
7458     return NULL;
7459
7460   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7461   if (!abbrev)
7462     {
7463       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7464                " at offset 0x%x [in module %s]"),
7465              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7466              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7467     }
7468
7469   return abbrev;
7470 }
7471
7472 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7473    Returns a pointer to the end of a series of DIEs, terminated by an empty
7474    DIE.  Any children of the skipped DIEs will also be skipped.  */
7475
7476 static const gdb_byte *
7477 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7478 {
7479   struct dwarf2_cu *cu = reader->cu;
7480   struct abbrev_info *abbrev;
7481   unsigned int bytes_read;
7482
7483   while (1)
7484     {
7485       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7486       if (abbrev == NULL)
7487         return info_ptr + bytes_read;
7488       else
7489         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7490     }
7491 }
7492
7493 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7494    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7495    abbrev corresponding to that skipped uleb128 should be passed in
7496    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7497    children.  */
7498
7499 static const gdb_byte *
7500 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7501               struct abbrev_info *abbrev)
7502 {
7503   unsigned int bytes_read;
7504   struct attribute attr;
7505   bfd *abfd = reader->abfd;
7506   struct dwarf2_cu *cu = reader->cu;
7507   const gdb_byte *buffer = reader->buffer;
7508   const gdb_byte *buffer_end = reader->buffer_end;
7509   unsigned int form, i;
7510
7511   for (i = 0; i < abbrev->num_attrs; i++)
7512     {
7513       /* The only abbrev we care about is DW_AT_sibling.  */
7514       if (abbrev->attrs[i].name == DW_AT_sibling)
7515         {
7516           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7517           if (attr.form == DW_FORM_ref_addr)
7518             complaint (&symfile_complaints,
7519                        _("ignoring absolute DW_AT_sibling"));
7520           else
7521             {
7522               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7523               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7524
7525               if (sibling_ptr < info_ptr)
7526                 complaint (&symfile_complaints,
7527                            _("DW_AT_sibling points backwards"));
7528               else if (sibling_ptr > reader->buffer_end)
7529                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7530               else
7531                 return sibling_ptr;
7532             }
7533         }
7534
7535       /* If it isn't DW_AT_sibling, skip this attribute.  */
7536       form = abbrev->attrs[i].form;
7537     skip_attribute:
7538       switch (form)
7539         {
7540         case DW_FORM_ref_addr:
7541           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7542              and later it is offset sized.  */
7543           if (cu->header.version == 2)
7544             info_ptr += cu->header.addr_size;
7545           else
7546             info_ptr += cu->header.offset_size;
7547           break;
7548         case DW_FORM_GNU_ref_alt:
7549           info_ptr += cu->header.offset_size;
7550           break;
7551         case DW_FORM_addr:
7552           info_ptr += cu->header.addr_size;
7553           break;
7554         case DW_FORM_data1:
7555         case DW_FORM_ref1:
7556         case DW_FORM_flag:
7557           info_ptr += 1;
7558           break;
7559         case DW_FORM_flag_present:
7560         case DW_FORM_implicit_const:
7561           break;
7562         case DW_FORM_data2:
7563         case DW_FORM_ref2:
7564           info_ptr += 2;
7565           break;
7566         case DW_FORM_data4:
7567         case DW_FORM_ref4:
7568           info_ptr += 4;
7569           break;
7570         case DW_FORM_data8:
7571         case DW_FORM_ref8:
7572         case DW_FORM_ref_sig8:
7573           info_ptr += 8;
7574           break;
7575         case DW_FORM_data16:
7576           info_ptr += 16;
7577           break;
7578         case DW_FORM_string:
7579           read_direct_string (abfd, info_ptr, &bytes_read);
7580           info_ptr += bytes_read;
7581           break;
7582         case DW_FORM_sec_offset:
7583         case DW_FORM_strp:
7584         case DW_FORM_GNU_strp_alt:
7585           info_ptr += cu->header.offset_size;
7586           break;
7587         case DW_FORM_exprloc:
7588         case DW_FORM_block:
7589           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7590           info_ptr += bytes_read;
7591           break;
7592         case DW_FORM_block1:
7593           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7594           break;
7595         case DW_FORM_block2:
7596           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7597           break;
7598         case DW_FORM_block4:
7599           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7600           break;
7601         case DW_FORM_sdata:
7602         case DW_FORM_udata:
7603         case DW_FORM_ref_udata:
7604         case DW_FORM_GNU_addr_index:
7605         case DW_FORM_GNU_str_index:
7606           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7607           break;
7608         case DW_FORM_indirect:
7609           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7610           info_ptr += bytes_read;
7611           /* We need to continue parsing from here, so just go back to
7612              the top.  */
7613           goto skip_attribute;
7614
7615         default:
7616           error (_("Dwarf Error: Cannot handle %s "
7617                    "in DWARF reader [in module %s]"),
7618                  dwarf_form_name (form),
7619                  bfd_get_filename (abfd));
7620         }
7621     }
7622
7623   if (abbrev->has_children)
7624     return skip_children (reader, info_ptr);
7625   else
7626     return info_ptr;
7627 }
7628
7629 /* Locate ORIG_PDI's sibling.
7630    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7631
7632 static const gdb_byte *
7633 locate_pdi_sibling (const struct die_reader_specs *reader,
7634                     struct partial_die_info *orig_pdi,
7635                     const gdb_byte *info_ptr)
7636 {
7637   /* Do we know the sibling already?  */
7638
7639   if (orig_pdi->sibling)
7640     return orig_pdi->sibling;
7641
7642   /* Are there any children to deal with?  */
7643
7644   if (!orig_pdi->has_children)
7645     return info_ptr;
7646
7647   /* Skip the children the long way.  */
7648
7649   return skip_children (reader, info_ptr);
7650 }
7651
7652 /* Expand this partial symbol table into a full symbol table.  SELF is
7653    not NULL.  */
7654
7655 static void
7656 dwarf2_read_symtab (struct partial_symtab *self,
7657                     struct objfile *objfile)
7658 {
7659   if (self->readin)
7660     {
7661       warning (_("bug: psymtab for %s is already read in."),
7662                self->filename);
7663     }
7664   else
7665     {
7666       if (info_verbose)
7667         {
7668           printf_filtered (_("Reading in symbols for %s..."),
7669                            self->filename);
7670           gdb_flush (gdb_stdout);
7671         }
7672
7673       /* Restore our global data.  */
7674       dwarf2_per_objfile
7675         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7676                                                       dwarf2_objfile_data_key);
7677
7678       /* If this psymtab is constructed from a debug-only objfile, the
7679          has_section_at_zero flag will not necessarily be correct.  We
7680          can get the correct value for this flag by looking at the data
7681          associated with the (presumably stripped) associated objfile.  */
7682       if (objfile->separate_debug_objfile_backlink)
7683         {
7684           struct dwarf2_per_objfile *dpo_backlink
7685             = ((struct dwarf2_per_objfile *)
7686                objfile_data (objfile->separate_debug_objfile_backlink,
7687                              dwarf2_objfile_data_key));
7688
7689           dwarf2_per_objfile->has_section_at_zero
7690             = dpo_backlink->has_section_at_zero;
7691         }
7692
7693       dwarf2_per_objfile->reading_partial_symbols = 0;
7694
7695       psymtab_to_symtab_1 (self);
7696
7697       /* Finish up the debug error message.  */
7698       if (info_verbose)
7699         printf_filtered (_("done.\n"));
7700     }
7701
7702   process_cu_includes ();
7703 }
7704 \f
7705 /* Reading in full CUs.  */
7706
7707 /* Add PER_CU to the queue.  */
7708
7709 static void
7710 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
7711                  enum language pretend_language)
7712 {
7713   struct dwarf2_queue_item *item;
7714
7715   per_cu->queued = 1;
7716   item = XNEW (struct dwarf2_queue_item);
7717   item->per_cu = per_cu;
7718   item->pretend_language = pretend_language;
7719   item->next = NULL;
7720
7721   if (dwarf2_queue == NULL)
7722     dwarf2_queue = item;
7723   else
7724     dwarf2_queue_tail->next = item;
7725
7726   dwarf2_queue_tail = item;
7727 }
7728
7729 /* If PER_CU is not yet queued, add it to the queue.
7730    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
7731    dependency.
7732    The result is non-zero if PER_CU was queued, otherwise the result is zero
7733    meaning either PER_CU is already queued or it is already loaded.
7734
7735    N.B. There is an invariant here that if a CU is queued then it is loaded.
7736    The caller is required to load PER_CU if we return non-zero.  */
7737
7738 static int
7739 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
7740                        struct dwarf2_per_cu_data *per_cu,
7741                        enum language pretend_language)
7742 {
7743   /* We may arrive here during partial symbol reading, if we need full
7744      DIEs to process an unusual case (e.g. template arguments).  Do
7745      not queue PER_CU, just tell our caller to load its DIEs.  */
7746   if (dwarf2_per_objfile->reading_partial_symbols)
7747     {
7748       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
7749         return 1;
7750       return 0;
7751     }
7752
7753   /* Mark the dependence relation so that we don't flush PER_CU
7754      too early.  */
7755   if (dependent_cu != NULL)
7756     dwarf2_add_dependence (dependent_cu, per_cu);
7757
7758   /* If it's already on the queue, we have nothing to do.  */
7759   if (per_cu->queued)
7760     return 0;
7761
7762   /* If the compilation unit is already loaded, just mark it as
7763      used.  */
7764   if (per_cu->cu != NULL)
7765     {
7766       per_cu->cu->last_used = 0;
7767       return 0;
7768     }
7769
7770   /* Add it to the queue.  */
7771   queue_comp_unit (per_cu, pretend_language);
7772
7773   return 1;
7774 }
7775
7776 /* Process the queue.  */
7777
7778 static void
7779 process_queue (void)
7780 {
7781   struct dwarf2_queue_item *item, *next_item;
7782
7783   if (dwarf_read_debug)
7784     {
7785       fprintf_unfiltered (gdb_stdlog,
7786                           "Expanding one or more symtabs of objfile %s ...\n",
7787                           objfile_name (dwarf2_per_objfile->objfile));
7788     }
7789
7790   /* The queue starts out with one item, but following a DIE reference
7791      may load a new CU, adding it to the end of the queue.  */
7792   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
7793     {
7794       if ((dwarf2_per_objfile->using_index
7795            ? !item->per_cu->v.quick->compunit_symtab
7796            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
7797           /* Skip dummy CUs.  */
7798           && item->per_cu->cu != NULL)
7799         {
7800           struct dwarf2_per_cu_data *per_cu = item->per_cu;
7801           unsigned int debug_print_threshold;
7802           char buf[100];
7803
7804           if (per_cu->is_debug_types)
7805             {
7806               struct signatured_type *sig_type =
7807                 (struct signatured_type *) per_cu;
7808
7809               sprintf (buf, "TU %s at offset 0x%x",
7810                        hex_string (sig_type->signature),
7811                        to_underlying (per_cu->sect_off));
7812               /* There can be 100s of TUs.
7813                  Only print them in verbose mode.  */
7814               debug_print_threshold = 2;
7815             }
7816           else
7817             {
7818               sprintf (buf, "CU at offset 0x%x",
7819                        to_underlying (per_cu->sect_off));
7820               debug_print_threshold = 1;
7821             }
7822
7823           if (dwarf_read_debug >= debug_print_threshold)
7824             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
7825
7826           if (per_cu->is_debug_types)
7827             process_full_type_unit (per_cu, item->pretend_language);
7828           else
7829             process_full_comp_unit (per_cu, item->pretend_language);
7830
7831           if (dwarf_read_debug >= debug_print_threshold)
7832             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
7833         }
7834
7835       item->per_cu->queued = 0;
7836       next_item = item->next;
7837       xfree (item);
7838     }
7839
7840   dwarf2_queue_tail = NULL;
7841
7842   if (dwarf_read_debug)
7843     {
7844       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
7845                           objfile_name (dwarf2_per_objfile->objfile));
7846     }
7847 }
7848
7849 /* Free all allocated queue entries.  This function only releases anything if
7850    an error was thrown; if the queue was processed then it would have been
7851    freed as we went along.  */
7852
7853 static void
7854 dwarf2_release_queue (void *dummy)
7855 {
7856   struct dwarf2_queue_item *item, *last;
7857
7858   item = dwarf2_queue;
7859   while (item)
7860     {
7861       /* Anything still marked queued is likely to be in an
7862          inconsistent state, so discard it.  */
7863       if (item->per_cu->queued)
7864         {
7865           if (item->per_cu->cu != NULL)
7866             free_one_cached_comp_unit (item->per_cu);
7867           item->per_cu->queued = 0;
7868         }
7869
7870       last = item;
7871       item = item->next;
7872       xfree (last);
7873     }
7874
7875   dwarf2_queue = dwarf2_queue_tail = NULL;
7876 }
7877
7878 /* Read in full symbols for PST, and anything it depends on.  */
7879
7880 static void
7881 psymtab_to_symtab_1 (struct partial_symtab *pst)
7882 {
7883   struct dwarf2_per_cu_data *per_cu;
7884   int i;
7885
7886   if (pst->readin)
7887     return;
7888
7889   for (i = 0; i < pst->number_of_dependencies; i++)
7890     if (!pst->dependencies[i]->readin
7891         && pst->dependencies[i]->user == NULL)
7892       {
7893         /* Inform about additional files that need to be read in.  */
7894         if (info_verbose)
7895           {
7896             /* FIXME: i18n: Need to make this a single string.  */
7897             fputs_filtered (" ", gdb_stdout);
7898             wrap_here ("");
7899             fputs_filtered ("and ", gdb_stdout);
7900             wrap_here ("");
7901             printf_filtered ("%s...", pst->dependencies[i]->filename);
7902             wrap_here ("");     /* Flush output.  */
7903             gdb_flush (gdb_stdout);
7904           }
7905         psymtab_to_symtab_1 (pst->dependencies[i]);
7906       }
7907
7908   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
7909
7910   if (per_cu == NULL)
7911     {
7912       /* It's an include file, no symbols to read for it.
7913          Everything is in the parent symtab.  */
7914       pst->readin = 1;
7915       return;
7916     }
7917
7918   dw2_do_instantiate_symtab (per_cu);
7919 }
7920
7921 /* Trivial hash function for die_info: the hash value of a DIE
7922    is its offset in .debug_info for this objfile.  */
7923
7924 static hashval_t
7925 die_hash (const void *item)
7926 {
7927   const struct die_info *die = (const struct die_info *) item;
7928
7929   return to_underlying (die->sect_off);
7930 }
7931
7932 /* Trivial comparison function for die_info structures: two DIEs
7933    are equal if they have the same offset.  */
7934
7935 static int
7936 die_eq (const void *item_lhs, const void *item_rhs)
7937 {
7938   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
7939   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
7940
7941   return die_lhs->sect_off == die_rhs->sect_off;
7942 }
7943
7944 /* die_reader_func for load_full_comp_unit.
7945    This is identical to read_signatured_type_reader,
7946    but is kept separate for now.  */
7947
7948 static void
7949 load_full_comp_unit_reader (const struct die_reader_specs *reader,
7950                             const gdb_byte *info_ptr,
7951                             struct die_info *comp_unit_die,
7952                             int has_children,
7953                             void *data)
7954 {
7955   struct dwarf2_cu *cu = reader->cu;
7956   enum language *language_ptr = (enum language *) data;
7957
7958   gdb_assert (cu->die_hash == NULL);
7959   cu->die_hash =
7960     htab_create_alloc_ex (cu->header.length / 12,
7961                           die_hash,
7962                           die_eq,
7963                           NULL,
7964                           &cu->comp_unit_obstack,
7965                           hashtab_obstack_allocate,
7966                           dummy_obstack_deallocate);
7967
7968   if (has_children)
7969     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
7970                                                   &info_ptr, comp_unit_die);
7971   cu->dies = comp_unit_die;
7972   /* comp_unit_die is not stored in die_hash, no need.  */
7973
7974   /* We try not to read any attributes in this function, because not
7975      all CUs needed for references have been loaded yet, and symbol
7976      table processing isn't initialized.  But we have to set the CU language,
7977      or we won't be able to build types correctly.
7978      Similarly, if we do not read the producer, we can not apply
7979      producer-specific interpretation.  */
7980   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
7981 }
7982
7983 /* Load the DIEs associated with PER_CU into memory.  */
7984
7985 static void
7986 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
7987                      enum language pretend_language)
7988 {
7989   gdb_assert (! this_cu->is_debug_types);
7990
7991   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7992                            load_full_comp_unit_reader, &pretend_language);
7993 }
7994
7995 /* Add a DIE to the delayed physname list.  */
7996
7997 static void
7998 add_to_method_list (struct type *type, int fnfield_index, int index,
7999                     const char *name, struct die_info *die,
8000                     struct dwarf2_cu *cu)
8001 {
8002   struct delayed_method_info mi;
8003   mi.type = type;
8004   mi.fnfield_index = fnfield_index;
8005   mi.index = index;
8006   mi.name = name;
8007   mi.die = die;
8008   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8009 }
8010
8011 /* A cleanup for freeing the delayed method list.  */
8012
8013 static void
8014 free_delayed_list (void *ptr)
8015 {
8016   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8017   if (cu->method_list != NULL)
8018     {
8019       VEC_free (delayed_method_info, cu->method_list);
8020       cu->method_list = NULL;
8021     }
8022 }
8023
8024 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8025    "const" / "volatile".  If so, decrements LEN by the length of the
8026    modifier and return true.  Otherwise return false.  */
8027
8028 template<size_t N>
8029 static bool
8030 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8031 {
8032   size_t mod_len = sizeof (mod) - 1;
8033   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8034     {
8035       len -= mod_len;
8036       return true;
8037     }
8038   return false;
8039 }
8040
8041 /* Compute the physnames of any methods on the CU's method list.
8042
8043    The computation of method physnames is delayed in order to avoid the
8044    (bad) condition that one of the method's formal parameters is of an as yet
8045    incomplete type.  */
8046
8047 static void
8048 compute_delayed_physnames (struct dwarf2_cu *cu)
8049 {
8050   int i;
8051   struct delayed_method_info *mi;
8052
8053   /* Only C++ delays computing physnames.  */
8054   if (VEC_empty (delayed_method_info, cu->method_list))
8055     return;
8056   gdb_assert (cu->language == language_cplus);
8057
8058   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8059     {
8060       const char *physname;
8061       struct fn_fieldlist *fn_flp
8062         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8063       physname = dwarf2_physname (mi->name, mi->die, cu);
8064       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8065         = physname ? physname : "";
8066
8067       /* Since there's no tag to indicate whether a method is a
8068          const/volatile overload, extract that information out of the
8069          demangled name.  */
8070       if (physname != NULL)
8071         {
8072           size_t len = strlen (physname);
8073
8074           while (1)
8075             {
8076               if (physname[len] == ')') /* shortcut */
8077                 break;
8078               else if (check_modifier (physname, len, " const"))
8079                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8080               else if (check_modifier (physname, len, " volatile"))
8081                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8082               else
8083                 break;
8084             }
8085         }
8086     }
8087 }
8088
8089 /* Go objects should be embedded in a DW_TAG_module DIE,
8090    and it's not clear if/how imported objects will appear.
8091    To keep Go support simple until that's worked out,
8092    go back through what we've read and create something usable.
8093    We could do this while processing each DIE, and feels kinda cleaner,
8094    but that way is more invasive.
8095    This is to, for example, allow the user to type "p var" or "b main"
8096    without having to specify the package name, and allow lookups
8097    of module.object to work in contexts that use the expression
8098    parser.  */
8099
8100 static void
8101 fixup_go_packaging (struct dwarf2_cu *cu)
8102 {
8103   char *package_name = NULL;
8104   struct pending *list;
8105   int i;
8106
8107   for (list = global_symbols; list != NULL; list = list->next)
8108     {
8109       for (i = 0; i < list->nsyms; ++i)
8110         {
8111           struct symbol *sym = list->symbol[i];
8112
8113           if (SYMBOL_LANGUAGE (sym) == language_go
8114               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8115             {
8116               char *this_package_name = go_symbol_package_name (sym);
8117
8118               if (this_package_name == NULL)
8119                 continue;
8120               if (package_name == NULL)
8121                 package_name = this_package_name;
8122               else
8123                 {
8124                   if (strcmp (package_name, this_package_name) != 0)
8125                     complaint (&symfile_complaints,
8126                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8127                                (symbol_symtab (sym) != NULL
8128                                 ? symtab_to_filename_for_display
8129                                     (symbol_symtab (sym))
8130                                 : objfile_name (cu->objfile)),
8131                                this_package_name, package_name);
8132                   xfree (this_package_name);
8133                 }
8134             }
8135         }
8136     }
8137
8138   if (package_name != NULL)
8139     {
8140       struct objfile *objfile = cu->objfile;
8141       const char *saved_package_name
8142         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8143                                         package_name,
8144                                         strlen (package_name));
8145       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8146                                      saved_package_name);
8147       struct symbol *sym;
8148
8149       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8150
8151       sym = allocate_symbol (objfile);
8152       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8153       SYMBOL_SET_NAMES (sym, saved_package_name,
8154                         strlen (saved_package_name), 0, objfile);
8155       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8156          e.g., "main" finds the "main" module and not C's main().  */
8157       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8158       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8159       SYMBOL_TYPE (sym) = type;
8160
8161       add_symbol_to_list (sym, &global_symbols);
8162
8163       xfree (package_name);
8164     }
8165 }
8166
8167 /* Return the symtab for PER_CU.  This works properly regardless of
8168    whether we're using the index or psymtabs.  */
8169
8170 static struct compunit_symtab *
8171 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8172 {
8173   return (dwarf2_per_objfile->using_index
8174           ? per_cu->v.quick->compunit_symtab
8175           : per_cu->v.psymtab->compunit_symtab);
8176 }
8177
8178 /* A helper function for computing the list of all symbol tables
8179    included by PER_CU.  */
8180
8181 static void
8182 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8183                                 htab_t all_children, htab_t all_type_symtabs,
8184                                 struct dwarf2_per_cu_data *per_cu,
8185                                 struct compunit_symtab *immediate_parent)
8186 {
8187   void **slot;
8188   int ix;
8189   struct compunit_symtab *cust;
8190   struct dwarf2_per_cu_data *iter;
8191
8192   slot = htab_find_slot (all_children, per_cu, INSERT);
8193   if (*slot != NULL)
8194     {
8195       /* This inclusion and its children have been processed.  */
8196       return;
8197     }
8198
8199   *slot = per_cu;
8200   /* Only add a CU if it has a symbol table.  */
8201   cust = get_compunit_symtab (per_cu);
8202   if (cust != NULL)
8203     {
8204       /* If this is a type unit only add its symbol table if we haven't
8205          seen it yet (type unit per_cu's can share symtabs).  */
8206       if (per_cu->is_debug_types)
8207         {
8208           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8209           if (*slot == NULL)
8210             {
8211               *slot = cust;
8212               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8213               if (cust->user == NULL)
8214                 cust->user = immediate_parent;
8215             }
8216         }
8217       else
8218         {
8219           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8220           if (cust->user == NULL)
8221             cust->user = immediate_parent;
8222         }
8223     }
8224
8225   for (ix = 0;
8226        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8227        ++ix)
8228     {
8229       recursively_compute_inclusions (result, all_children,
8230                                       all_type_symtabs, iter, cust);
8231     }
8232 }
8233
8234 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8235    PER_CU.  */
8236
8237 static void
8238 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8239 {
8240   gdb_assert (! per_cu->is_debug_types);
8241
8242   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8243     {
8244       int ix, len;
8245       struct dwarf2_per_cu_data *per_cu_iter;
8246       struct compunit_symtab *compunit_symtab_iter;
8247       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8248       htab_t all_children, all_type_symtabs;
8249       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8250
8251       /* If we don't have a symtab, we can just skip this case.  */
8252       if (cust == NULL)
8253         return;
8254
8255       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8256                                         NULL, xcalloc, xfree);
8257       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8258                                             NULL, xcalloc, xfree);
8259
8260       for (ix = 0;
8261            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8262                         ix, per_cu_iter);
8263            ++ix)
8264         {
8265           recursively_compute_inclusions (&result_symtabs, all_children,
8266                                           all_type_symtabs, per_cu_iter,
8267                                           cust);
8268         }
8269
8270       /* Now we have a transitive closure of all the included symtabs.  */
8271       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8272       cust->includes
8273         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8274                      struct compunit_symtab *, len + 1);
8275       for (ix = 0;
8276            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8277                         compunit_symtab_iter);
8278            ++ix)
8279         cust->includes[ix] = compunit_symtab_iter;
8280       cust->includes[len] = NULL;
8281
8282       VEC_free (compunit_symtab_ptr, result_symtabs);
8283       htab_delete (all_children);
8284       htab_delete (all_type_symtabs);
8285     }
8286 }
8287
8288 /* Compute the 'includes' field for the symtabs of all the CUs we just
8289    read.  */
8290
8291 static void
8292 process_cu_includes (void)
8293 {
8294   int ix;
8295   struct dwarf2_per_cu_data *iter;
8296
8297   for (ix = 0;
8298        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8299                     ix, iter);
8300        ++ix)
8301     {
8302       if (! iter->is_debug_types)
8303         compute_compunit_symtab_includes (iter);
8304     }
8305
8306   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8307 }
8308
8309 /* Generate full symbol information for PER_CU, whose DIEs have
8310    already been loaded into memory.  */
8311
8312 static void
8313 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8314                         enum language pretend_language)
8315 {
8316   struct dwarf2_cu *cu = per_cu->cu;
8317   struct objfile *objfile = per_cu->objfile;
8318   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8319   CORE_ADDR lowpc, highpc;
8320   struct compunit_symtab *cust;
8321   struct cleanup *back_to, *delayed_list_cleanup;
8322   CORE_ADDR baseaddr;
8323   struct block *static_block;
8324   CORE_ADDR addr;
8325
8326   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8327
8328   buildsym_init ();
8329   back_to = make_cleanup (really_free_pendings, NULL);
8330   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8331
8332   cu->list_in_scope = &file_symbols;
8333
8334   cu->language = pretend_language;
8335   cu->language_defn = language_def (cu->language);
8336
8337   /* Do line number decoding in read_file_scope () */
8338   process_die (cu->dies, cu);
8339
8340   /* For now fudge the Go package.  */
8341   if (cu->language == language_go)
8342     fixup_go_packaging (cu);
8343
8344   /* Now that we have processed all the DIEs in the CU, all the types 
8345      should be complete, and it should now be safe to compute all of the
8346      physnames.  */
8347   compute_delayed_physnames (cu);
8348   do_cleanups (delayed_list_cleanup);
8349
8350   /* Some compilers don't define a DW_AT_high_pc attribute for the
8351      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8352      it, by scanning the DIE's below the compilation unit.  */
8353   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8354
8355   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8356   static_block = end_symtab_get_static_block (addr, 0, 1);
8357
8358   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8359      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8360      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8361      addrmap to help ensure it has an accurate map of pc values belonging to
8362      this comp unit.  */
8363   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8364
8365   cust = end_symtab_from_static_block (static_block,
8366                                        SECT_OFF_TEXT (objfile), 0);
8367
8368   if (cust != NULL)
8369     {
8370       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8371
8372       /* Set symtab language to language from DW_AT_language.  If the
8373          compilation is from a C file generated by language preprocessors, do
8374          not set the language if it was already deduced by start_subfile.  */
8375       if (!(cu->language == language_c
8376             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8377         COMPUNIT_FILETABS (cust)->language = cu->language;
8378
8379       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8380          produce DW_AT_location with location lists but it can be possibly
8381          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8382          there were bugs in prologue debug info, fixed later in GCC-4.5
8383          by "unwind info for epilogues" patch (which is not directly related).
8384
8385          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8386          needed, it would be wrong due to missing DW_AT_producer there.
8387
8388          Still one can confuse GDB by using non-standard GCC compilation
8389          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8390          */ 
8391       if (cu->has_loclist && gcc_4_minor >= 5)
8392         cust->locations_valid = 1;
8393
8394       if (gcc_4_minor >= 5)
8395         cust->epilogue_unwind_valid = 1;
8396
8397       cust->call_site_htab = cu->call_site_htab;
8398     }
8399
8400   if (dwarf2_per_objfile->using_index)
8401     per_cu->v.quick->compunit_symtab = cust;
8402   else
8403     {
8404       struct partial_symtab *pst = per_cu->v.psymtab;
8405       pst->compunit_symtab = cust;
8406       pst->readin = 1;
8407     }
8408
8409   /* Push it for inclusion processing later.  */
8410   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8411
8412   do_cleanups (back_to);
8413 }
8414
8415 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8416    already been loaded into memory.  */
8417
8418 static void
8419 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8420                         enum language pretend_language)
8421 {
8422   struct dwarf2_cu *cu = per_cu->cu;
8423   struct objfile *objfile = per_cu->objfile;
8424   struct compunit_symtab *cust;
8425   struct cleanup *back_to, *delayed_list_cleanup;
8426   struct signatured_type *sig_type;
8427
8428   gdb_assert (per_cu->is_debug_types);
8429   sig_type = (struct signatured_type *) per_cu;
8430
8431   buildsym_init ();
8432   back_to = make_cleanup (really_free_pendings, NULL);
8433   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8434
8435   cu->list_in_scope = &file_symbols;
8436
8437   cu->language = pretend_language;
8438   cu->language_defn = language_def (cu->language);
8439
8440   /* The symbol tables are set up in read_type_unit_scope.  */
8441   process_die (cu->dies, cu);
8442
8443   /* For now fudge the Go package.  */
8444   if (cu->language == language_go)
8445     fixup_go_packaging (cu);
8446
8447   /* Now that we have processed all the DIEs in the CU, all the types 
8448      should be complete, and it should now be safe to compute all of the
8449      physnames.  */
8450   compute_delayed_physnames (cu);
8451   do_cleanups (delayed_list_cleanup);
8452
8453   /* TUs share symbol tables.
8454      If this is the first TU to use this symtab, complete the construction
8455      of it with end_expandable_symtab.  Otherwise, complete the addition of
8456      this TU's symbols to the existing symtab.  */
8457   if (sig_type->type_unit_group->compunit_symtab == NULL)
8458     {
8459       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8460       sig_type->type_unit_group->compunit_symtab = cust;
8461
8462       if (cust != NULL)
8463         {
8464           /* Set symtab language to language from DW_AT_language.  If the
8465              compilation is from a C file generated by language preprocessors,
8466              do not set the language if it was already deduced by
8467              start_subfile.  */
8468           if (!(cu->language == language_c
8469                 && COMPUNIT_FILETABS (cust)->language != language_c))
8470             COMPUNIT_FILETABS (cust)->language = cu->language;
8471         }
8472     }
8473   else
8474     {
8475       augment_type_symtab ();
8476       cust = sig_type->type_unit_group->compunit_symtab;
8477     }
8478
8479   if (dwarf2_per_objfile->using_index)
8480     per_cu->v.quick->compunit_symtab = cust;
8481   else
8482     {
8483       struct partial_symtab *pst = per_cu->v.psymtab;
8484       pst->compunit_symtab = cust;
8485       pst->readin = 1;
8486     }
8487
8488   do_cleanups (back_to);
8489 }
8490
8491 /* Process an imported unit DIE.  */
8492
8493 static void
8494 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8495 {
8496   struct attribute *attr;
8497
8498   /* For now we don't handle imported units in type units.  */
8499   if (cu->per_cu->is_debug_types)
8500     {
8501       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8502                " supported in type units [in module %s]"),
8503              objfile_name (cu->objfile));
8504     }
8505
8506   attr = dwarf2_attr (die, DW_AT_import, cu);
8507   if (attr != NULL)
8508     {
8509       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8510       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8511       dwarf2_per_cu_data *per_cu
8512         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8513
8514       /* If necessary, add it to the queue and load its DIEs.  */
8515       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8516         load_full_comp_unit (per_cu, cu->language);
8517
8518       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8519                      per_cu);
8520     }
8521 }
8522
8523 /* RAII object that represents a process_die scope: i.e.,
8524    starts/finishes processing a DIE.  */
8525 class process_die_scope
8526 {
8527 public:
8528   process_die_scope (die_info *die, dwarf2_cu *cu)
8529     : m_die (die), m_cu (cu)
8530   {
8531     /* We should only be processing DIEs not already in process.  */
8532     gdb_assert (!m_die->in_process);
8533     m_die->in_process = true;
8534   }
8535
8536   ~process_die_scope ()
8537   {
8538     m_die->in_process = false;
8539
8540     /* If we're done processing the DIE for the CU that owns the line
8541        header, we don't need the line header anymore.  */
8542     if (m_cu->line_header_die_owner == m_die)
8543       {
8544         delete m_cu->line_header;
8545         m_cu->line_header = NULL;
8546         m_cu->line_header_die_owner = NULL;
8547       }
8548   }
8549
8550 private:
8551   die_info *m_die;
8552   dwarf2_cu *m_cu;
8553 };
8554
8555 /* Process a die and its children.  */
8556
8557 static void
8558 process_die (struct die_info *die, struct dwarf2_cu *cu)
8559 {
8560   process_die_scope scope (die, cu);
8561
8562   switch (die->tag)
8563     {
8564     case DW_TAG_padding:
8565       break;
8566     case DW_TAG_compile_unit:
8567     case DW_TAG_partial_unit:
8568       read_file_scope (die, cu);
8569       break;
8570     case DW_TAG_type_unit:
8571       read_type_unit_scope (die, cu);
8572       break;
8573     case DW_TAG_subprogram:
8574     case DW_TAG_inlined_subroutine:
8575       read_func_scope (die, cu);
8576       break;
8577     case DW_TAG_lexical_block:
8578     case DW_TAG_try_block:
8579     case DW_TAG_catch_block:
8580       read_lexical_block_scope (die, cu);
8581       break;
8582     case DW_TAG_call_site:
8583     case DW_TAG_GNU_call_site:
8584       read_call_site_scope (die, cu);
8585       break;
8586     case DW_TAG_class_type:
8587     case DW_TAG_interface_type:
8588     case DW_TAG_structure_type:
8589     case DW_TAG_union_type:
8590       process_structure_scope (die, cu);
8591       break;
8592     case DW_TAG_enumeration_type:
8593       process_enumeration_scope (die, cu);
8594       break;
8595
8596     /* These dies have a type, but processing them does not create
8597        a symbol or recurse to process the children.  Therefore we can
8598        read them on-demand through read_type_die.  */
8599     case DW_TAG_subroutine_type:
8600     case DW_TAG_set_type:
8601     case DW_TAG_array_type:
8602     case DW_TAG_pointer_type:
8603     case DW_TAG_ptr_to_member_type:
8604     case DW_TAG_reference_type:
8605     case DW_TAG_rvalue_reference_type:
8606     case DW_TAG_string_type:
8607       break;
8608
8609     case DW_TAG_base_type:
8610     case DW_TAG_subrange_type:
8611     case DW_TAG_typedef:
8612       /* Add a typedef symbol for the type definition, if it has a
8613          DW_AT_name.  */
8614       new_symbol (die, read_type_die (die, cu), cu);
8615       break;
8616     case DW_TAG_common_block:
8617       read_common_block (die, cu);
8618       break;
8619     case DW_TAG_common_inclusion:
8620       break;
8621     case DW_TAG_namespace:
8622       cu->processing_has_namespace_info = 1;
8623       read_namespace (die, cu);
8624       break;
8625     case DW_TAG_module:
8626       cu->processing_has_namespace_info = 1;
8627       read_module (die, cu);
8628       break;
8629     case DW_TAG_imported_declaration:
8630       cu->processing_has_namespace_info = 1;
8631       if (read_namespace_alias (die, cu))
8632         break;
8633       /* The declaration is not a global namespace alias: fall through.  */
8634     case DW_TAG_imported_module:
8635       cu->processing_has_namespace_info = 1;
8636       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8637                                  || cu->language != language_fortran))
8638         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8639                    dwarf_tag_name (die->tag));
8640       read_import_statement (die, cu);
8641       break;
8642
8643     case DW_TAG_imported_unit:
8644       process_imported_unit_die (die, cu);
8645       break;
8646
8647     default:
8648       new_symbol (die, NULL, cu);
8649       break;
8650     }
8651 }
8652 \f
8653 /* DWARF name computation.  */
8654
8655 /* A helper function for dwarf2_compute_name which determines whether DIE
8656    needs to have the name of the scope prepended to the name listed in the
8657    die.  */
8658
8659 static int
8660 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8661 {
8662   struct attribute *attr;
8663
8664   switch (die->tag)
8665     {
8666     case DW_TAG_namespace:
8667     case DW_TAG_typedef:
8668     case DW_TAG_class_type:
8669     case DW_TAG_interface_type:
8670     case DW_TAG_structure_type:
8671     case DW_TAG_union_type:
8672     case DW_TAG_enumeration_type:
8673     case DW_TAG_enumerator:
8674     case DW_TAG_subprogram:
8675     case DW_TAG_inlined_subroutine:
8676     case DW_TAG_member:
8677     case DW_TAG_imported_declaration:
8678       return 1;
8679
8680     case DW_TAG_variable:
8681     case DW_TAG_constant:
8682       /* We only need to prefix "globally" visible variables.  These include
8683          any variable marked with DW_AT_external or any variable that
8684          lives in a namespace.  [Variables in anonymous namespaces
8685          require prefixing, but they are not DW_AT_external.]  */
8686
8687       if (dwarf2_attr (die, DW_AT_specification, cu))
8688         {
8689           struct dwarf2_cu *spec_cu = cu;
8690
8691           return die_needs_namespace (die_specification (die, &spec_cu),
8692                                       spec_cu);
8693         }
8694
8695       attr = dwarf2_attr (die, DW_AT_external, cu);
8696       if (attr == NULL && die->parent->tag != DW_TAG_namespace
8697           && die->parent->tag != DW_TAG_module)
8698         return 0;
8699       /* A variable in a lexical block of some kind does not need a
8700          namespace, even though in C++ such variables may be external
8701          and have a mangled name.  */
8702       if (die->parent->tag ==  DW_TAG_lexical_block
8703           || die->parent->tag ==  DW_TAG_try_block
8704           || die->parent->tag ==  DW_TAG_catch_block
8705           || die->parent->tag == DW_TAG_subprogram)
8706         return 0;
8707       return 1;
8708
8709     default:
8710       return 0;
8711     }
8712 }
8713
8714 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
8715    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8716    defined for the given DIE.  */
8717
8718 static struct attribute *
8719 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
8720 {
8721   struct attribute *attr;
8722
8723   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
8724   if (attr == NULL)
8725     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
8726
8727   return attr;
8728 }
8729
8730 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
8731    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
8732    defined for the given DIE.  */
8733
8734 static const char *
8735 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
8736 {
8737   const char *linkage_name;
8738
8739   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
8740   if (linkage_name == NULL)
8741     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
8742
8743   return linkage_name;
8744 }
8745
8746 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
8747    compute the physname for the object, which include a method's:
8748    - formal parameters (C++),
8749    - receiver type (Go),
8750
8751    The term "physname" is a bit confusing.
8752    For C++, for example, it is the demangled name.
8753    For Go, for example, it's the mangled name.
8754
8755    For Ada, return the DIE's linkage name rather than the fully qualified
8756    name.  PHYSNAME is ignored..
8757
8758    The result is allocated on the objfile_obstack and canonicalized.  */
8759
8760 static const char *
8761 dwarf2_compute_name (const char *name,
8762                      struct die_info *die, struct dwarf2_cu *cu,
8763                      int physname)
8764 {
8765   struct objfile *objfile = cu->objfile;
8766
8767   if (name == NULL)
8768     name = dwarf2_name (die, cu);
8769
8770   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
8771      but otherwise compute it by typename_concat inside GDB.
8772      FIXME: Actually this is not really true, or at least not always true.
8773      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
8774      Fortran names because there is no mangling standard.  So new_symbol_full
8775      will set the demangled name to the result of dwarf2_full_name, and it is
8776      the demangled name that GDB uses if it exists.  */
8777   if (cu->language == language_ada
8778       || (cu->language == language_fortran && physname))
8779     {
8780       /* For Ada unit, we prefer the linkage name over the name, as
8781          the former contains the exported name, which the user expects
8782          to be able to reference.  Ideally, we want the user to be able
8783          to reference this entity using either natural or linkage name,
8784          but we haven't started looking at this enhancement yet.  */
8785       const char *linkage_name = dw2_linkage_name (die, cu);
8786
8787       if (linkage_name != NULL)
8788         return linkage_name;
8789     }
8790
8791   /* These are the only languages we know how to qualify names in.  */
8792   if (name != NULL
8793       && (cu->language == language_cplus
8794           || cu->language == language_fortran || cu->language == language_d
8795           || cu->language == language_rust))
8796     {
8797       if (die_needs_namespace (die, cu))
8798         {
8799           long length;
8800           const char *prefix;
8801           const char *canonical_name = NULL;
8802
8803           string_file buf;
8804
8805           prefix = determine_prefix (die, cu);
8806           if (*prefix != '\0')
8807             {
8808               char *prefixed_name = typename_concat (NULL, prefix, name,
8809                                                      physname, cu);
8810
8811               buf.puts (prefixed_name);
8812               xfree (prefixed_name);
8813             }
8814           else
8815             buf.puts (name);
8816
8817           /* Template parameters may be specified in the DIE's DW_AT_name, or
8818              as children with DW_TAG_template_type_param or
8819              DW_TAG_value_type_param.  If the latter, add them to the name
8820              here.  If the name already has template parameters, then
8821              skip this step; some versions of GCC emit both, and
8822              it is more efficient to use the pre-computed name.
8823
8824              Something to keep in mind about this process: it is very
8825              unlikely, or in some cases downright impossible, to produce
8826              something that will match the mangled name of a function.
8827              If the definition of the function has the same debug info,
8828              we should be able to match up with it anyway.  But fallbacks
8829              using the minimal symbol, for instance to find a method
8830              implemented in a stripped copy of libstdc++, will not work.
8831              If we do not have debug info for the definition, we will have to
8832              match them up some other way.
8833
8834              When we do name matching there is a related problem with function
8835              templates; two instantiated function templates are allowed to
8836              differ only by their return types, which we do not add here.  */
8837
8838           if (cu->language == language_cplus && strchr (name, '<') == NULL)
8839             {
8840               struct attribute *attr;
8841               struct die_info *child;
8842               int first = 1;
8843
8844               die->building_fullname = 1;
8845
8846               for (child = die->child; child != NULL; child = child->sibling)
8847                 {
8848                   struct type *type;
8849                   LONGEST value;
8850                   const gdb_byte *bytes;
8851                   struct dwarf2_locexpr_baton *baton;
8852                   struct value *v;
8853
8854                   if (child->tag != DW_TAG_template_type_param
8855                       && child->tag != DW_TAG_template_value_param)
8856                     continue;
8857
8858                   if (first)
8859                     {
8860                       buf.puts ("<");
8861                       first = 0;
8862                     }
8863                   else
8864                     buf.puts (", ");
8865
8866                   attr = dwarf2_attr (child, DW_AT_type, cu);
8867                   if (attr == NULL)
8868                     {
8869                       complaint (&symfile_complaints,
8870                                  _("template parameter missing DW_AT_type"));
8871                       buf.puts ("UNKNOWN_TYPE");
8872                       continue;
8873                     }
8874                   type = die_type (child, cu);
8875
8876                   if (child->tag == DW_TAG_template_type_param)
8877                     {
8878                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
8879                       continue;
8880                     }
8881
8882                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
8883                   if (attr == NULL)
8884                     {
8885                       complaint (&symfile_complaints,
8886                                  _("template parameter missing "
8887                                    "DW_AT_const_value"));
8888                       buf.puts ("UNKNOWN_VALUE");
8889                       continue;
8890                     }
8891
8892                   dwarf2_const_value_attr (attr, type, name,
8893                                            &cu->comp_unit_obstack, cu,
8894                                            &value, &bytes, &baton);
8895
8896                   if (TYPE_NOSIGN (type))
8897                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
8898                        changed, this can use value_print instead.  */
8899                     c_printchar (value, type, &buf);
8900                   else
8901                     {
8902                       struct value_print_options opts;
8903
8904                       if (baton != NULL)
8905                         v = dwarf2_evaluate_loc_desc (type, NULL,
8906                                                       baton->data,
8907                                                       baton->size,
8908                                                       baton->per_cu);
8909                       else if (bytes != NULL)
8910                         {
8911                           v = allocate_value (type);
8912                           memcpy (value_contents_writeable (v), bytes,
8913                                   TYPE_LENGTH (type));
8914                         }
8915                       else
8916                         v = value_from_longest (type, value);
8917
8918                       /* Specify decimal so that we do not depend on
8919                          the radix.  */
8920                       get_formatted_print_options (&opts, 'd');
8921                       opts.raw = 1;
8922                       value_print (v, &buf, &opts);
8923                       release_value (v);
8924                       value_free (v);
8925                     }
8926                 }
8927
8928               die->building_fullname = 0;
8929
8930               if (!first)
8931                 {
8932                   /* Close the argument list, with a space if necessary
8933                      (nested templates).  */
8934                   if (!buf.empty () && buf.string ().back () == '>')
8935                     buf.puts (" >");
8936                   else
8937                     buf.puts (">");
8938                 }
8939             }
8940
8941           /* For C++ methods, append formal parameter type
8942              information, if PHYSNAME.  */
8943
8944           if (physname && die->tag == DW_TAG_subprogram
8945               && cu->language == language_cplus)
8946             {
8947               struct type *type = read_type_die (die, cu);
8948
8949               c_type_print_args (type, &buf, 1, cu->language,
8950                                  &type_print_raw_options);
8951
8952               if (cu->language == language_cplus)
8953                 {
8954                   /* Assume that an artificial first parameter is
8955                      "this", but do not crash if it is not.  RealView
8956                      marks unnamed (and thus unused) parameters as
8957                      artificial; there is no way to differentiate
8958                      the two cases.  */
8959                   if (TYPE_NFIELDS (type) > 0
8960                       && TYPE_FIELD_ARTIFICIAL (type, 0)
8961                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
8962                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
8963                                                                         0))))
8964                     buf.puts (" const");
8965                 }
8966             }
8967
8968           const std::string &intermediate_name = buf.string ();
8969
8970           if (cu->language == language_cplus)
8971             canonical_name
8972               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
8973                                           &objfile->per_bfd->storage_obstack);
8974
8975           /* If we only computed INTERMEDIATE_NAME, or if
8976              INTERMEDIATE_NAME is already canonical, then we need to
8977              copy it to the appropriate obstack.  */
8978           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
8979             name = ((const char *)
8980                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
8981                                    intermediate_name.c_str (),
8982                                    intermediate_name.length ()));
8983           else
8984             name = canonical_name;
8985         }
8986     }
8987
8988   return name;
8989 }
8990
8991 /* Return the fully qualified name of DIE, based on its DW_AT_name.
8992    If scope qualifiers are appropriate they will be added.  The result
8993    will be allocated on the storage_obstack, or NULL if the DIE does
8994    not have a name.  NAME may either be from a previous call to
8995    dwarf2_name or NULL.
8996
8997    The output string will be canonicalized (if C++).  */
8998
8999 static const char *
9000 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9001 {
9002   return dwarf2_compute_name (name, die, cu, 0);
9003 }
9004
9005 /* Construct a physname for the given DIE in CU.  NAME may either be
9006    from a previous call to dwarf2_name or NULL.  The result will be
9007    allocated on the objfile_objstack or NULL if the DIE does not have a
9008    name.
9009
9010    The output string will be canonicalized (if C++).  */
9011
9012 static const char *
9013 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9014 {
9015   struct objfile *objfile = cu->objfile;
9016   const char *retval, *mangled = NULL, *canon = NULL;
9017   int need_copy = 1;
9018
9019   /* In this case dwarf2_compute_name is just a shortcut not building anything
9020      on its own.  */
9021   if (!die_needs_namespace (die, cu))
9022     return dwarf2_compute_name (name, die, cu, 1);
9023
9024   mangled = dw2_linkage_name (die, cu);
9025
9026   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9027      See https://github.com/rust-lang/rust/issues/32925.  */
9028   if (cu->language == language_rust && mangled != NULL
9029       && strchr (mangled, '{') != NULL)
9030     mangled = NULL;
9031
9032   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9033      has computed.  */
9034   gdb::unique_xmalloc_ptr<char> demangled;
9035   if (mangled != NULL)
9036     {
9037       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9038          type.  It is easier for GDB users to search for such functions as
9039          `name(params)' than `long name(params)'.  In such case the minimal
9040          symbol names do not match the full symbol names but for template
9041          functions there is never a need to look up their definition from their
9042          declaration so the only disadvantage remains the minimal symbol
9043          variant `long name(params)' does not have the proper inferior type.
9044          */
9045
9046       if (cu->language == language_go)
9047         {
9048           /* This is a lie, but we already lie to the caller new_symbol_full.
9049              new_symbol_full assumes we return the mangled name.
9050              This just undoes that lie until things are cleaned up.  */
9051         }
9052       else
9053         {
9054           demangled.reset (gdb_demangle (mangled,
9055                                          (DMGL_PARAMS | DMGL_ANSI
9056                                           | DMGL_RET_DROP)));
9057         }
9058       if (demangled)
9059         canon = demangled.get ();
9060       else
9061         {
9062           canon = mangled;
9063           need_copy = 0;
9064         }
9065     }
9066
9067   if (canon == NULL || check_physname)
9068     {
9069       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9070
9071       if (canon != NULL && strcmp (physname, canon) != 0)
9072         {
9073           /* It may not mean a bug in GDB.  The compiler could also
9074              compute DW_AT_linkage_name incorrectly.  But in such case
9075              GDB would need to be bug-to-bug compatible.  */
9076
9077           complaint (&symfile_complaints,
9078                      _("Computed physname <%s> does not match demangled <%s> "
9079                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9080                      physname, canon, mangled, to_underlying (die->sect_off),
9081                      objfile_name (objfile));
9082
9083           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9084              is available here - over computed PHYSNAME.  It is safer
9085              against both buggy GDB and buggy compilers.  */
9086
9087           retval = canon;
9088         }
9089       else
9090         {
9091           retval = physname;
9092           need_copy = 0;
9093         }
9094     }
9095   else
9096     retval = canon;
9097
9098   if (need_copy)
9099     retval = ((const char *)
9100               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9101                              retval, strlen (retval)));
9102
9103   return retval;
9104 }
9105
9106 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9107    a new symbol for it.
9108
9109    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9110
9111 static int
9112 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9113 {
9114   struct attribute *attr;
9115
9116   /* If the die does not have a name, this is not a namespace
9117      alias.  */
9118   attr = dwarf2_attr (die, DW_AT_name, cu);
9119   if (attr != NULL)
9120     {
9121       int num;
9122       struct die_info *d = die;
9123       struct dwarf2_cu *imported_cu = cu;
9124
9125       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9126          keep inspecting DIEs until we hit the underlying import.  */
9127 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9128       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9129         {
9130           attr = dwarf2_attr (d, DW_AT_import, cu);
9131           if (attr == NULL)
9132             break;
9133
9134           d = follow_die_ref (d, attr, &imported_cu);
9135           if (d->tag != DW_TAG_imported_declaration)
9136             break;
9137         }
9138
9139       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9140         {
9141           complaint (&symfile_complaints,
9142                      _("DIE at 0x%x has too many recursively imported "
9143                        "declarations"), to_underlying (d->sect_off));
9144           return 0;
9145         }
9146
9147       if (attr != NULL)
9148         {
9149           struct type *type;
9150           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9151
9152           type = get_die_type_at_offset (sect_off, cu->per_cu);
9153           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9154             {
9155               /* This declaration is a global namespace alias.  Add
9156                  a symbol for it whose type is the aliased namespace.  */
9157               new_symbol (die, type, cu);
9158               return 1;
9159             }
9160         }
9161     }
9162
9163   return 0;
9164 }
9165
9166 /* Return the using directives repository (global or local?) to use in the
9167    current context for LANGUAGE.
9168
9169    For Ada, imported declarations can materialize renamings, which *may* be
9170    global.  However it is impossible (for now?) in DWARF to distinguish
9171    "external" imported declarations and "static" ones.  As all imported
9172    declarations seem to be static in all other languages, make them all CU-wide
9173    global only in Ada.  */
9174
9175 static struct using_direct **
9176 using_directives (enum language language)
9177 {
9178   if (language == language_ada && context_stack_depth == 0)
9179     return &global_using_directives;
9180   else
9181     return &local_using_directives;
9182 }
9183
9184 /* Read the import statement specified by the given die and record it.  */
9185
9186 static void
9187 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9188 {
9189   struct objfile *objfile = cu->objfile;
9190   struct attribute *import_attr;
9191   struct die_info *imported_die, *child_die;
9192   struct dwarf2_cu *imported_cu;
9193   const char *imported_name;
9194   const char *imported_name_prefix;
9195   const char *canonical_name;
9196   const char *import_alias;
9197   const char *imported_declaration = NULL;
9198   const char *import_prefix;
9199   std::vector<const char *> excludes;
9200
9201   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9202   if (import_attr == NULL)
9203     {
9204       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9205                  dwarf_tag_name (die->tag));
9206       return;
9207     }
9208
9209   imported_cu = cu;
9210   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9211   imported_name = dwarf2_name (imported_die, imported_cu);
9212   if (imported_name == NULL)
9213     {
9214       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9215
9216         The import in the following code:
9217         namespace A
9218           {
9219             typedef int B;
9220           }
9221
9222         int main ()
9223           {
9224             using A::B;
9225             B b;
9226             return b;
9227           }
9228
9229         ...
9230          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9231             <52>   DW_AT_decl_file   : 1
9232             <53>   DW_AT_decl_line   : 6
9233             <54>   DW_AT_import      : <0x75>
9234          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9235             <59>   DW_AT_name        : B
9236             <5b>   DW_AT_decl_file   : 1
9237             <5c>   DW_AT_decl_line   : 2
9238             <5d>   DW_AT_type        : <0x6e>
9239         ...
9240          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9241             <76>   DW_AT_byte_size   : 4
9242             <77>   DW_AT_encoding    : 5        (signed)
9243
9244         imports the wrong die ( 0x75 instead of 0x58 ).
9245         This case will be ignored until the gcc bug is fixed.  */
9246       return;
9247     }
9248
9249   /* Figure out the local name after import.  */
9250   import_alias = dwarf2_name (die, cu);
9251
9252   /* Figure out where the statement is being imported to.  */
9253   import_prefix = determine_prefix (die, cu);
9254
9255   /* Figure out what the scope of the imported die is and prepend it
9256      to the name of the imported die.  */
9257   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9258
9259   if (imported_die->tag != DW_TAG_namespace
9260       && imported_die->tag != DW_TAG_module)
9261     {
9262       imported_declaration = imported_name;
9263       canonical_name = imported_name_prefix;
9264     }
9265   else if (strlen (imported_name_prefix) > 0)
9266     canonical_name = obconcat (&objfile->objfile_obstack,
9267                                imported_name_prefix,
9268                                (cu->language == language_d ? "." : "::"),
9269                                imported_name, (char *) NULL);
9270   else
9271     canonical_name = imported_name;
9272
9273   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9274     for (child_die = die->child; child_die && child_die->tag;
9275          child_die = sibling_die (child_die))
9276       {
9277         /* DWARF-4: A Fortran use statement with a “rename list” may be
9278            represented by an imported module entry with an import attribute
9279            referring to the module and owned entries corresponding to those
9280            entities that are renamed as part of being imported.  */
9281
9282         if (child_die->tag != DW_TAG_imported_declaration)
9283           {
9284             complaint (&symfile_complaints,
9285                        _("child DW_TAG_imported_declaration expected "
9286                          "- DIE at 0x%x [in module %s]"),
9287                        to_underlying (child_die->sect_off), objfile_name (objfile));
9288             continue;
9289           }
9290
9291         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9292         if (import_attr == NULL)
9293           {
9294             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9295                        dwarf_tag_name (child_die->tag));
9296             continue;
9297           }
9298
9299         imported_cu = cu;
9300         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9301                                               &imported_cu);
9302         imported_name = dwarf2_name (imported_die, imported_cu);
9303         if (imported_name == NULL)
9304           {
9305             complaint (&symfile_complaints,
9306                        _("child DW_TAG_imported_declaration has unknown "
9307                          "imported name - DIE at 0x%x [in module %s]"),
9308                        to_underlying (child_die->sect_off), objfile_name (objfile));
9309             continue;
9310           }
9311
9312         excludes.push_back (imported_name);
9313
9314         process_die (child_die, cu);
9315       }
9316
9317   add_using_directive (using_directives (cu->language),
9318                        import_prefix,
9319                        canonical_name,
9320                        import_alias,
9321                        imported_declaration,
9322                        excludes,
9323                        0,
9324                        &objfile->objfile_obstack);
9325 }
9326
9327 /* ICC<14 does not output the required DW_AT_declaration on incomplete
9328    types, but gives them a size of zero.  Starting with version 14,
9329    ICC is compatible with GCC.  */
9330
9331 static int
9332 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
9333 {
9334   if (!cu->checked_producer)
9335     check_producer (cu);
9336
9337   return cu->producer_is_icc_lt_14;
9338 }
9339
9340 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9341    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9342    this, it was first present in GCC release 4.3.0.  */
9343
9344 static int
9345 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9346 {
9347   if (!cu->checked_producer)
9348     check_producer (cu);
9349
9350   return cu->producer_is_gcc_lt_4_3;
9351 }
9352
9353 static file_and_directory
9354 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9355 {
9356   file_and_directory res;
9357
9358   /* Find the filename.  Do not use dwarf2_name here, since the filename
9359      is not a source language identifier.  */
9360   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9361   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9362
9363   if (res.comp_dir == NULL
9364       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9365       && IS_ABSOLUTE_PATH (res.name))
9366     {
9367       res.comp_dir_storage = ldirname (res.name);
9368       if (!res.comp_dir_storage.empty ())
9369         res.comp_dir = res.comp_dir_storage.c_str ();
9370     }
9371   if (res.comp_dir != NULL)
9372     {
9373       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9374          directory, get rid of it.  */
9375       const char *cp = strchr (res.comp_dir, ':');
9376
9377       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9378         res.comp_dir = cp + 1;
9379     }
9380
9381   if (res.name == NULL)
9382     res.name = "<unknown>";
9383
9384   return res;
9385 }
9386
9387 /* Handle DW_AT_stmt_list for a compilation unit.
9388    DIE is the DW_TAG_compile_unit die for CU.
9389    COMP_DIR is the compilation directory.  LOWPC is passed to
9390    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9391
9392 static void
9393 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9394                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9395 {
9396   struct objfile *objfile = dwarf2_per_objfile->objfile;
9397   struct attribute *attr;
9398   struct line_header line_header_local;
9399   hashval_t line_header_local_hash;
9400   unsigned u;
9401   void **slot;
9402   int decode_mapping;
9403
9404   gdb_assert (! cu->per_cu->is_debug_types);
9405
9406   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9407   if (attr == NULL)
9408     return;
9409
9410   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9411
9412   /* The line header hash table is only created if needed (it exists to
9413      prevent redundant reading of the line table for partial_units).
9414      If we're given a partial_unit, we'll need it.  If we're given a
9415      compile_unit, then use the line header hash table if it's already
9416      created, but don't create one just yet.  */
9417
9418   if (dwarf2_per_objfile->line_header_hash == NULL
9419       && die->tag == DW_TAG_partial_unit)
9420     {
9421       dwarf2_per_objfile->line_header_hash
9422         = htab_create_alloc_ex (127, line_header_hash_voidp,
9423                                 line_header_eq_voidp,
9424                                 free_line_header_voidp,
9425                                 &objfile->objfile_obstack,
9426                                 hashtab_obstack_allocate,
9427                                 dummy_obstack_deallocate);
9428     }
9429
9430   line_header_local.sect_off = line_offset;
9431   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9432   line_header_local_hash = line_header_hash (&line_header_local);
9433   if (dwarf2_per_objfile->line_header_hash != NULL)
9434     {
9435       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9436                                        &line_header_local,
9437                                        line_header_local_hash, NO_INSERT);
9438
9439       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9440          is not present in *SLOT (since if there is something in *SLOT then
9441          it will be for a partial_unit).  */
9442       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9443         {
9444           gdb_assert (*slot != NULL);
9445           cu->line_header = (struct line_header *) *slot;
9446           return;
9447         }
9448     }
9449
9450   /* dwarf_decode_line_header does not yet provide sufficient information.
9451      We always have to call also dwarf_decode_lines for it.  */
9452   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9453   if (lh == NULL)
9454     return;
9455
9456   cu->line_header = lh.release ();
9457   cu->line_header_die_owner = die;
9458
9459   if (dwarf2_per_objfile->line_header_hash == NULL)
9460     slot = NULL;
9461   else
9462     {
9463       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9464                                        &line_header_local,
9465                                        line_header_local_hash, INSERT);
9466       gdb_assert (slot != NULL);
9467     }
9468   if (slot != NULL && *slot == NULL)
9469     {
9470       /* This newly decoded line number information unit will be owned
9471          by line_header_hash hash table.  */
9472       *slot = cu->line_header;
9473       cu->line_header_die_owner = NULL;
9474     }
9475   else
9476     {
9477       /* We cannot free any current entry in (*slot) as that struct line_header
9478          may be already used by multiple CUs.  Create only temporary decoded
9479          line_header for this CU - it may happen at most once for each line
9480          number information unit.  And if we're not using line_header_hash
9481          then this is what we want as well.  */
9482       gdb_assert (die->tag != DW_TAG_partial_unit);
9483     }
9484   decode_mapping = (die->tag != DW_TAG_partial_unit);
9485   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9486                       decode_mapping);
9487
9488 }
9489
9490 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9491
9492 static void
9493 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9494 {
9495   struct objfile *objfile = dwarf2_per_objfile->objfile;
9496   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9497   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9498   CORE_ADDR highpc = ((CORE_ADDR) 0);
9499   struct attribute *attr;
9500   struct die_info *child_die;
9501   CORE_ADDR baseaddr;
9502
9503   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9504
9505   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9506
9507   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9508      from finish_block.  */
9509   if (lowpc == ((CORE_ADDR) -1))
9510     lowpc = highpc;
9511   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9512
9513   file_and_directory fnd = find_file_and_directory (die, cu);
9514
9515   prepare_one_comp_unit (cu, die, cu->language);
9516
9517   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9518      standardised yet.  As a workaround for the language detection we fall
9519      back to the DW_AT_producer string.  */
9520   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9521     cu->language = language_opencl;
9522
9523   /* Similar hack for Go.  */
9524   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9525     set_cu_language (DW_LANG_Go, cu);
9526
9527   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9528
9529   /* Decode line number information if present.  We do this before
9530      processing child DIEs, so that the line header table is available
9531      for DW_AT_decl_file.  */
9532   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9533
9534   /* Process all dies in compilation unit.  */
9535   if (die->child != NULL)
9536     {
9537       child_die = die->child;
9538       while (child_die && child_die->tag)
9539         {
9540           process_die (child_die, cu);
9541           child_die = sibling_die (child_die);
9542         }
9543     }
9544
9545   /* Decode macro information, if present.  Dwarf 2 macro information
9546      refers to information in the line number info statement program
9547      header, so we can only read it if we've read the header
9548      successfully.  */
9549   attr = dwarf2_attr (die, DW_AT_macros, cu);
9550   if (attr == NULL)
9551     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9552   if (attr && cu->line_header)
9553     {
9554       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9555         complaint (&symfile_complaints,
9556                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9557
9558       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9559     }
9560   else
9561     {
9562       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9563       if (attr && cu->line_header)
9564         {
9565           unsigned int macro_offset = DW_UNSND (attr);
9566
9567           dwarf_decode_macros (cu, macro_offset, 0);
9568         }
9569     }
9570 }
9571
9572 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9573    Create the set of symtabs used by this TU, or if this TU is sharing
9574    symtabs with another TU and the symtabs have already been created
9575    then restore those symtabs in the line header.
9576    We don't need the pc/line-number mapping for type units.  */
9577
9578 static void
9579 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9580 {
9581   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9582   struct type_unit_group *tu_group;
9583   int first_time;
9584   struct attribute *attr;
9585   unsigned int i;
9586   struct signatured_type *sig_type;
9587
9588   gdb_assert (per_cu->is_debug_types);
9589   sig_type = (struct signatured_type *) per_cu;
9590
9591   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9592
9593   /* If we're using .gdb_index (includes -readnow) then
9594      per_cu->type_unit_group may not have been set up yet.  */
9595   if (sig_type->type_unit_group == NULL)
9596     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9597   tu_group = sig_type->type_unit_group;
9598
9599   /* If we've already processed this stmt_list there's no real need to
9600      do it again, we could fake it and just recreate the part we need
9601      (file name,index -> symtab mapping).  If data shows this optimization
9602      is useful we can do it then.  */
9603   first_time = tu_group->compunit_symtab == NULL;
9604
9605   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9606      debug info.  */
9607   line_header_up lh;
9608   if (attr != NULL)
9609     {
9610       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9611       lh = dwarf_decode_line_header (line_offset, cu);
9612     }
9613   if (lh == NULL)
9614     {
9615       if (first_time)
9616         dwarf2_start_symtab (cu, "", NULL, 0);
9617       else
9618         {
9619           gdb_assert (tu_group->symtabs == NULL);
9620           restart_symtab (tu_group->compunit_symtab, "", 0);
9621         }
9622       return;
9623     }
9624
9625   cu->line_header = lh.release ();
9626   cu->line_header_die_owner = die;
9627
9628   if (first_time)
9629     {
9630       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9631
9632       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9633          still initializing it, and our caller (a few levels up)
9634          process_full_type_unit still needs to know if this is the first
9635          time.  */
9636
9637       tu_group->num_symtabs = cu->line_header->file_names.size ();
9638       tu_group->symtabs = XNEWVEC (struct symtab *,
9639                                    cu->line_header->file_names.size ());
9640
9641       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9642         {
9643           file_entry &fe = cu->line_header->file_names[i];
9644
9645           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9646
9647           if (current_subfile->symtab == NULL)
9648             {
9649               /* NOTE: start_subfile will recognize when it's been
9650                  passed a file it has already seen.  So we can't
9651                  assume there's a simple mapping from
9652                  cu->line_header->file_names to subfiles, plus
9653                  cu->line_header->file_names may contain dups.  */
9654               current_subfile->symtab
9655                 = allocate_symtab (cust, current_subfile->name);
9656             }
9657
9658           fe.symtab = current_subfile->symtab;
9659           tu_group->symtabs[i] = fe.symtab;
9660         }
9661     }
9662   else
9663     {
9664       restart_symtab (tu_group->compunit_symtab, "", 0);
9665
9666       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9667         {
9668           file_entry &fe = cu->line_header->file_names[i];
9669
9670           fe.symtab = tu_group->symtabs[i];
9671         }
9672     }
9673
9674   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9675      so they don't have a "real" (so to speak) symtab anyway.
9676      There is later code that will assign the main symtab to all symbols
9677      that don't have one.  We need to handle the case of a symbol with a
9678      missing symtab (DW_AT_decl_file) anyway.  */
9679 }
9680
9681 /* Process DW_TAG_type_unit.
9682    For TUs we want to skip the first top level sibling if it's not the
9683    actual type being defined by this TU.  In this case the first top
9684    level sibling is there to provide context only.  */
9685
9686 static void
9687 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9688 {
9689   struct die_info *child_die;
9690
9691   prepare_one_comp_unit (cu, die, language_minimal);
9692
9693   /* Initialize (or reinitialize) the machinery for building symtabs.
9694      We do this before processing child DIEs, so that the line header table
9695      is available for DW_AT_decl_file.  */
9696   setup_type_unit_groups (die, cu);
9697
9698   if (die->child != NULL)
9699     {
9700       child_die = die->child;
9701       while (child_die && child_die->tag)
9702         {
9703           process_die (child_die, cu);
9704           child_die = sibling_die (child_die);
9705         }
9706     }
9707 }
9708 \f
9709 /* DWO/DWP files.
9710
9711    http://gcc.gnu.org/wiki/DebugFission
9712    http://gcc.gnu.org/wiki/DebugFissionDWP
9713
9714    To simplify handling of both DWO files ("object" files with the DWARF info)
9715    and DWP files (a file with the DWOs packaged up into one file), we treat
9716    DWP files as having a collection of virtual DWO files.  */
9717
9718 static hashval_t
9719 hash_dwo_file (const void *item)
9720 {
9721   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
9722   hashval_t hash;
9723
9724   hash = htab_hash_string (dwo_file->dwo_name);
9725   if (dwo_file->comp_dir != NULL)
9726     hash += htab_hash_string (dwo_file->comp_dir);
9727   return hash;
9728 }
9729
9730 static int
9731 eq_dwo_file (const void *item_lhs, const void *item_rhs)
9732 {
9733   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
9734   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
9735
9736   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
9737     return 0;
9738   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
9739     return lhs->comp_dir == rhs->comp_dir;
9740   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
9741 }
9742
9743 /* Allocate a hash table for DWO files.  */
9744
9745 static htab_t
9746 allocate_dwo_file_hash_table (void)
9747 {
9748   struct objfile *objfile = dwarf2_per_objfile->objfile;
9749
9750   return htab_create_alloc_ex (41,
9751                                hash_dwo_file,
9752                                eq_dwo_file,
9753                                NULL,
9754                                &objfile->objfile_obstack,
9755                                hashtab_obstack_allocate,
9756                                dummy_obstack_deallocate);
9757 }
9758
9759 /* Lookup DWO file DWO_NAME.  */
9760
9761 static void **
9762 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
9763 {
9764   struct dwo_file find_entry;
9765   void **slot;
9766
9767   if (dwarf2_per_objfile->dwo_files == NULL)
9768     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
9769
9770   memset (&find_entry, 0, sizeof (find_entry));
9771   find_entry.dwo_name = dwo_name;
9772   find_entry.comp_dir = comp_dir;
9773   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
9774
9775   return slot;
9776 }
9777
9778 static hashval_t
9779 hash_dwo_unit (const void *item)
9780 {
9781   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
9782
9783   /* This drops the top 32 bits of the id, but is ok for a hash.  */
9784   return dwo_unit->signature;
9785 }
9786
9787 static int
9788 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
9789 {
9790   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
9791   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
9792
9793   /* The signature is assumed to be unique within the DWO file.
9794      So while object file CU dwo_id's always have the value zero,
9795      that's OK, assuming each object file DWO file has only one CU,
9796      and that's the rule for now.  */
9797   return lhs->signature == rhs->signature;
9798 }
9799
9800 /* Allocate a hash table for DWO CUs,TUs.
9801    There is one of these tables for each of CUs,TUs for each DWO file.  */
9802
9803 static htab_t
9804 allocate_dwo_unit_table (struct objfile *objfile)
9805 {
9806   /* Start out with a pretty small number.
9807      Generally DWO files contain only one CU and maybe some TUs.  */
9808   return htab_create_alloc_ex (3,
9809                                hash_dwo_unit,
9810                                eq_dwo_unit,
9811                                NULL,
9812                                &objfile->objfile_obstack,
9813                                hashtab_obstack_allocate,
9814                                dummy_obstack_deallocate);
9815 }
9816
9817 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
9818
9819 struct create_dwo_cu_data
9820 {
9821   struct dwo_file *dwo_file;
9822   struct dwo_unit dwo_unit;
9823 };
9824
9825 /* die_reader_func for create_dwo_cu.  */
9826
9827 static void
9828 create_dwo_cu_reader (const struct die_reader_specs *reader,
9829                       const gdb_byte *info_ptr,
9830                       struct die_info *comp_unit_die,
9831                       int has_children,
9832                       void *datap)
9833 {
9834   struct dwarf2_cu *cu = reader->cu;
9835   sect_offset sect_off = cu->per_cu->sect_off;
9836   struct dwarf2_section_info *section = cu->per_cu->section;
9837   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
9838   struct dwo_file *dwo_file = data->dwo_file;
9839   struct dwo_unit *dwo_unit = &data->dwo_unit;
9840   struct attribute *attr;
9841
9842   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
9843   if (attr == NULL)
9844     {
9845       complaint (&symfile_complaints,
9846                  _("Dwarf Error: debug entry at offset 0x%x is missing"
9847                    " its dwo_id [in module %s]"),
9848                  to_underlying (sect_off), dwo_file->dwo_name);
9849       return;
9850     }
9851
9852   dwo_unit->dwo_file = dwo_file;
9853   dwo_unit->signature = DW_UNSND (attr);
9854   dwo_unit->section = section;
9855   dwo_unit->sect_off = sect_off;
9856   dwo_unit->length = cu->per_cu->length;
9857
9858   if (dwarf_read_debug)
9859     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
9860                         to_underlying (sect_off),
9861                         hex_string (dwo_unit->signature));
9862 }
9863
9864 /* Create the dwo_units for the CUs in a DWO_FILE.
9865    Note: This function processes DWO files only, not DWP files.  */
9866
9867 static void
9868 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
9869                        htab_t &cus_htab)
9870 {
9871   struct objfile *objfile = dwarf2_per_objfile->objfile;
9872   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
9873   const gdb_byte *info_ptr, *end_ptr;
9874
9875   dwarf2_read_section (objfile, &section);
9876   info_ptr = section.buffer;
9877
9878   if (info_ptr == NULL)
9879     return;
9880
9881   if (dwarf_read_debug)
9882     {
9883       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
9884                           get_section_name (&section),
9885                           get_section_file_name (&section));
9886     }
9887
9888   end_ptr = info_ptr + section.size;
9889   while (info_ptr < end_ptr)
9890     {
9891       struct dwarf2_per_cu_data per_cu;
9892       struct create_dwo_cu_data create_dwo_cu_data;
9893       struct dwo_unit *dwo_unit;
9894       void **slot;
9895       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
9896
9897       memset (&create_dwo_cu_data.dwo_unit, 0,
9898               sizeof (create_dwo_cu_data.dwo_unit));
9899       memset (&per_cu, 0, sizeof (per_cu));
9900       per_cu.objfile = objfile;
9901       per_cu.is_debug_types = 0;
9902       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
9903       per_cu.section = &section;
9904       create_dwo_cu_data.dwo_file = &dwo_file;
9905
9906       init_cutu_and_read_dies_no_follow (
9907           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
9908       info_ptr += per_cu.length;
9909
9910       // If the unit could not be parsed, skip it.
9911       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
9912         continue;
9913
9914       if (cus_htab == NULL)
9915         cus_htab = allocate_dwo_unit_table (objfile);
9916
9917       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
9918       *dwo_unit = create_dwo_cu_data.dwo_unit;
9919       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
9920       gdb_assert (slot != NULL);
9921       if (*slot != NULL)
9922         {
9923           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
9924           sect_offset dup_sect_off = dup_cu->sect_off;
9925
9926           complaint (&symfile_complaints,
9927                      _("debug cu entry at offset 0x%x is duplicate to"
9928                        " the entry at offset 0x%x, signature %s"),
9929                      to_underlying (sect_off), to_underlying (dup_sect_off),
9930                      hex_string (dwo_unit->signature));
9931         }
9932       *slot = (void *)dwo_unit;
9933     }
9934 }
9935
9936 /* DWP file .debug_{cu,tu}_index section format:
9937    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
9938
9939    DWP Version 1:
9940
9941    Both index sections have the same format, and serve to map a 64-bit
9942    signature to a set of section numbers.  Each section begins with a header,
9943    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
9944    indexes, and a pool of 32-bit section numbers.  The index sections will be
9945    aligned at 8-byte boundaries in the file.
9946
9947    The index section header consists of:
9948
9949     V, 32 bit version number
9950     -, 32 bits unused
9951     N, 32 bit number of compilation units or type units in the index
9952     M, 32 bit number of slots in the hash table
9953
9954    Numbers are recorded using the byte order of the application binary.
9955
9956    The hash table begins at offset 16 in the section, and consists of an array
9957    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
9958    order of the application binary).  Unused slots in the hash table are 0.
9959    (We rely on the extreme unlikeliness of a signature being exactly 0.)
9960
9961    The parallel table begins immediately after the hash table
9962    (at offset 16 + 8 * M from the beginning of the section), and consists of an
9963    array of 32-bit indexes (using the byte order of the application binary),
9964    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
9965    table contains a 32-bit index into the pool of section numbers.  For unused
9966    hash table slots, the corresponding entry in the parallel table will be 0.
9967
9968    The pool of section numbers begins immediately following the hash table
9969    (at offset 16 + 12 * M from the beginning of the section).  The pool of
9970    section numbers consists of an array of 32-bit words (using the byte order
9971    of the application binary).  Each item in the array is indexed starting
9972    from 0.  The hash table entry provides the index of the first section
9973    number in the set.  Additional section numbers in the set follow, and the
9974    set is terminated by a 0 entry (section number 0 is not used in ELF).
9975
9976    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
9977    section must be the first entry in the set, and the .debug_abbrev.dwo must
9978    be the second entry. Other members of the set may follow in any order.
9979
9980    ---
9981
9982    DWP Version 2:
9983
9984    DWP Version 2 combines all the .debug_info, etc. sections into one,
9985    and the entries in the index tables are now offsets into these sections.
9986    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
9987    section.
9988
9989    Index Section Contents:
9990     Header
9991     Hash Table of Signatures   dwp_hash_table.hash_table
9992     Parallel Table of Indices  dwp_hash_table.unit_table
9993     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
9994     Table of Section Sizes     dwp_hash_table.v2.sizes
9995
9996    The index section header consists of:
9997
9998     V, 32 bit version number
9999     L, 32 bit number of columns in the table of section offsets
10000     N, 32 bit number of compilation units or type units in the index
10001     M, 32 bit number of slots in the hash table
10002
10003    Numbers are recorded using the byte order of the application binary.
10004
10005    The hash table has the same format as version 1.
10006    The parallel table of indices has the same format as version 1,
10007    except that the entries are origin-1 indices into the table of sections
10008    offsets and the table of section sizes.
10009
10010    The table of offsets begins immediately following the parallel table
10011    (at offset 16 + 12 * M from the beginning of the section).  The table is
10012    a two-dimensional array of 32-bit words (using the byte order of the
10013    application binary), with L columns and N+1 rows, in row-major order.
10014    Each row in the array is indexed starting from 0.  The first row provides
10015    a key to the remaining rows: each column in this row provides an identifier
10016    for a debug section, and the offsets in the same column of subsequent rows
10017    refer to that section.  The section identifiers are:
10018
10019     DW_SECT_INFO         1  .debug_info.dwo
10020     DW_SECT_TYPES        2  .debug_types.dwo
10021     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10022     DW_SECT_LINE         4  .debug_line.dwo
10023     DW_SECT_LOC          5  .debug_loc.dwo
10024     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10025     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10026     DW_SECT_MACRO        8  .debug_macro.dwo
10027
10028    The offsets provided by the CU and TU index sections are the base offsets
10029    for the contributions made by each CU or TU to the corresponding section
10030    in the package file.  Each CU and TU header contains an abbrev_offset
10031    field, used to find the abbreviations table for that CU or TU within the
10032    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10033    be interpreted as relative to the base offset given in the index section.
10034    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10035    should be interpreted as relative to the base offset for .debug_line.dwo,
10036    and offsets into other debug sections obtained from DWARF attributes should
10037    also be interpreted as relative to the corresponding base offset.
10038
10039    The table of sizes begins immediately following the table of offsets.
10040    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10041    with L columns and N rows, in row-major order.  Each row in the array is
10042    indexed starting from 1 (row 0 is shared by the two tables).
10043
10044    ---
10045
10046    Hash table lookup is handled the same in version 1 and 2:
10047
10048    We assume that N and M will not exceed 2^32 - 1.
10049    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10050
10051    Given a 64-bit compilation unit signature or a type signature S, an entry
10052    in the hash table is located as follows:
10053
10054    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10055       the low-order k bits all set to 1.
10056
10057    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10058
10059    3) If the hash table entry at index H matches the signature, use that
10060       entry.  If the hash table entry at index H is unused (all zeroes),
10061       terminate the search: the signature is not present in the table.
10062
10063    4) Let H = (H + H') modulo M. Repeat at Step 3.
10064
10065    Because M > N and H' and M are relatively prime, the search is guaranteed
10066    to stop at an unused slot or find the match.  */
10067
10068 /* Create a hash table to map DWO IDs to their CU/TU entry in
10069    .debug_{info,types}.dwo in DWP_FILE.
10070    Returns NULL if there isn't one.
10071    Note: This function processes DWP files only, not DWO files.  */
10072
10073 static struct dwp_hash_table *
10074 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10075 {
10076   struct objfile *objfile = dwarf2_per_objfile->objfile;
10077   bfd *dbfd = dwp_file->dbfd;
10078   const gdb_byte *index_ptr, *index_end;
10079   struct dwarf2_section_info *index;
10080   uint32_t version, nr_columns, nr_units, nr_slots;
10081   struct dwp_hash_table *htab;
10082
10083   if (is_debug_types)
10084     index = &dwp_file->sections.tu_index;
10085   else
10086     index = &dwp_file->sections.cu_index;
10087
10088   if (dwarf2_section_empty_p (index))
10089     return NULL;
10090   dwarf2_read_section (objfile, index);
10091
10092   index_ptr = index->buffer;
10093   index_end = index_ptr + index->size;
10094
10095   version = read_4_bytes (dbfd, index_ptr);
10096   index_ptr += 4;
10097   if (version == 2)
10098     nr_columns = read_4_bytes (dbfd, index_ptr);
10099   else
10100     nr_columns = 0;
10101   index_ptr += 4;
10102   nr_units = read_4_bytes (dbfd, index_ptr);
10103   index_ptr += 4;
10104   nr_slots = read_4_bytes (dbfd, index_ptr);
10105   index_ptr += 4;
10106
10107   if (version != 1 && version != 2)
10108     {
10109       error (_("Dwarf Error: unsupported DWP file version (%s)"
10110                " [in module %s]"),
10111              pulongest (version), dwp_file->name);
10112     }
10113   if (nr_slots != (nr_slots & -nr_slots))
10114     {
10115       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10116                " is not power of 2 [in module %s]"),
10117              pulongest (nr_slots), dwp_file->name);
10118     }
10119
10120   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10121   htab->version = version;
10122   htab->nr_columns = nr_columns;
10123   htab->nr_units = nr_units;
10124   htab->nr_slots = nr_slots;
10125   htab->hash_table = index_ptr;
10126   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10127
10128   /* Exit early if the table is empty.  */
10129   if (nr_slots == 0 || nr_units == 0
10130       || (version == 2 && nr_columns == 0))
10131     {
10132       /* All must be zero.  */
10133       if (nr_slots != 0 || nr_units != 0
10134           || (version == 2 && nr_columns != 0))
10135         {
10136           complaint (&symfile_complaints,
10137                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10138                        " all zero [in modules %s]"),
10139                      dwp_file->name);
10140         }
10141       return htab;
10142     }
10143
10144   if (version == 1)
10145     {
10146       htab->section_pool.v1.indices =
10147         htab->unit_table + sizeof (uint32_t) * nr_slots;
10148       /* It's harder to decide whether the section is too small in v1.
10149          V1 is deprecated anyway so we punt.  */
10150     }
10151   else
10152     {
10153       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10154       int *ids = htab->section_pool.v2.section_ids;
10155       /* Reverse map for error checking.  */
10156       int ids_seen[DW_SECT_MAX + 1];
10157       int i;
10158
10159       if (nr_columns < 2)
10160         {
10161           error (_("Dwarf Error: bad DWP hash table, too few columns"
10162                    " in section table [in module %s]"),
10163                  dwp_file->name);
10164         }
10165       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10166         {
10167           error (_("Dwarf Error: bad DWP hash table, too many columns"
10168                    " in section table [in module %s]"),
10169                  dwp_file->name);
10170         }
10171       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10172       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10173       for (i = 0; i < nr_columns; ++i)
10174         {
10175           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10176
10177           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10178             {
10179               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10180                        " in section table [in module %s]"),
10181                      id, dwp_file->name);
10182             }
10183           if (ids_seen[id] != -1)
10184             {
10185               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10186                        " id %d in section table [in module %s]"),
10187                      id, dwp_file->name);
10188             }
10189           ids_seen[id] = i;
10190           ids[i] = id;
10191         }
10192       /* Must have exactly one info or types section.  */
10193       if (((ids_seen[DW_SECT_INFO] != -1)
10194            + (ids_seen[DW_SECT_TYPES] != -1))
10195           != 1)
10196         {
10197           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10198                    " DWO info/types section [in module %s]"),
10199                  dwp_file->name);
10200         }
10201       /* Must have an abbrev section.  */
10202       if (ids_seen[DW_SECT_ABBREV] == -1)
10203         {
10204           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10205                    " section [in module %s]"),
10206                  dwp_file->name);
10207         }
10208       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10209       htab->section_pool.v2.sizes =
10210         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10211                                          * nr_units * nr_columns);
10212       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10213                                           * nr_units * nr_columns))
10214           > index_end)
10215         {
10216           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10217                    " [in module %s]"),
10218                  dwp_file->name);
10219         }
10220     }
10221
10222   return htab;
10223 }
10224
10225 /* Update SECTIONS with the data from SECTP.
10226
10227    This function is like the other "locate" section routines that are
10228    passed to bfd_map_over_sections, but in this context the sections to
10229    read comes from the DWP V1 hash table, not the full ELF section table.
10230
10231    The result is non-zero for success, or zero if an error was found.  */
10232
10233 static int
10234 locate_v1_virtual_dwo_sections (asection *sectp,
10235                                 struct virtual_v1_dwo_sections *sections)
10236 {
10237   const struct dwop_section_names *names = &dwop_section_names;
10238
10239   if (section_is_p (sectp->name, &names->abbrev_dwo))
10240     {
10241       /* There can be only one.  */
10242       if (sections->abbrev.s.section != NULL)
10243         return 0;
10244       sections->abbrev.s.section = sectp;
10245       sections->abbrev.size = bfd_get_section_size (sectp);
10246     }
10247   else if (section_is_p (sectp->name, &names->info_dwo)
10248            || section_is_p (sectp->name, &names->types_dwo))
10249     {
10250       /* There can be only one.  */
10251       if (sections->info_or_types.s.section != NULL)
10252         return 0;
10253       sections->info_or_types.s.section = sectp;
10254       sections->info_or_types.size = bfd_get_section_size (sectp);
10255     }
10256   else if (section_is_p (sectp->name, &names->line_dwo))
10257     {
10258       /* There can be only one.  */
10259       if (sections->line.s.section != NULL)
10260         return 0;
10261       sections->line.s.section = sectp;
10262       sections->line.size = bfd_get_section_size (sectp);
10263     }
10264   else if (section_is_p (sectp->name, &names->loc_dwo))
10265     {
10266       /* There can be only one.  */
10267       if (sections->loc.s.section != NULL)
10268         return 0;
10269       sections->loc.s.section = sectp;
10270       sections->loc.size = bfd_get_section_size (sectp);
10271     }
10272   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10273     {
10274       /* There can be only one.  */
10275       if (sections->macinfo.s.section != NULL)
10276         return 0;
10277       sections->macinfo.s.section = sectp;
10278       sections->macinfo.size = bfd_get_section_size (sectp);
10279     }
10280   else if (section_is_p (sectp->name, &names->macro_dwo))
10281     {
10282       /* There can be only one.  */
10283       if (sections->macro.s.section != NULL)
10284         return 0;
10285       sections->macro.s.section = sectp;
10286       sections->macro.size = bfd_get_section_size (sectp);
10287     }
10288   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10289     {
10290       /* There can be only one.  */
10291       if (sections->str_offsets.s.section != NULL)
10292         return 0;
10293       sections->str_offsets.s.section = sectp;
10294       sections->str_offsets.size = bfd_get_section_size (sectp);
10295     }
10296   else
10297     {
10298       /* No other kind of section is valid.  */
10299       return 0;
10300     }
10301
10302   return 1;
10303 }
10304
10305 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10306    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10307    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10308    This is for DWP version 1 files.  */
10309
10310 static struct dwo_unit *
10311 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10312                            uint32_t unit_index,
10313                            const char *comp_dir,
10314                            ULONGEST signature, int is_debug_types)
10315 {
10316   struct objfile *objfile = dwarf2_per_objfile->objfile;
10317   const struct dwp_hash_table *dwp_htab =
10318     is_debug_types ? dwp_file->tus : dwp_file->cus;
10319   bfd *dbfd = dwp_file->dbfd;
10320   const char *kind = is_debug_types ? "TU" : "CU";
10321   struct dwo_file *dwo_file;
10322   struct dwo_unit *dwo_unit;
10323   struct virtual_v1_dwo_sections sections;
10324   void **dwo_file_slot;
10325   int i;
10326
10327   gdb_assert (dwp_file->version == 1);
10328
10329   if (dwarf_read_debug)
10330     {
10331       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10332                           kind,
10333                           pulongest (unit_index), hex_string (signature),
10334                           dwp_file->name);
10335     }
10336
10337   /* Fetch the sections of this DWO unit.
10338      Put a limit on the number of sections we look for so that bad data
10339      doesn't cause us to loop forever.  */
10340
10341 #define MAX_NR_V1_DWO_SECTIONS \
10342   (1 /* .debug_info or .debug_types */ \
10343    + 1 /* .debug_abbrev */ \
10344    + 1 /* .debug_line */ \
10345    + 1 /* .debug_loc */ \
10346    + 1 /* .debug_str_offsets */ \
10347    + 1 /* .debug_macro or .debug_macinfo */ \
10348    + 1 /* trailing zero */)
10349
10350   memset (&sections, 0, sizeof (sections));
10351
10352   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10353     {
10354       asection *sectp;
10355       uint32_t section_nr =
10356         read_4_bytes (dbfd,
10357                       dwp_htab->section_pool.v1.indices
10358                       + (unit_index + i) * sizeof (uint32_t));
10359
10360       if (section_nr == 0)
10361         break;
10362       if (section_nr >= dwp_file->num_sections)
10363         {
10364           error (_("Dwarf Error: bad DWP hash table, section number too large"
10365                    " [in module %s]"),
10366                  dwp_file->name);
10367         }
10368
10369       sectp = dwp_file->elf_sections[section_nr];
10370       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10371         {
10372           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10373                    " [in module %s]"),
10374                  dwp_file->name);
10375         }
10376     }
10377
10378   if (i < 2
10379       || dwarf2_section_empty_p (&sections.info_or_types)
10380       || dwarf2_section_empty_p (&sections.abbrev))
10381     {
10382       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10383                " [in module %s]"),
10384              dwp_file->name);
10385     }
10386   if (i == MAX_NR_V1_DWO_SECTIONS)
10387     {
10388       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10389                " [in module %s]"),
10390              dwp_file->name);
10391     }
10392
10393   /* It's easier for the rest of the code if we fake a struct dwo_file and
10394      have dwo_unit "live" in that.  At least for now.
10395
10396      The DWP file can be made up of a random collection of CUs and TUs.
10397      However, for each CU + set of TUs that came from the same original DWO
10398      file, we can combine them back into a virtual DWO file to save space
10399      (fewer struct dwo_file objects to allocate).  Remember that for really
10400      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10401
10402   std::string virtual_dwo_name =
10403     string_printf ("virtual-dwo/%d-%d-%d-%d",
10404                    get_section_id (&sections.abbrev),
10405                    get_section_id (&sections.line),
10406                    get_section_id (&sections.loc),
10407                    get_section_id (&sections.str_offsets));
10408   /* Can we use an existing virtual DWO file?  */
10409   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10410   /* Create one if necessary.  */
10411   if (*dwo_file_slot == NULL)
10412     {
10413       if (dwarf_read_debug)
10414         {
10415           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10416                               virtual_dwo_name.c_str ());
10417         }
10418       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10419       dwo_file->dwo_name
10420         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10421                                         virtual_dwo_name.c_str (),
10422                                         virtual_dwo_name.size ());
10423       dwo_file->comp_dir = comp_dir;
10424       dwo_file->sections.abbrev = sections.abbrev;
10425       dwo_file->sections.line = sections.line;
10426       dwo_file->sections.loc = sections.loc;
10427       dwo_file->sections.macinfo = sections.macinfo;
10428       dwo_file->sections.macro = sections.macro;
10429       dwo_file->sections.str_offsets = sections.str_offsets;
10430       /* The "str" section is global to the entire DWP file.  */
10431       dwo_file->sections.str = dwp_file->sections.str;
10432       /* The info or types section is assigned below to dwo_unit,
10433          there's no need to record it in dwo_file.
10434          Also, we can't simply record type sections in dwo_file because
10435          we record a pointer into the vector in dwo_unit.  As we collect more
10436          types we'll grow the vector and eventually have to reallocate space
10437          for it, invalidating all copies of pointers into the previous
10438          contents.  */
10439       *dwo_file_slot = dwo_file;
10440     }
10441   else
10442     {
10443       if (dwarf_read_debug)
10444         {
10445           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10446                               virtual_dwo_name.c_str ());
10447         }
10448       dwo_file = (struct dwo_file *) *dwo_file_slot;
10449     }
10450
10451   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10452   dwo_unit->dwo_file = dwo_file;
10453   dwo_unit->signature = signature;
10454   dwo_unit->section =
10455     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10456   *dwo_unit->section = sections.info_or_types;
10457   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10458
10459   return dwo_unit;
10460 }
10461
10462 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10463    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10464    piece within that section used by a TU/CU, return a virtual section
10465    of just that piece.  */
10466
10467 static struct dwarf2_section_info
10468 create_dwp_v2_section (struct dwarf2_section_info *section,
10469                        bfd_size_type offset, bfd_size_type size)
10470 {
10471   struct dwarf2_section_info result;
10472   asection *sectp;
10473
10474   gdb_assert (section != NULL);
10475   gdb_assert (!section->is_virtual);
10476
10477   memset (&result, 0, sizeof (result));
10478   result.s.containing_section = section;
10479   result.is_virtual = 1;
10480
10481   if (size == 0)
10482     return result;
10483
10484   sectp = get_section_bfd_section (section);
10485
10486   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10487      bounds of the real section.  This is a pretty-rare event, so just
10488      flag an error (easier) instead of a warning and trying to cope.  */
10489   if (sectp == NULL
10490       || offset + size > bfd_get_section_size (sectp))
10491     {
10492       bfd *abfd = sectp->owner;
10493
10494       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10495                " in section %s [in module %s]"),
10496              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10497              objfile_name (dwarf2_per_objfile->objfile));
10498     }
10499
10500   result.virtual_offset = offset;
10501   result.size = size;
10502   return result;
10503 }
10504
10505 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10506    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10507    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10508    This is for DWP version 2 files.  */
10509
10510 static struct dwo_unit *
10511 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10512                            uint32_t unit_index,
10513                            const char *comp_dir,
10514                            ULONGEST signature, int is_debug_types)
10515 {
10516   struct objfile *objfile = dwarf2_per_objfile->objfile;
10517   const struct dwp_hash_table *dwp_htab =
10518     is_debug_types ? dwp_file->tus : dwp_file->cus;
10519   bfd *dbfd = dwp_file->dbfd;
10520   const char *kind = is_debug_types ? "TU" : "CU";
10521   struct dwo_file *dwo_file;
10522   struct dwo_unit *dwo_unit;
10523   struct virtual_v2_dwo_sections sections;
10524   void **dwo_file_slot;
10525   int i;
10526
10527   gdb_assert (dwp_file->version == 2);
10528
10529   if (dwarf_read_debug)
10530     {
10531       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10532                           kind,
10533                           pulongest (unit_index), hex_string (signature),
10534                           dwp_file->name);
10535     }
10536
10537   /* Fetch the section offsets of this DWO unit.  */
10538
10539   memset (&sections, 0, sizeof (sections));
10540
10541   for (i = 0; i < dwp_htab->nr_columns; ++i)
10542     {
10543       uint32_t offset = read_4_bytes (dbfd,
10544                                       dwp_htab->section_pool.v2.offsets
10545                                       + (((unit_index - 1) * dwp_htab->nr_columns
10546                                           + i)
10547                                          * sizeof (uint32_t)));
10548       uint32_t size = read_4_bytes (dbfd,
10549                                     dwp_htab->section_pool.v2.sizes
10550                                     + (((unit_index - 1) * dwp_htab->nr_columns
10551                                         + i)
10552                                        * sizeof (uint32_t)));
10553
10554       switch (dwp_htab->section_pool.v2.section_ids[i])
10555         {
10556         case DW_SECT_INFO:
10557         case DW_SECT_TYPES:
10558           sections.info_or_types_offset = offset;
10559           sections.info_or_types_size = size;
10560           break;
10561         case DW_SECT_ABBREV:
10562           sections.abbrev_offset = offset;
10563           sections.abbrev_size = size;
10564           break;
10565         case DW_SECT_LINE:
10566           sections.line_offset = offset;
10567           sections.line_size = size;
10568           break;
10569         case DW_SECT_LOC:
10570           sections.loc_offset = offset;
10571           sections.loc_size = size;
10572           break;
10573         case DW_SECT_STR_OFFSETS:
10574           sections.str_offsets_offset = offset;
10575           sections.str_offsets_size = size;
10576           break;
10577         case DW_SECT_MACINFO:
10578           sections.macinfo_offset = offset;
10579           sections.macinfo_size = size;
10580           break;
10581         case DW_SECT_MACRO:
10582           sections.macro_offset = offset;
10583           sections.macro_size = size;
10584           break;
10585         }
10586     }
10587
10588   /* It's easier for the rest of the code if we fake a struct dwo_file and
10589      have dwo_unit "live" in that.  At least for now.
10590
10591      The DWP file can be made up of a random collection of CUs and TUs.
10592      However, for each CU + set of TUs that came from the same original DWO
10593      file, we can combine them back into a virtual DWO file to save space
10594      (fewer struct dwo_file objects to allocate).  Remember that for really
10595      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10596
10597   std::string virtual_dwo_name =
10598     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
10599                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10600                    (long) (sections.line_size ? sections.line_offset : 0),
10601                    (long) (sections.loc_size ? sections.loc_offset : 0),
10602                    (long) (sections.str_offsets_size
10603                            ? sections.str_offsets_offset : 0));
10604   /* Can we use an existing virtual DWO file?  */
10605   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10606   /* Create one if necessary.  */
10607   if (*dwo_file_slot == NULL)
10608     {
10609       if (dwarf_read_debug)
10610         {
10611           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10612                               virtual_dwo_name.c_str ());
10613         }
10614       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10615       dwo_file->dwo_name
10616         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10617                                         virtual_dwo_name.c_str (),
10618                                         virtual_dwo_name.size ());
10619       dwo_file->comp_dir = comp_dir;
10620       dwo_file->sections.abbrev =
10621         create_dwp_v2_section (&dwp_file->sections.abbrev,
10622                                sections.abbrev_offset, sections.abbrev_size);
10623       dwo_file->sections.line =
10624         create_dwp_v2_section (&dwp_file->sections.line,
10625                                sections.line_offset, sections.line_size);
10626       dwo_file->sections.loc =
10627         create_dwp_v2_section (&dwp_file->sections.loc,
10628                                sections.loc_offset, sections.loc_size);
10629       dwo_file->sections.macinfo =
10630         create_dwp_v2_section (&dwp_file->sections.macinfo,
10631                                sections.macinfo_offset, sections.macinfo_size);
10632       dwo_file->sections.macro =
10633         create_dwp_v2_section (&dwp_file->sections.macro,
10634                                sections.macro_offset, sections.macro_size);
10635       dwo_file->sections.str_offsets =
10636         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10637                                sections.str_offsets_offset,
10638                                sections.str_offsets_size);
10639       /* The "str" section is global to the entire DWP file.  */
10640       dwo_file->sections.str = dwp_file->sections.str;
10641       /* The info or types section is assigned below to dwo_unit,
10642          there's no need to record it in dwo_file.
10643          Also, we can't simply record type sections in dwo_file because
10644          we record a pointer into the vector in dwo_unit.  As we collect more
10645          types we'll grow the vector and eventually have to reallocate space
10646          for it, invalidating all copies of pointers into the previous
10647          contents.  */
10648       *dwo_file_slot = dwo_file;
10649     }
10650   else
10651     {
10652       if (dwarf_read_debug)
10653         {
10654           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10655                               virtual_dwo_name.c_str ());
10656         }
10657       dwo_file = (struct dwo_file *) *dwo_file_slot;
10658     }
10659
10660   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10661   dwo_unit->dwo_file = dwo_file;
10662   dwo_unit->signature = signature;
10663   dwo_unit->section =
10664     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10665   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10666                                               ? &dwp_file->sections.types
10667                                               : &dwp_file->sections.info,
10668                                               sections.info_or_types_offset,
10669                                               sections.info_or_types_size);
10670   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10671
10672   return dwo_unit;
10673 }
10674
10675 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10676    Returns NULL if the signature isn't found.  */
10677
10678 static struct dwo_unit *
10679 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10680                         ULONGEST signature, int is_debug_types)
10681 {
10682   const struct dwp_hash_table *dwp_htab =
10683     is_debug_types ? dwp_file->tus : dwp_file->cus;
10684   bfd *dbfd = dwp_file->dbfd;
10685   uint32_t mask = dwp_htab->nr_slots - 1;
10686   uint32_t hash = signature & mask;
10687   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10688   unsigned int i;
10689   void **slot;
10690   struct dwo_unit find_dwo_cu;
10691
10692   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10693   find_dwo_cu.signature = signature;
10694   slot = htab_find_slot (is_debug_types
10695                          ? dwp_file->loaded_tus
10696                          : dwp_file->loaded_cus,
10697                          &find_dwo_cu, INSERT);
10698
10699   if (*slot != NULL)
10700     return (struct dwo_unit *) *slot;
10701
10702   /* Use a for loop so that we don't loop forever on bad debug info.  */
10703   for (i = 0; i < dwp_htab->nr_slots; ++i)
10704     {
10705       ULONGEST signature_in_table;
10706
10707       signature_in_table =
10708         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
10709       if (signature_in_table == signature)
10710         {
10711           uint32_t unit_index =
10712             read_4_bytes (dbfd,
10713                           dwp_htab->unit_table + hash * sizeof (uint32_t));
10714
10715           if (dwp_file->version == 1)
10716             {
10717               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
10718                                                  comp_dir, signature,
10719                                                  is_debug_types);
10720             }
10721           else
10722             {
10723               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
10724                                                  comp_dir, signature,
10725                                                  is_debug_types);
10726             }
10727           return (struct dwo_unit *) *slot;
10728         }
10729       if (signature_in_table == 0)
10730         return NULL;
10731       hash = (hash + hash2) & mask;
10732     }
10733
10734   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
10735            " [in module %s]"),
10736          dwp_file->name);
10737 }
10738
10739 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
10740    Open the file specified by FILE_NAME and hand it off to BFD for
10741    preliminary analysis.  Return a newly initialized bfd *, which
10742    includes a canonicalized copy of FILE_NAME.
10743    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
10744    SEARCH_CWD is true if the current directory is to be searched.
10745    It will be searched before debug-file-directory.
10746    If successful, the file is added to the bfd include table of the
10747    objfile's bfd (see gdb_bfd_record_inclusion).
10748    If unable to find/open the file, return NULL.
10749    NOTE: This function is derived from symfile_bfd_open.  */
10750
10751 static gdb_bfd_ref_ptr
10752 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
10753 {
10754   int desc, flags;
10755   char *absolute_name;
10756   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
10757      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
10758      to debug_file_directory.  */
10759   char *search_path;
10760   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
10761
10762   if (search_cwd)
10763     {
10764       if (*debug_file_directory != '\0')
10765         search_path = concat (".", dirname_separator_string,
10766                               debug_file_directory, (char *) NULL);
10767       else
10768         search_path = xstrdup (".");
10769     }
10770   else
10771     search_path = xstrdup (debug_file_directory);
10772
10773   flags = OPF_RETURN_REALPATH;
10774   if (is_dwp)
10775     flags |= OPF_SEARCH_IN_PATH;
10776   desc = openp (search_path, flags, file_name,
10777                 O_RDONLY | O_BINARY, &absolute_name);
10778   xfree (search_path);
10779   if (desc < 0)
10780     return NULL;
10781
10782   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
10783   xfree (absolute_name);
10784   if (sym_bfd == NULL)
10785     return NULL;
10786   bfd_set_cacheable (sym_bfd.get (), 1);
10787
10788   if (!bfd_check_format (sym_bfd.get (), bfd_object))
10789     return NULL;
10790
10791   /* Success.  Record the bfd as having been included by the objfile's bfd.
10792      This is important because things like demangled_names_hash lives in the
10793      objfile's per_bfd space and may have references to things like symbol
10794      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
10795   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
10796
10797   return sym_bfd;
10798 }
10799
10800 /* Try to open DWO file FILE_NAME.
10801    COMP_DIR is the DW_AT_comp_dir attribute.
10802    The result is the bfd handle of the file.
10803    If there is a problem finding or opening the file, return NULL.
10804    Upon success, the canonicalized path of the file is stored in the bfd,
10805    same as symfile_bfd_open.  */
10806
10807 static gdb_bfd_ref_ptr
10808 open_dwo_file (const char *file_name, const char *comp_dir)
10809 {
10810   if (IS_ABSOLUTE_PATH (file_name))
10811     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
10812
10813   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
10814
10815   if (comp_dir != NULL)
10816     {
10817       char *path_to_try = concat (comp_dir, SLASH_STRING,
10818                                   file_name, (char *) NULL);
10819
10820       /* NOTE: If comp_dir is a relative path, this will also try the
10821          search path, which seems useful.  */
10822       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
10823                                                 1 /*search_cwd*/));
10824       xfree (path_to_try);
10825       if (abfd != NULL)
10826         return abfd;
10827     }
10828
10829   /* That didn't work, try debug-file-directory, which, despite its name,
10830      is a list of paths.  */
10831
10832   if (*debug_file_directory == '\0')
10833     return NULL;
10834
10835   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
10836 }
10837
10838 /* This function is mapped across the sections and remembers the offset and
10839    size of each of the DWO debugging sections we are interested in.  */
10840
10841 static void
10842 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
10843 {
10844   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
10845   const struct dwop_section_names *names = &dwop_section_names;
10846
10847   if (section_is_p (sectp->name, &names->abbrev_dwo))
10848     {
10849       dwo_sections->abbrev.s.section = sectp;
10850       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
10851     }
10852   else if (section_is_p (sectp->name, &names->info_dwo))
10853     {
10854       dwo_sections->info.s.section = sectp;
10855       dwo_sections->info.size = bfd_get_section_size (sectp);
10856     }
10857   else if (section_is_p (sectp->name, &names->line_dwo))
10858     {
10859       dwo_sections->line.s.section = sectp;
10860       dwo_sections->line.size = bfd_get_section_size (sectp);
10861     }
10862   else if (section_is_p (sectp->name, &names->loc_dwo))
10863     {
10864       dwo_sections->loc.s.section = sectp;
10865       dwo_sections->loc.size = bfd_get_section_size (sectp);
10866     }
10867   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10868     {
10869       dwo_sections->macinfo.s.section = sectp;
10870       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
10871     }
10872   else if (section_is_p (sectp->name, &names->macro_dwo))
10873     {
10874       dwo_sections->macro.s.section = sectp;
10875       dwo_sections->macro.size = bfd_get_section_size (sectp);
10876     }
10877   else if (section_is_p (sectp->name, &names->str_dwo))
10878     {
10879       dwo_sections->str.s.section = sectp;
10880       dwo_sections->str.size = bfd_get_section_size (sectp);
10881     }
10882   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10883     {
10884       dwo_sections->str_offsets.s.section = sectp;
10885       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
10886     }
10887   else if (section_is_p (sectp->name, &names->types_dwo))
10888     {
10889       struct dwarf2_section_info type_section;
10890
10891       memset (&type_section, 0, sizeof (type_section));
10892       type_section.s.section = sectp;
10893       type_section.size = bfd_get_section_size (sectp);
10894       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
10895                      &type_section);
10896     }
10897 }
10898
10899 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
10900    by PER_CU.  This is for the non-DWP case.
10901    The result is NULL if DWO_NAME can't be found.  */
10902
10903 static struct dwo_file *
10904 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
10905                         const char *dwo_name, const char *comp_dir)
10906 {
10907   struct objfile *objfile = dwarf2_per_objfile->objfile;
10908   struct dwo_file *dwo_file;
10909   struct cleanup *cleanups;
10910
10911   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
10912   if (dbfd == NULL)
10913     {
10914       if (dwarf_read_debug)
10915         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
10916       return NULL;
10917     }
10918   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10919   dwo_file->dwo_name = dwo_name;
10920   dwo_file->comp_dir = comp_dir;
10921   dwo_file->dbfd = dbfd.release ();
10922
10923   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
10924
10925   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
10926                          &dwo_file->sections);
10927
10928   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
10929
10930   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
10931                                  dwo_file->tus);
10932
10933   discard_cleanups (cleanups);
10934
10935   if (dwarf_read_debug)
10936     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
10937
10938   return dwo_file;
10939 }
10940
10941 /* This function is mapped across the sections and remembers the offset and
10942    size of each of the DWP debugging sections common to version 1 and 2 that
10943    we are interested in.  */
10944
10945 static void
10946 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
10947                                    void *dwp_file_ptr)
10948 {
10949   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10950   const struct dwop_section_names *names = &dwop_section_names;
10951   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10952
10953   /* Record the ELF section number for later lookup: this is what the
10954      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10955   gdb_assert (elf_section_nr < dwp_file->num_sections);
10956   dwp_file->elf_sections[elf_section_nr] = sectp;
10957
10958   /* Look for specific sections that we need.  */
10959   if (section_is_p (sectp->name, &names->str_dwo))
10960     {
10961       dwp_file->sections.str.s.section = sectp;
10962       dwp_file->sections.str.size = bfd_get_section_size (sectp);
10963     }
10964   else if (section_is_p (sectp->name, &names->cu_index))
10965     {
10966       dwp_file->sections.cu_index.s.section = sectp;
10967       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
10968     }
10969   else if (section_is_p (sectp->name, &names->tu_index))
10970     {
10971       dwp_file->sections.tu_index.s.section = sectp;
10972       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
10973     }
10974 }
10975
10976 /* This function is mapped across the sections and remembers the offset and
10977    size of each of the DWP version 2 debugging sections that we are interested
10978    in.  This is split into a separate function because we don't know if we
10979    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
10980
10981 static void
10982 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
10983 {
10984   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
10985   const struct dwop_section_names *names = &dwop_section_names;
10986   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
10987
10988   /* Record the ELF section number for later lookup: this is what the
10989      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
10990   gdb_assert (elf_section_nr < dwp_file->num_sections);
10991   dwp_file->elf_sections[elf_section_nr] = sectp;
10992
10993   /* Look for specific sections that we need.  */
10994   if (section_is_p (sectp->name, &names->abbrev_dwo))
10995     {
10996       dwp_file->sections.abbrev.s.section = sectp;
10997       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
10998     }
10999   else if (section_is_p (sectp->name, &names->info_dwo))
11000     {
11001       dwp_file->sections.info.s.section = sectp;
11002       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11003     }
11004   else if (section_is_p (sectp->name, &names->line_dwo))
11005     {
11006       dwp_file->sections.line.s.section = sectp;
11007       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11008     }
11009   else if (section_is_p (sectp->name, &names->loc_dwo))
11010     {
11011       dwp_file->sections.loc.s.section = sectp;
11012       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11013     }
11014   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11015     {
11016       dwp_file->sections.macinfo.s.section = sectp;
11017       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11018     }
11019   else if (section_is_p (sectp->name, &names->macro_dwo))
11020     {
11021       dwp_file->sections.macro.s.section = sectp;
11022       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11023     }
11024   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11025     {
11026       dwp_file->sections.str_offsets.s.section = sectp;
11027       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11028     }
11029   else if (section_is_p (sectp->name, &names->types_dwo))
11030     {
11031       dwp_file->sections.types.s.section = sectp;
11032       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11033     }
11034 }
11035
11036 /* Hash function for dwp_file loaded CUs/TUs.  */
11037
11038 static hashval_t
11039 hash_dwp_loaded_cutus (const void *item)
11040 {
11041   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11042
11043   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11044   return dwo_unit->signature;
11045 }
11046
11047 /* Equality function for dwp_file loaded CUs/TUs.  */
11048
11049 static int
11050 eq_dwp_loaded_cutus (const void *a, const void *b)
11051 {
11052   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11053   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11054
11055   return dua->signature == dub->signature;
11056 }
11057
11058 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11059
11060 static htab_t
11061 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11062 {
11063   return htab_create_alloc_ex (3,
11064                                hash_dwp_loaded_cutus,
11065                                eq_dwp_loaded_cutus,
11066                                NULL,
11067                                &objfile->objfile_obstack,
11068                                hashtab_obstack_allocate,
11069                                dummy_obstack_deallocate);
11070 }
11071
11072 /* Try to open DWP file FILE_NAME.
11073    The result is the bfd handle of the file.
11074    If there is a problem finding or opening the file, return NULL.
11075    Upon success, the canonicalized path of the file is stored in the bfd,
11076    same as symfile_bfd_open.  */
11077
11078 static gdb_bfd_ref_ptr
11079 open_dwp_file (const char *file_name)
11080 {
11081   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11082                                             1 /*search_cwd*/));
11083   if (abfd != NULL)
11084     return abfd;
11085
11086   /* Work around upstream bug 15652.
11087      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11088      [Whether that's a "bug" is debatable, but it is getting in our way.]
11089      We have no real idea where the dwp file is, because gdb's realpath-ing
11090      of the executable's path may have discarded the needed info.
11091      [IWBN if the dwp file name was recorded in the executable, akin to
11092      .gnu_debuglink, but that doesn't exist yet.]
11093      Strip the directory from FILE_NAME and search again.  */
11094   if (*debug_file_directory != '\0')
11095     {
11096       /* Don't implicitly search the current directory here.
11097          If the user wants to search "." to handle this case,
11098          it must be added to debug-file-directory.  */
11099       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11100                                  0 /*search_cwd*/);
11101     }
11102
11103   return NULL;
11104 }
11105
11106 /* Initialize the use of the DWP file for the current objfile.
11107    By convention the name of the DWP file is ${objfile}.dwp.
11108    The result is NULL if it can't be found.  */
11109
11110 static struct dwp_file *
11111 open_and_init_dwp_file (void)
11112 {
11113   struct objfile *objfile = dwarf2_per_objfile->objfile;
11114   struct dwp_file *dwp_file;
11115
11116   /* Try to find first .dwp for the binary file before any symbolic links
11117      resolving.  */
11118
11119   /* If the objfile is a debug file, find the name of the real binary
11120      file and get the name of dwp file from there.  */
11121   std::string dwp_name;
11122   if (objfile->separate_debug_objfile_backlink != NULL)
11123     {
11124       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11125       const char *backlink_basename = lbasename (backlink->original_name);
11126
11127       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11128     }
11129   else
11130     dwp_name = objfile->original_name;
11131
11132   dwp_name += ".dwp";
11133
11134   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11135   if (dbfd == NULL
11136       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11137     {
11138       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11139       dwp_name = objfile_name (objfile);
11140       dwp_name += ".dwp";
11141       dbfd = open_dwp_file (dwp_name.c_str ());
11142     }
11143
11144   if (dbfd == NULL)
11145     {
11146       if (dwarf_read_debug)
11147         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11148       return NULL;
11149     }
11150   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11151   dwp_file->name = bfd_get_filename (dbfd.get ());
11152   dwp_file->dbfd = dbfd.release ();
11153
11154   /* +1: section 0 is unused */
11155   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11156   dwp_file->elf_sections =
11157     OBSTACK_CALLOC (&objfile->objfile_obstack,
11158                     dwp_file->num_sections, asection *);
11159
11160   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11161                          dwp_file);
11162
11163   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11164
11165   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11166
11167   /* The DWP file version is stored in the hash table.  Oh well.  */
11168   if (dwp_file->cus && dwp_file->tus
11169       && dwp_file->cus->version != dwp_file->tus->version)
11170     {
11171       /* Technically speaking, we should try to limp along, but this is
11172          pretty bizarre.  We use pulongest here because that's the established
11173          portability solution (e.g, we cannot use %u for uint32_t).  */
11174       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11175                " TU version %s [in DWP file %s]"),
11176              pulongest (dwp_file->cus->version),
11177              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11178     }
11179
11180   if (dwp_file->cus)
11181     dwp_file->version = dwp_file->cus->version;
11182   else if (dwp_file->tus)
11183     dwp_file->version = dwp_file->tus->version;
11184   else
11185     dwp_file->version = 2;
11186
11187   if (dwp_file->version == 2)
11188     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11189                            dwp_file);
11190
11191   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11192   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11193
11194   if (dwarf_read_debug)
11195     {
11196       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11197       fprintf_unfiltered (gdb_stdlog,
11198                           "    %s CUs, %s TUs\n",
11199                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11200                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11201     }
11202
11203   return dwp_file;
11204 }
11205
11206 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11207
11208 static struct dwp_file *
11209 get_dwp_file (void)
11210 {
11211   if (! dwarf2_per_objfile->dwp_checked)
11212     {
11213       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11214       dwarf2_per_objfile->dwp_checked = 1;
11215     }
11216   return dwarf2_per_objfile->dwp_file;
11217 }
11218
11219 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11220    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11221    or in the DWP file for the objfile, referenced by THIS_UNIT.
11222    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11223    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11224
11225    This is called, for example, when wanting to read a variable with a
11226    complex location.  Therefore we don't want to do file i/o for every call.
11227    Therefore we don't want to look for a DWO file on every call.
11228    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11229    then we check if we've already seen DWO_NAME, and only THEN do we check
11230    for a DWO file.
11231
11232    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11233    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11234
11235 static struct dwo_unit *
11236 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11237                  const char *dwo_name, const char *comp_dir,
11238                  ULONGEST signature, int is_debug_types)
11239 {
11240   struct objfile *objfile = dwarf2_per_objfile->objfile;
11241   const char *kind = is_debug_types ? "TU" : "CU";
11242   void **dwo_file_slot;
11243   struct dwo_file *dwo_file;
11244   struct dwp_file *dwp_file;
11245
11246   /* First see if there's a DWP file.
11247      If we have a DWP file but didn't find the DWO inside it, don't
11248      look for the original DWO file.  It makes gdb behave differently
11249      depending on whether one is debugging in the build tree.  */
11250
11251   dwp_file = get_dwp_file ();
11252   if (dwp_file != NULL)
11253     {
11254       const struct dwp_hash_table *dwp_htab =
11255         is_debug_types ? dwp_file->tus : dwp_file->cus;
11256
11257       if (dwp_htab != NULL)
11258         {
11259           struct dwo_unit *dwo_cutu =
11260             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11261                                     signature, is_debug_types);
11262
11263           if (dwo_cutu != NULL)
11264             {
11265               if (dwarf_read_debug)
11266                 {
11267                   fprintf_unfiltered (gdb_stdlog,
11268                                       "Virtual DWO %s %s found: @%s\n",
11269                                       kind, hex_string (signature),
11270                                       host_address_to_string (dwo_cutu));
11271                 }
11272               return dwo_cutu;
11273             }
11274         }
11275     }
11276   else
11277     {
11278       /* No DWP file, look for the DWO file.  */
11279
11280       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11281       if (*dwo_file_slot == NULL)
11282         {
11283           /* Read in the file and build a table of the CUs/TUs it contains.  */
11284           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11285         }
11286       /* NOTE: This will be NULL if unable to open the file.  */
11287       dwo_file = (struct dwo_file *) *dwo_file_slot;
11288
11289       if (dwo_file != NULL)
11290         {
11291           struct dwo_unit *dwo_cutu = NULL;
11292
11293           if (is_debug_types && dwo_file->tus)
11294             {
11295               struct dwo_unit find_dwo_cutu;
11296
11297               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11298               find_dwo_cutu.signature = signature;
11299               dwo_cutu
11300                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11301             }
11302           else if (!is_debug_types && dwo_file->cus)
11303             {
11304               struct dwo_unit find_dwo_cutu;
11305
11306               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11307               find_dwo_cutu.signature = signature;
11308               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11309                                                        &find_dwo_cutu);
11310             }
11311
11312           if (dwo_cutu != NULL)
11313             {
11314               if (dwarf_read_debug)
11315                 {
11316                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11317                                       kind, dwo_name, hex_string (signature),
11318                                       host_address_to_string (dwo_cutu));
11319                 }
11320               return dwo_cutu;
11321             }
11322         }
11323     }
11324
11325   /* We didn't find it.  This could mean a dwo_id mismatch, or
11326      someone deleted the DWO/DWP file, or the search path isn't set up
11327      correctly to find the file.  */
11328
11329   if (dwarf_read_debug)
11330     {
11331       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11332                           kind, dwo_name, hex_string (signature));
11333     }
11334
11335   /* This is a warning and not a complaint because it can be caused by
11336      pilot error (e.g., user accidentally deleting the DWO).  */
11337   {
11338     /* Print the name of the DWP file if we looked there, helps the user
11339        better diagnose the problem.  */
11340     std::string dwp_text;
11341
11342     if (dwp_file != NULL)
11343       dwp_text = string_printf (" [in DWP file %s]",
11344                                 lbasename (dwp_file->name));
11345
11346     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11347                " [in module %s]"),
11348              kind, dwo_name, hex_string (signature),
11349              dwp_text.c_str (),
11350              this_unit->is_debug_types ? "TU" : "CU",
11351              to_underlying (this_unit->sect_off), objfile_name (objfile));
11352   }
11353   return NULL;
11354 }
11355
11356 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11357    See lookup_dwo_cutu_unit for details.  */
11358
11359 static struct dwo_unit *
11360 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11361                       const char *dwo_name, const char *comp_dir,
11362                       ULONGEST signature)
11363 {
11364   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11365 }
11366
11367 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11368    See lookup_dwo_cutu_unit for details.  */
11369
11370 static struct dwo_unit *
11371 lookup_dwo_type_unit (struct signatured_type *this_tu,
11372                       const char *dwo_name, const char *comp_dir)
11373 {
11374   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11375 }
11376
11377 /* Traversal function for queue_and_load_all_dwo_tus.  */
11378
11379 static int
11380 queue_and_load_dwo_tu (void **slot, void *info)
11381 {
11382   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11383   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11384   ULONGEST signature = dwo_unit->signature;
11385   struct signatured_type *sig_type =
11386     lookup_dwo_signatured_type (per_cu->cu, signature);
11387
11388   if (sig_type != NULL)
11389     {
11390       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11391
11392       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11393          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11394          while processing PER_CU.  */
11395       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11396         load_full_type_unit (sig_cu);
11397       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11398     }
11399
11400   return 1;
11401 }
11402
11403 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11404    The DWO may have the only definition of the type, though it may not be
11405    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11406    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11407
11408 static void
11409 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11410 {
11411   struct dwo_unit *dwo_unit;
11412   struct dwo_file *dwo_file;
11413
11414   gdb_assert (!per_cu->is_debug_types);
11415   gdb_assert (get_dwp_file () == NULL);
11416   gdb_assert (per_cu->cu != NULL);
11417
11418   dwo_unit = per_cu->cu->dwo_unit;
11419   gdb_assert (dwo_unit != NULL);
11420
11421   dwo_file = dwo_unit->dwo_file;
11422   if (dwo_file->tus != NULL)
11423     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11424 }
11425
11426 /* Free all resources associated with DWO_FILE.
11427    Close the DWO file and munmap the sections.
11428    All memory should be on the objfile obstack.  */
11429
11430 static void
11431 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11432 {
11433
11434   /* Note: dbfd is NULL for virtual DWO files.  */
11435   gdb_bfd_unref (dwo_file->dbfd);
11436
11437   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11438 }
11439
11440 /* Wrapper for free_dwo_file for use in cleanups.  */
11441
11442 static void
11443 free_dwo_file_cleanup (void *arg)
11444 {
11445   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11446   struct objfile *objfile = dwarf2_per_objfile->objfile;
11447
11448   free_dwo_file (dwo_file, objfile);
11449 }
11450
11451 /* Traversal function for free_dwo_files.  */
11452
11453 static int
11454 free_dwo_file_from_slot (void **slot, void *info)
11455 {
11456   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11457   struct objfile *objfile = (struct objfile *) info;
11458
11459   free_dwo_file (dwo_file, objfile);
11460
11461   return 1;
11462 }
11463
11464 /* Free all resources associated with DWO_FILES.  */
11465
11466 static void
11467 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11468 {
11469   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11470 }
11471 \f
11472 /* Read in various DIEs.  */
11473
11474 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11475    Inherit only the children of the DW_AT_abstract_origin DIE not being
11476    already referenced by DW_AT_abstract_origin from the children of the
11477    current DIE.  */
11478
11479 static void
11480 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11481 {
11482   struct die_info *child_die;
11483   sect_offset *offsetp;
11484   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11485   struct die_info *origin_die;
11486   /* Iterator of the ORIGIN_DIE children.  */
11487   struct die_info *origin_child_die;
11488   struct attribute *attr;
11489   struct dwarf2_cu *origin_cu;
11490   struct pending **origin_previous_list_in_scope;
11491
11492   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11493   if (!attr)
11494     return;
11495
11496   /* Note that following die references may follow to a die in a
11497      different cu.  */
11498
11499   origin_cu = cu;
11500   origin_die = follow_die_ref (die, attr, &origin_cu);
11501
11502   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11503      symbols in.  */
11504   origin_previous_list_in_scope = origin_cu->list_in_scope;
11505   origin_cu->list_in_scope = cu->list_in_scope;
11506
11507   if (die->tag != origin_die->tag
11508       && !(die->tag == DW_TAG_inlined_subroutine
11509            && origin_die->tag == DW_TAG_subprogram))
11510     complaint (&symfile_complaints,
11511                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11512                to_underlying (die->sect_off),
11513                to_underlying (origin_die->sect_off));
11514
11515   std::vector<sect_offset> offsets;
11516
11517   for (child_die = die->child;
11518        child_die && child_die->tag;
11519        child_die = sibling_die (child_die))
11520     {
11521       struct die_info *child_origin_die;
11522       struct dwarf2_cu *child_origin_cu;
11523
11524       /* We are trying to process concrete instance entries:
11525          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11526          it's not relevant to our analysis here. i.e. detecting DIEs that are
11527          present in the abstract instance but not referenced in the concrete
11528          one.  */
11529       if (child_die->tag == DW_TAG_call_site
11530           || child_die->tag == DW_TAG_GNU_call_site)
11531         continue;
11532
11533       /* For each CHILD_DIE, find the corresponding child of
11534          ORIGIN_DIE.  If there is more than one layer of
11535          DW_AT_abstract_origin, follow them all; there shouldn't be,
11536          but GCC versions at least through 4.4 generate this (GCC PR
11537          40573).  */
11538       child_origin_die = child_die;
11539       child_origin_cu = cu;
11540       while (1)
11541         {
11542           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11543                               child_origin_cu);
11544           if (attr == NULL)
11545             break;
11546           child_origin_die = follow_die_ref (child_origin_die, attr,
11547                                              &child_origin_cu);
11548         }
11549
11550       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11551          counterpart may exist.  */
11552       if (child_origin_die != child_die)
11553         {
11554           if (child_die->tag != child_origin_die->tag
11555               && !(child_die->tag == DW_TAG_inlined_subroutine
11556                    && child_origin_die->tag == DW_TAG_subprogram))
11557             complaint (&symfile_complaints,
11558                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11559                          "different tags"),
11560                        to_underlying (child_die->sect_off),
11561                        to_underlying (child_origin_die->sect_off));
11562           if (child_origin_die->parent != origin_die)
11563             complaint (&symfile_complaints,
11564                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11565                          "different parents"),
11566                        to_underlying (child_die->sect_off),
11567                        to_underlying (child_origin_die->sect_off));
11568           else
11569             offsets.push_back (child_origin_die->sect_off);
11570         }
11571     }
11572   std::sort (offsets.begin (), offsets.end ());
11573   sect_offset *offsets_end = offsets.data () + offsets.size ();
11574   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
11575     if (offsetp[-1] == *offsetp)
11576       complaint (&symfile_complaints,
11577                  _("Multiple children of DIE 0x%x refer "
11578                    "to DIE 0x%x as their abstract origin"),
11579                  to_underlying (die->sect_off), to_underlying (*offsetp));
11580
11581   offsetp = offsets.data ();
11582   origin_child_die = origin_die->child;
11583   while (origin_child_die && origin_child_die->tag)
11584     {
11585       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11586       while (offsetp < offsets_end
11587              && *offsetp < origin_child_die->sect_off)
11588         offsetp++;
11589       if (offsetp >= offsets_end
11590           || *offsetp > origin_child_die->sect_off)
11591         {
11592           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11593              Check whether we're already processing ORIGIN_CHILD_DIE.
11594              This can happen with mutually referenced abstract_origins.
11595              PR 16581.  */
11596           if (!origin_child_die->in_process)
11597             process_die (origin_child_die, origin_cu);
11598         }
11599       origin_child_die = sibling_die (origin_child_die);
11600     }
11601   origin_cu->list_in_scope = origin_previous_list_in_scope;
11602 }
11603
11604 static void
11605 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11606 {
11607   struct objfile *objfile = cu->objfile;
11608   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11609   struct context_stack *newobj;
11610   CORE_ADDR lowpc;
11611   CORE_ADDR highpc;
11612   struct die_info *child_die;
11613   struct attribute *attr, *call_line, *call_file;
11614   const char *name;
11615   CORE_ADDR baseaddr;
11616   struct block *block;
11617   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11618   VEC (symbolp) *template_args = NULL;
11619   struct template_symbol *templ_func = NULL;
11620
11621   if (inlined_func)
11622     {
11623       /* If we do not have call site information, we can't show the
11624          caller of this inlined function.  That's too confusing, so
11625          only use the scope for local variables.  */
11626       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11627       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11628       if (call_line == NULL || call_file == NULL)
11629         {
11630           read_lexical_block_scope (die, cu);
11631           return;
11632         }
11633     }
11634
11635   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11636
11637   name = dwarf2_name (die, cu);
11638
11639   /* Ignore functions with missing or empty names.  These are actually
11640      illegal according to the DWARF standard.  */
11641   if (name == NULL)
11642     {
11643       complaint (&symfile_complaints,
11644                  _("missing name for subprogram DIE at %d"),
11645                  to_underlying (die->sect_off));
11646       return;
11647     }
11648
11649   /* Ignore functions with missing or invalid low and high pc attributes.  */
11650   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11651       <= PC_BOUNDS_INVALID)
11652     {
11653       attr = dwarf2_attr (die, DW_AT_external, cu);
11654       if (!attr || !DW_UNSND (attr))
11655         complaint (&symfile_complaints,
11656                    _("cannot get low and high bounds "
11657                      "for subprogram DIE at %d"),
11658                    to_underlying (die->sect_off));
11659       return;
11660     }
11661
11662   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11663   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11664
11665   /* If we have any template arguments, then we must allocate a
11666      different sort of symbol.  */
11667   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11668     {
11669       if (child_die->tag == DW_TAG_template_type_param
11670           || child_die->tag == DW_TAG_template_value_param)
11671         {
11672           templ_func = allocate_template_symbol (objfile);
11673           templ_func->base.is_cplus_template_function = 1;
11674           break;
11675         }
11676     }
11677
11678   newobj = push_context (0, lowpc);
11679   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11680                                (struct symbol *) templ_func);
11681
11682   /* If there is a location expression for DW_AT_frame_base, record
11683      it.  */
11684   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11685   if (attr)
11686     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11687
11688   /* If there is a location for the static link, record it.  */
11689   newobj->static_link = NULL;
11690   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11691   if (attr)
11692     {
11693       newobj->static_link
11694         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11695       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
11696     }
11697
11698   cu->list_in_scope = &local_symbols;
11699
11700   if (die->child != NULL)
11701     {
11702       child_die = die->child;
11703       while (child_die && child_die->tag)
11704         {
11705           if (child_die->tag == DW_TAG_template_type_param
11706               || child_die->tag == DW_TAG_template_value_param)
11707             {
11708               struct symbol *arg = new_symbol (child_die, NULL, cu);
11709
11710               if (arg != NULL)
11711                 VEC_safe_push (symbolp, template_args, arg);
11712             }
11713           else
11714             process_die (child_die, cu);
11715           child_die = sibling_die (child_die);
11716         }
11717     }
11718
11719   inherit_abstract_dies (die, cu);
11720
11721   /* If we have a DW_AT_specification, we might need to import using
11722      directives from the context of the specification DIE.  See the
11723      comment in determine_prefix.  */
11724   if (cu->language == language_cplus
11725       && dwarf2_attr (die, DW_AT_specification, cu))
11726     {
11727       struct dwarf2_cu *spec_cu = cu;
11728       struct die_info *spec_die = die_specification (die, &spec_cu);
11729
11730       while (spec_die)
11731         {
11732           child_die = spec_die->child;
11733           while (child_die && child_die->tag)
11734             {
11735               if (child_die->tag == DW_TAG_imported_module)
11736                 process_die (child_die, spec_cu);
11737               child_die = sibling_die (child_die);
11738             }
11739
11740           /* In some cases, GCC generates specification DIEs that
11741              themselves contain DW_AT_specification attributes.  */
11742           spec_die = die_specification (spec_die, &spec_cu);
11743         }
11744     }
11745
11746   newobj = pop_context ();
11747   /* Make a block for the local symbols within.  */
11748   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
11749                         newobj->static_link, lowpc, highpc);
11750
11751   /* For C++, set the block's scope.  */
11752   if ((cu->language == language_cplus
11753        || cu->language == language_fortran
11754        || cu->language == language_d
11755        || cu->language == language_rust)
11756       && cu->processing_has_namespace_info)
11757     block_set_scope (block, determine_prefix (die, cu),
11758                      &objfile->objfile_obstack);
11759
11760   /* If we have address ranges, record them.  */
11761   dwarf2_record_block_ranges (die, block, baseaddr, cu);
11762
11763   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
11764
11765   /* Attach template arguments to function.  */
11766   if (! VEC_empty (symbolp, template_args))
11767     {
11768       gdb_assert (templ_func != NULL);
11769
11770       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
11771       templ_func->template_arguments
11772         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
11773                      templ_func->n_template_arguments);
11774       memcpy (templ_func->template_arguments,
11775               VEC_address (symbolp, template_args),
11776               (templ_func->n_template_arguments * sizeof (struct symbol *)));
11777       VEC_free (symbolp, template_args);
11778     }
11779
11780   /* In C++, we can have functions nested inside functions (e.g., when
11781      a function declares a class that has methods).  This means that
11782      when we finish processing a function scope, we may need to go
11783      back to building a containing block's symbol lists.  */
11784   local_symbols = newobj->locals;
11785   local_using_directives = newobj->local_using_directives;
11786
11787   /* If we've finished processing a top-level function, subsequent
11788      symbols go in the file symbol list.  */
11789   if (outermost_context_p ())
11790     cu->list_in_scope = &file_symbols;
11791 }
11792
11793 /* Process all the DIES contained within a lexical block scope.  Start
11794    a new scope, process the dies, and then close the scope.  */
11795
11796 static void
11797 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
11798 {
11799   struct objfile *objfile = cu->objfile;
11800   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11801   struct context_stack *newobj;
11802   CORE_ADDR lowpc, highpc;
11803   struct die_info *child_die;
11804   CORE_ADDR baseaddr;
11805
11806   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11807
11808   /* Ignore blocks with missing or invalid low and high pc attributes.  */
11809   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
11810      as multiple lexical blocks?  Handling children in a sane way would
11811      be nasty.  Might be easier to properly extend generic blocks to
11812      describe ranges.  */
11813   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
11814     {
11815     case PC_BOUNDS_NOT_PRESENT:
11816       /* DW_TAG_lexical_block has no attributes, process its children as if
11817          there was no wrapping by that DW_TAG_lexical_block.
11818          GCC does no longer produces such DWARF since GCC r224161.  */
11819       for (child_die = die->child;
11820            child_die != NULL && child_die->tag;
11821            child_die = sibling_die (child_die))
11822         process_die (child_die, cu);
11823       return;
11824     case PC_BOUNDS_INVALID:
11825       return;
11826     }
11827   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11828   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11829
11830   push_context (0, lowpc);
11831   if (die->child != NULL)
11832     {
11833       child_die = die->child;
11834       while (child_die && child_die->tag)
11835         {
11836           process_die (child_die, cu);
11837           child_die = sibling_die (child_die);
11838         }
11839     }
11840   inherit_abstract_dies (die, cu);
11841   newobj = pop_context ();
11842
11843   if (local_symbols != NULL || local_using_directives != NULL)
11844     {
11845       struct block *block
11846         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
11847                         newobj->start_addr, highpc);
11848
11849       /* Note that recording ranges after traversing children, as we
11850          do here, means that recording a parent's ranges entails
11851          walking across all its children's ranges as they appear in
11852          the address map, which is quadratic behavior.
11853
11854          It would be nicer to record the parent's ranges before
11855          traversing its children, simply overriding whatever you find
11856          there.  But since we don't even decide whether to create a
11857          block until after we've traversed its children, that's hard
11858          to do.  */
11859       dwarf2_record_block_ranges (die, block, baseaddr, cu);
11860     }
11861   local_symbols = newobj->locals;
11862   local_using_directives = newobj->local_using_directives;
11863 }
11864
11865 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
11866
11867 static void
11868 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
11869 {
11870   struct objfile *objfile = cu->objfile;
11871   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11872   CORE_ADDR pc, baseaddr;
11873   struct attribute *attr;
11874   struct call_site *call_site, call_site_local;
11875   void **slot;
11876   int nparams;
11877   struct die_info *child_die;
11878
11879   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11880
11881   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
11882   if (attr == NULL)
11883     {
11884       /* This was a pre-DWARF-5 GNU extension alias
11885          for DW_AT_call_return_pc.  */
11886       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
11887     }
11888   if (!attr)
11889     {
11890       complaint (&symfile_complaints,
11891                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
11892                    "DIE 0x%x [in module %s]"),
11893                  to_underlying (die->sect_off), objfile_name (objfile));
11894       return;
11895     }
11896   pc = attr_value_as_address (attr) + baseaddr;
11897   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
11898
11899   if (cu->call_site_htab == NULL)
11900     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
11901                                                NULL, &objfile->objfile_obstack,
11902                                                hashtab_obstack_allocate, NULL);
11903   call_site_local.pc = pc;
11904   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
11905   if (*slot != NULL)
11906     {
11907       complaint (&symfile_complaints,
11908                  _("Duplicate PC %s for DW_TAG_call_site "
11909                    "DIE 0x%x [in module %s]"),
11910                  paddress (gdbarch, pc), to_underlying (die->sect_off),
11911                  objfile_name (objfile));
11912       return;
11913     }
11914
11915   /* Count parameters at the caller.  */
11916
11917   nparams = 0;
11918   for (child_die = die->child; child_die && child_die->tag;
11919        child_die = sibling_die (child_die))
11920     {
11921       if (child_die->tag != DW_TAG_call_site_parameter
11922           && child_die->tag != DW_TAG_GNU_call_site_parameter)
11923         {
11924           complaint (&symfile_complaints,
11925                      _("Tag %d is not DW_TAG_call_site_parameter in "
11926                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
11927                      child_die->tag, to_underlying (child_die->sect_off),
11928                      objfile_name (objfile));
11929           continue;
11930         }
11931
11932       nparams++;
11933     }
11934
11935   call_site
11936     = ((struct call_site *)
11937        obstack_alloc (&objfile->objfile_obstack,
11938                       sizeof (*call_site)
11939                       + (sizeof (*call_site->parameter) * (nparams - 1))));
11940   *slot = call_site;
11941   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
11942   call_site->pc = pc;
11943
11944   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
11945       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
11946     {
11947       struct die_info *func_die;
11948
11949       /* Skip also over DW_TAG_inlined_subroutine.  */
11950       for (func_die = die->parent;
11951            func_die && func_die->tag != DW_TAG_subprogram
11952            && func_die->tag != DW_TAG_subroutine_type;
11953            func_die = func_die->parent);
11954
11955       /* DW_AT_call_all_calls is a superset
11956          of DW_AT_call_all_tail_calls.  */
11957       if (func_die
11958           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
11959           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
11960           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
11961           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
11962         {
11963           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
11964              not complete.  But keep CALL_SITE for look ups via call_site_htab,
11965              both the initial caller containing the real return address PC and
11966              the final callee containing the current PC of a chain of tail
11967              calls do not need to have the tail call list complete.  But any
11968              function candidate for a virtual tail call frame searched via
11969              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
11970              determined unambiguously.  */
11971         }
11972       else
11973         {
11974           struct type *func_type = NULL;
11975
11976           if (func_die)
11977             func_type = get_die_type (func_die, cu);
11978           if (func_type != NULL)
11979             {
11980               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
11981
11982               /* Enlist this call site to the function.  */
11983               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
11984               TYPE_TAIL_CALL_LIST (func_type) = call_site;
11985             }
11986           else
11987             complaint (&symfile_complaints,
11988                        _("Cannot find function owning DW_TAG_call_site "
11989                          "DIE 0x%x [in module %s]"),
11990                        to_underlying (die->sect_off), objfile_name (objfile));
11991         }
11992     }
11993
11994   attr = dwarf2_attr (die, DW_AT_call_target, cu);
11995   if (attr == NULL)
11996     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
11997   if (attr == NULL)
11998     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
11999   if (attr == NULL)
12000     {
12001       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12002       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12003     }
12004   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12005   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12006     /* Keep NULL DWARF_BLOCK.  */;
12007   else if (attr_form_is_block (attr))
12008     {
12009       struct dwarf2_locexpr_baton *dlbaton;
12010
12011       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12012       dlbaton->data = DW_BLOCK (attr)->data;
12013       dlbaton->size = DW_BLOCK (attr)->size;
12014       dlbaton->per_cu = cu->per_cu;
12015
12016       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12017     }
12018   else if (attr_form_is_ref (attr))
12019     {
12020       struct dwarf2_cu *target_cu = cu;
12021       struct die_info *target_die;
12022
12023       target_die = follow_die_ref (die, attr, &target_cu);
12024       gdb_assert (target_cu->objfile == objfile);
12025       if (die_is_declaration (target_die, target_cu))
12026         {
12027           const char *target_physname;
12028
12029           /* Prefer the mangled name; otherwise compute the demangled one.  */
12030           target_physname = dw2_linkage_name (target_die, target_cu);
12031           if (target_physname == NULL)
12032             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12033           if (target_physname == NULL)
12034             complaint (&symfile_complaints,
12035                        _("DW_AT_call_target target DIE has invalid "
12036                          "physname, for referencing DIE 0x%x [in module %s]"),
12037                        to_underlying (die->sect_off), objfile_name (objfile));
12038           else
12039             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12040         }
12041       else
12042         {
12043           CORE_ADDR lowpc;
12044
12045           /* DW_AT_entry_pc should be preferred.  */
12046           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12047               <= PC_BOUNDS_INVALID)
12048             complaint (&symfile_complaints,
12049                        _("DW_AT_call_target target DIE has invalid "
12050                          "low pc, for referencing DIE 0x%x [in module %s]"),
12051                        to_underlying (die->sect_off), objfile_name (objfile));
12052           else
12053             {
12054               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12055               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12056             }
12057         }
12058     }
12059   else
12060     complaint (&symfile_complaints,
12061                _("DW_TAG_call_site DW_AT_call_target is neither "
12062                  "block nor reference, for DIE 0x%x [in module %s]"),
12063                to_underlying (die->sect_off), objfile_name (objfile));
12064
12065   call_site->per_cu = cu->per_cu;
12066
12067   for (child_die = die->child;
12068        child_die && child_die->tag;
12069        child_die = sibling_die (child_die))
12070     {
12071       struct call_site_parameter *parameter;
12072       struct attribute *loc, *origin;
12073
12074       if (child_die->tag != DW_TAG_call_site_parameter
12075           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12076         {
12077           /* Already printed the complaint above.  */
12078           continue;
12079         }
12080
12081       gdb_assert (call_site->parameter_count < nparams);
12082       parameter = &call_site->parameter[call_site->parameter_count];
12083
12084       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12085          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12086          register is contained in DW_AT_call_value.  */
12087
12088       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12089       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12090       if (origin == NULL)
12091         {
12092           /* This was a pre-DWARF-5 GNU extension alias
12093              for DW_AT_call_parameter.  */
12094           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12095         }
12096       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12097         {
12098           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12099
12100           sect_offset sect_off
12101             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12102           if (!offset_in_cu_p (&cu->header, sect_off))
12103             {
12104               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12105                  binding can be done only inside one CU.  Such referenced DIE
12106                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12107               complaint (&symfile_complaints,
12108                          _("DW_AT_call_parameter offset is not in CU for "
12109                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12110                          to_underlying (child_die->sect_off),
12111                          objfile_name (objfile));
12112               continue;
12113             }
12114           parameter->u.param_cu_off
12115             = (cu_offset) (sect_off - cu->header.sect_off);
12116         }
12117       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12118         {
12119           complaint (&symfile_complaints,
12120                      _("No DW_FORM_block* DW_AT_location for "
12121                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12122                      to_underlying (child_die->sect_off), objfile_name (objfile));
12123           continue;
12124         }
12125       else
12126         {
12127           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12128             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12129           if (parameter->u.dwarf_reg != -1)
12130             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12131           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12132                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12133                                              &parameter->u.fb_offset))
12134             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12135           else
12136             {
12137               complaint (&symfile_complaints,
12138                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12139                            "for DW_FORM_block* DW_AT_location is supported for "
12140                            "DW_TAG_call_site child DIE 0x%x "
12141                            "[in module %s]"),
12142                          to_underlying (child_die->sect_off),
12143                          objfile_name (objfile));
12144               continue;
12145             }
12146         }
12147
12148       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12149       if (attr == NULL)
12150         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12151       if (!attr_form_is_block (attr))
12152         {
12153           complaint (&symfile_complaints,
12154                      _("No DW_FORM_block* DW_AT_call_value for "
12155                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12156                      to_underlying (child_die->sect_off),
12157                      objfile_name (objfile));
12158           continue;
12159         }
12160       parameter->value = DW_BLOCK (attr)->data;
12161       parameter->value_size = DW_BLOCK (attr)->size;
12162
12163       /* Parameters are not pre-cleared by memset above.  */
12164       parameter->data_value = NULL;
12165       parameter->data_value_size = 0;
12166       call_site->parameter_count++;
12167
12168       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12169       if (attr == NULL)
12170         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12171       if (attr)
12172         {
12173           if (!attr_form_is_block (attr))
12174             complaint (&symfile_complaints,
12175                        _("No DW_FORM_block* DW_AT_call_data_value for "
12176                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12177                        to_underlying (child_die->sect_off),
12178                        objfile_name (objfile));
12179           else
12180             {
12181               parameter->data_value = DW_BLOCK (attr)->data;
12182               parameter->data_value_size = DW_BLOCK (attr)->size;
12183             }
12184         }
12185     }
12186 }
12187
12188 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12189    reading .debug_rnglists.
12190    Callback's type should be:
12191     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12192    Return true if the attributes are present and valid, otherwise,
12193    return false.  */
12194
12195 template <typename Callback>
12196 static bool
12197 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12198                          Callback &&callback)
12199 {
12200   struct objfile *objfile = cu->objfile;
12201   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12202   struct comp_unit_head *cu_header = &cu->header;
12203   bfd *obfd = objfile->obfd;
12204   unsigned int addr_size = cu_header->addr_size;
12205   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12206   /* Base address selection entry.  */
12207   CORE_ADDR base;
12208   int found_base;
12209   unsigned int dummy;
12210   const gdb_byte *buffer;
12211   CORE_ADDR low = 0;
12212   CORE_ADDR high = 0;
12213   CORE_ADDR baseaddr;
12214   bool overflow = false;
12215
12216   found_base = cu->base_known;
12217   base = cu->base_address;
12218
12219   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12220   if (offset >= dwarf2_per_objfile->rnglists.size)
12221     {
12222       complaint (&symfile_complaints,
12223                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12224                  offset);
12225       return false;
12226     }
12227   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12228
12229   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12230
12231   while (1)
12232     {
12233       /* Initialize it due to a false compiler warning.  */
12234       CORE_ADDR range_beginning = 0, range_end = 0;
12235       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12236                                  + dwarf2_per_objfile->rnglists.size);
12237       unsigned int bytes_read;
12238
12239       if (buffer == buf_end)
12240         {
12241           overflow = true;
12242           break;
12243         }
12244       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12245       switch (rlet)
12246         {
12247         case DW_RLE_end_of_list:
12248           break;
12249         case DW_RLE_base_address:
12250           if (buffer + cu->header.addr_size > buf_end)
12251             {
12252               overflow = true;
12253               break;
12254             }
12255           base = read_address (obfd, buffer, cu, &bytes_read);
12256           found_base = 1;
12257           buffer += bytes_read;
12258           break;
12259         case DW_RLE_start_length:
12260           if (buffer + cu->header.addr_size > buf_end)
12261             {
12262               overflow = true;
12263               break;
12264             }
12265           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12266           buffer += bytes_read;
12267           range_end = (range_beginning
12268                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12269           buffer += bytes_read;
12270           if (buffer > buf_end)
12271             {
12272               overflow = true;
12273               break;
12274             }
12275           break;
12276         case DW_RLE_offset_pair:
12277           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12278           buffer += bytes_read;
12279           if (buffer > buf_end)
12280             {
12281               overflow = true;
12282               break;
12283             }
12284           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12285           buffer += bytes_read;
12286           if (buffer > buf_end)
12287             {
12288               overflow = true;
12289               break;
12290             }
12291           break;
12292         case DW_RLE_start_end:
12293           if (buffer + 2 * cu->header.addr_size > buf_end)
12294             {
12295               overflow = true;
12296               break;
12297             }
12298           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12299           buffer += bytes_read;
12300           range_end = read_address (obfd, buffer, cu, &bytes_read);
12301           buffer += bytes_read;
12302           break;
12303         default:
12304           complaint (&symfile_complaints,
12305                      _("Invalid .debug_rnglists data (no base address)"));
12306           return false;
12307         }
12308       if (rlet == DW_RLE_end_of_list || overflow)
12309         break;
12310       if (rlet == DW_RLE_base_address)
12311         continue;
12312
12313       if (!found_base)
12314         {
12315           /* We have no valid base address for the ranges
12316              data.  */
12317           complaint (&symfile_complaints,
12318                      _("Invalid .debug_rnglists data (no base address)"));
12319           return false;
12320         }
12321
12322       if (range_beginning > range_end)
12323         {
12324           /* Inverted range entries are invalid.  */
12325           complaint (&symfile_complaints,
12326                      _("Invalid .debug_rnglists data (inverted range)"));
12327           return false;
12328         }
12329
12330       /* Empty range entries have no effect.  */
12331       if (range_beginning == range_end)
12332         continue;
12333
12334       range_beginning += base;
12335       range_end += base;
12336
12337       /* A not-uncommon case of bad debug info.
12338          Don't pollute the addrmap with bad data.  */
12339       if (range_beginning + baseaddr == 0
12340           && !dwarf2_per_objfile->has_section_at_zero)
12341         {
12342           complaint (&symfile_complaints,
12343                      _(".debug_rnglists entry has start address of zero"
12344                        " [in module %s]"), objfile_name (objfile));
12345           continue;
12346         }
12347
12348       callback (range_beginning, range_end);
12349     }
12350
12351   if (overflow)
12352     {
12353       complaint (&symfile_complaints,
12354                  _("Offset %d is not terminated "
12355                    "for DW_AT_ranges attribute"),
12356                  offset);
12357       return false;
12358     }
12359
12360   return true;
12361 }
12362
12363 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12364    Callback's type should be:
12365     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12366    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12367
12368 template <typename Callback>
12369 static int
12370 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12371                        Callback &&callback)
12372 {
12373   struct objfile *objfile = cu->objfile;
12374   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12375   struct comp_unit_head *cu_header = &cu->header;
12376   bfd *obfd = objfile->obfd;
12377   unsigned int addr_size = cu_header->addr_size;
12378   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12379   /* Base address selection entry.  */
12380   CORE_ADDR base;
12381   int found_base;
12382   unsigned int dummy;
12383   const gdb_byte *buffer;
12384   CORE_ADDR baseaddr;
12385
12386   if (cu_header->version >= 5)
12387     return dwarf2_rnglists_process (offset, cu, callback);
12388
12389   found_base = cu->base_known;
12390   base = cu->base_address;
12391
12392   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12393   if (offset >= dwarf2_per_objfile->ranges.size)
12394     {
12395       complaint (&symfile_complaints,
12396                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12397                  offset);
12398       return 0;
12399     }
12400   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12401
12402   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12403
12404   while (1)
12405     {
12406       CORE_ADDR range_beginning, range_end;
12407
12408       range_beginning = read_address (obfd, buffer, cu, &dummy);
12409       buffer += addr_size;
12410       range_end = read_address (obfd, buffer, cu, &dummy);
12411       buffer += addr_size;
12412       offset += 2 * addr_size;
12413
12414       /* An end of list marker is a pair of zero addresses.  */
12415       if (range_beginning == 0 && range_end == 0)
12416         /* Found the end of list entry.  */
12417         break;
12418
12419       /* Each base address selection entry is a pair of 2 values.
12420          The first is the largest possible address, the second is
12421          the base address.  Check for a base address here.  */
12422       if ((range_beginning & mask) == mask)
12423         {
12424           /* If we found the largest possible address, then we already
12425              have the base address in range_end.  */
12426           base = range_end;
12427           found_base = 1;
12428           continue;
12429         }
12430
12431       if (!found_base)
12432         {
12433           /* We have no valid base address for the ranges
12434              data.  */
12435           complaint (&symfile_complaints,
12436                      _("Invalid .debug_ranges data (no base address)"));
12437           return 0;
12438         }
12439
12440       if (range_beginning > range_end)
12441         {
12442           /* Inverted range entries are invalid.  */
12443           complaint (&symfile_complaints,
12444                      _("Invalid .debug_ranges data (inverted range)"));
12445           return 0;
12446         }
12447
12448       /* Empty range entries have no effect.  */
12449       if (range_beginning == range_end)
12450         continue;
12451
12452       range_beginning += base;
12453       range_end += base;
12454
12455       /* A not-uncommon case of bad debug info.
12456          Don't pollute the addrmap with bad data.  */
12457       if (range_beginning + baseaddr == 0
12458           && !dwarf2_per_objfile->has_section_at_zero)
12459         {
12460           complaint (&symfile_complaints,
12461                      _(".debug_ranges entry has start address of zero"
12462                        " [in module %s]"), objfile_name (objfile));
12463           continue;
12464         }
12465
12466       callback (range_beginning, range_end);
12467     }
12468
12469   return 1;
12470 }
12471
12472 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12473    Return 1 if the attributes are present and valid, otherwise, return 0.
12474    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12475
12476 static int
12477 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12478                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12479                     struct partial_symtab *ranges_pst)
12480 {
12481   struct objfile *objfile = cu->objfile;
12482   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12483   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12484                                        SECT_OFF_TEXT (objfile));
12485   int low_set = 0;
12486   CORE_ADDR low = 0;
12487   CORE_ADDR high = 0;
12488   int retval;
12489
12490   retval = dwarf2_ranges_process (offset, cu,
12491     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12492     {
12493       if (ranges_pst != NULL)
12494         {
12495           CORE_ADDR lowpc;
12496           CORE_ADDR highpc;
12497
12498           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12499                                               range_beginning + baseaddr);
12500           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12501                                                range_end + baseaddr);
12502           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12503                              ranges_pst);
12504         }
12505
12506       /* FIXME: This is recording everything as a low-high
12507          segment of consecutive addresses.  We should have a
12508          data structure for discontiguous block ranges
12509          instead.  */
12510       if (! low_set)
12511         {
12512           low = range_beginning;
12513           high = range_end;
12514           low_set = 1;
12515         }
12516       else
12517         {
12518           if (range_beginning < low)
12519             low = range_beginning;
12520           if (range_end > high)
12521             high = range_end;
12522         }
12523     });
12524   if (!retval)
12525     return 0;
12526
12527   if (! low_set)
12528     /* If the first entry is an end-of-list marker, the range
12529        describes an empty scope, i.e. no instructions.  */
12530     return 0;
12531
12532   if (low_return)
12533     *low_return = low;
12534   if (high_return)
12535     *high_return = high;
12536   return 1;
12537 }
12538
12539 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12540    definition for the return value.  *LOWPC and *HIGHPC are set iff
12541    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12542
12543 static enum pc_bounds_kind
12544 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12545                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12546                       struct partial_symtab *pst)
12547 {
12548   struct attribute *attr;
12549   struct attribute *attr_high;
12550   CORE_ADDR low = 0;
12551   CORE_ADDR high = 0;
12552   enum pc_bounds_kind ret;
12553
12554   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12555   if (attr_high)
12556     {
12557       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12558       if (attr)
12559         {
12560           low = attr_value_as_address (attr);
12561           high = attr_value_as_address (attr_high);
12562           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12563             high += low;
12564         }
12565       else
12566         /* Found high w/o low attribute.  */
12567         return PC_BOUNDS_INVALID;
12568
12569       /* Found consecutive range of addresses.  */
12570       ret = PC_BOUNDS_HIGH_LOW;
12571     }
12572   else
12573     {
12574       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12575       if (attr != NULL)
12576         {
12577           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12578              We take advantage of the fact that DW_AT_ranges does not appear
12579              in DW_TAG_compile_unit of DWO files.  */
12580           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12581           unsigned int ranges_offset = (DW_UNSND (attr)
12582                                         + (need_ranges_base
12583                                            ? cu->ranges_base
12584                                            : 0));
12585
12586           /* Value of the DW_AT_ranges attribute is the offset in the
12587              .debug_ranges section.  */
12588           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12589             return PC_BOUNDS_INVALID;
12590           /* Found discontinuous range of addresses.  */
12591           ret = PC_BOUNDS_RANGES;
12592         }
12593       else
12594         return PC_BOUNDS_NOT_PRESENT;
12595     }
12596
12597   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12598   if (high <= low)
12599     return PC_BOUNDS_INVALID;
12600
12601   /* When using the GNU linker, .gnu.linkonce. sections are used to
12602      eliminate duplicate copies of functions and vtables and such.
12603      The linker will arbitrarily choose one and discard the others.
12604      The AT_*_pc values for such functions refer to local labels in
12605      these sections.  If the section from that file was discarded, the
12606      labels are not in the output, so the relocs get a value of 0.
12607      If this is a discarded function, mark the pc bounds as invalid,
12608      so that GDB will ignore it.  */
12609   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12610     return PC_BOUNDS_INVALID;
12611
12612   *lowpc = low;
12613   if (highpc)
12614     *highpc = high;
12615   return ret;
12616 }
12617
12618 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12619    its low and high PC addresses.  Do nothing if these addresses could not
12620    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12621    and HIGHPC to the high address if greater than HIGHPC.  */
12622
12623 static void
12624 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12625                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12626                                  struct dwarf2_cu *cu)
12627 {
12628   CORE_ADDR low, high;
12629   struct die_info *child = die->child;
12630
12631   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12632     {
12633       *lowpc = std::min (*lowpc, low);
12634       *highpc = std::max (*highpc, high);
12635     }
12636
12637   /* If the language does not allow nested subprograms (either inside
12638      subprograms or lexical blocks), we're done.  */
12639   if (cu->language != language_ada)
12640     return;
12641
12642   /* Check all the children of the given DIE.  If it contains nested
12643      subprograms, then check their pc bounds.  Likewise, we need to
12644      check lexical blocks as well, as they may also contain subprogram
12645      definitions.  */
12646   while (child && child->tag)
12647     {
12648       if (child->tag == DW_TAG_subprogram
12649           || child->tag == DW_TAG_lexical_block)
12650         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12651       child = sibling_die (child);
12652     }
12653 }
12654
12655 /* Get the low and high pc's represented by the scope DIE, and store
12656    them in *LOWPC and *HIGHPC.  If the correct values can't be
12657    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12658
12659 static void
12660 get_scope_pc_bounds (struct die_info *die,
12661                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12662                      struct dwarf2_cu *cu)
12663 {
12664   CORE_ADDR best_low = (CORE_ADDR) -1;
12665   CORE_ADDR best_high = (CORE_ADDR) 0;
12666   CORE_ADDR current_low, current_high;
12667
12668   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12669       >= PC_BOUNDS_RANGES)
12670     {
12671       best_low = current_low;
12672       best_high = current_high;
12673     }
12674   else
12675     {
12676       struct die_info *child = die->child;
12677
12678       while (child && child->tag)
12679         {
12680           switch (child->tag) {
12681           case DW_TAG_subprogram:
12682             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12683             break;
12684           case DW_TAG_namespace:
12685           case DW_TAG_module:
12686             /* FIXME: carlton/2004-01-16: Should we do this for
12687                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12688                that current GCC's always emit the DIEs corresponding
12689                to definitions of methods of classes as children of a
12690                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12691                the DIEs giving the declarations, which could be
12692                anywhere).  But I don't see any reason why the
12693                standards says that they have to be there.  */
12694             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12695
12696             if (current_low != ((CORE_ADDR) -1))
12697               {
12698                 best_low = std::min (best_low, current_low);
12699                 best_high = std::max (best_high, current_high);
12700               }
12701             break;
12702           default:
12703             /* Ignore.  */
12704             break;
12705           }
12706
12707           child = sibling_die (child);
12708         }
12709     }
12710
12711   *lowpc = best_low;
12712   *highpc = best_high;
12713 }
12714
12715 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
12716    in DIE.  */
12717
12718 static void
12719 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
12720                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
12721 {
12722   struct objfile *objfile = cu->objfile;
12723   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12724   struct attribute *attr;
12725   struct attribute *attr_high;
12726
12727   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12728   if (attr_high)
12729     {
12730       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12731       if (attr)
12732         {
12733           CORE_ADDR low = attr_value_as_address (attr);
12734           CORE_ADDR high = attr_value_as_address (attr_high);
12735
12736           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12737             high += low;
12738
12739           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
12740           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
12741           record_block_range (block, low, high - 1);
12742         }
12743     }
12744
12745   attr = dwarf2_attr (die, DW_AT_ranges, cu);
12746   if (attr)
12747     {
12748       bfd *obfd = objfile->obfd;
12749       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12750          We take advantage of the fact that DW_AT_ranges does not appear
12751          in DW_TAG_compile_unit of DWO files.  */
12752       int need_ranges_base = die->tag != DW_TAG_compile_unit;
12753
12754       /* The value of the DW_AT_ranges attribute is the offset of the
12755          address range list in the .debug_ranges section.  */
12756       unsigned long offset = (DW_UNSND (attr)
12757                               + (need_ranges_base ? cu->ranges_base : 0));
12758       const gdb_byte *buffer;
12759
12760       /* For some target architectures, but not others, the
12761          read_address function sign-extends the addresses it returns.
12762          To recognize base address selection entries, we need a
12763          mask.  */
12764       unsigned int addr_size = cu->header.addr_size;
12765       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12766
12767       /* The base address, to which the next pair is relative.  Note
12768          that this 'base' is a DWARF concept: most entries in a range
12769          list are relative, to reduce the number of relocs against the
12770          debugging information.  This is separate from this function's
12771          'baseaddr' argument, which GDB uses to relocate debugging
12772          information from a shared library based on the address at
12773          which the library was loaded.  */
12774       CORE_ADDR base = cu->base_address;
12775       int base_known = cu->base_known;
12776
12777       dwarf2_ranges_process (offset, cu,
12778         [&] (CORE_ADDR start, CORE_ADDR end)
12779         {
12780           start += baseaddr;
12781           end += baseaddr;
12782           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
12783           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
12784           record_block_range (block, start, end - 1);
12785         });
12786     }
12787 }
12788
12789 /* Check whether the producer field indicates either of GCC < 4.6, or the
12790    Intel C/C++ compiler, and cache the result in CU.  */
12791
12792 static void
12793 check_producer (struct dwarf2_cu *cu)
12794 {
12795   int major, minor;
12796
12797   if (cu->producer == NULL)
12798     {
12799       /* For unknown compilers expect their behavior is DWARF version
12800          compliant.
12801
12802          GCC started to support .debug_types sections by -gdwarf-4 since
12803          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
12804          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
12805          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
12806          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
12807     }
12808   else if (producer_is_gcc (cu->producer, &major, &minor))
12809     {
12810       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
12811       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
12812     }
12813   else if (producer_is_icc (cu->producer, &major, &minor))
12814     cu->producer_is_icc_lt_14 = major < 14;
12815   else
12816     {
12817       /* For other non-GCC compilers, expect their behavior is DWARF version
12818          compliant.  */
12819     }
12820
12821   cu->checked_producer = 1;
12822 }
12823
12824 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
12825    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
12826    during 4.6.0 experimental.  */
12827
12828 static int
12829 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
12830 {
12831   if (!cu->checked_producer)
12832     check_producer (cu);
12833
12834   return cu->producer_is_gxx_lt_4_6;
12835 }
12836
12837 /* Return the default accessibility type if it is not overriden by
12838    DW_AT_accessibility.  */
12839
12840 static enum dwarf_access_attribute
12841 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
12842 {
12843   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
12844     {
12845       /* The default DWARF 2 accessibility for members is public, the default
12846          accessibility for inheritance is private.  */
12847
12848       if (die->tag != DW_TAG_inheritance)
12849         return DW_ACCESS_public;
12850       else
12851         return DW_ACCESS_private;
12852     }
12853   else
12854     {
12855       /* DWARF 3+ defines the default accessibility a different way.  The same
12856          rules apply now for DW_TAG_inheritance as for the members and it only
12857          depends on the container kind.  */
12858
12859       if (die->parent->tag == DW_TAG_class_type)
12860         return DW_ACCESS_private;
12861       else
12862         return DW_ACCESS_public;
12863     }
12864 }
12865
12866 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
12867    offset.  If the attribute was not found return 0, otherwise return
12868    1.  If it was found but could not properly be handled, set *OFFSET
12869    to 0.  */
12870
12871 static int
12872 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
12873                              LONGEST *offset)
12874 {
12875   struct attribute *attr;
12876
12877   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
12878   if (attr != NULL)
12879     {
12880       *offset = 0;
12881
12882       /* Note that we do not check for a section offset first here.
12883          This is because DW_AT_data_member_location is new in DWARF 4,
12884          so if we see it, we can assume that a constant form is really
12885          a constant and not a section offset.  */
12886       if (attr_form_is_constant (attr))
12887         *offset = dwarf2_get_attr_constant_value (attr, 0);
12888       else if (attr_form_is_section_offset (attr))
12889         dwarf2_complex_location_expr_complaint ();
12890       else if (attr_form_is_block (attr))
12891         *offset = decode_locdesc (DW_BLOCK (attr), cu);
12892       else
12893         dwarf2_complex_location_expr_complaint ();
12894
12895       return 1;
12896     }
12897
12898   return 0;
12899 }
12900
12901 /* Add an aggregate field to the field list.  */
12902
12903 static void
12904 dwarf2_add_field (struct field_info *fip, struct die_info *die,
12905                   struct dwarf2_cu *cu)
12906 {
12907   struct objfile *objfile = cu->objfile;
12908   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12909   struct nextfield *new_field;
12910   struct attribute *attr;
12911   struct field *fp;
12912   const char *fieldname = "";
12913
12914   /* Allocate a new field list entry and link it in.  */
12915   new_field = XNEW (struct nextfield);
12916   make_cleanup (xfree, new_field);
12917   memset (new_field, 0, sizeof (struct nextfield));
12918
12919   if (die->tag == DW_TAG_inheritance)
12920     {
12921       new_field->next = fip->baseclasses;
12922       fip->baseclasses = new_field;
12923     }
12924   else
12925     {
12926       new_field->next = fip->fields;
12927       fip->fields = new_field;
12928     }
12929   fip->nfields++;
12930
12931   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
12932   if (attr)
12933     new_field->accessibility = DW_UNSND (attr);
12934   else
12935     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
12936   if (new_field->accessibility != DW_ACCESS_public)
12937     fip->non_public_fields = 1;
12938
12939   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
12940   if (attr)
12941     new_field->virtuality = DW_UNSND (attr);
12942   else
12943     new_field->virtuality = DW_VIRTUALITY_none;
12944
12945   fp = &new_field->field;
12946
12947   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
12948     {
12949       LONGEST offset;
12950
12951       /* Data member other than a C++ static data member.  */
12952
12953       /* Get type of field.  */
12954       fp->type = die_type (die, cu);
12955
12956       SET_FIELD_BITPOS (*fp, 0);
12957
12958       /* Get bit size of field (zero if none).  */
12959       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
12960       if (attr)
12961         {
12962           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
12963         }
12964       else
12965         {
12966           FIELD_BITSIZE (*fp) = 0;
12967         }
12968
12969       /* Get bit offset of field.  */
12970       if (handle_data_member_location (die, cu, &offset))
12971         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
12972       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
12973       if (attr)
12974         {
12975           if (gdbarch_bits_big_endian (gdbarch))
12976             {
12977               /* For big endian bits, the DW_AT_bit_offset gives the
12978                  additional bit offset from the MSB of the containing
12979                  anonymous object to the MSB of the field.  We don't
12980                  have to do anything special since we don't need to
12981                  know the size of the anonymous object.  */
12982               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
12983             }
12984           else
12985             {
12986               /* For little endian bits, compute the bit offset to the
12987                  MSB of the anonymous object, subtract off the number of
12988                  bits from the MSB of the field to the MSB of the
12989                  object, and then subtract off the number of bits of
12990                  the field itself.  The result is the bit offset of
12991                  the LSB of the field.  */
12992               int anonymous_size;
12993               int bit_offset = DW_UNSND (attr);
12994
12995               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
12996               if (attr)
12997                 {
12998                   /* The size of the anonymous object containing
12999                      the bit field is explicit, so use the
13000                      indicated size (in bytes).  */
13001                   anonymous_size = DW_UNSND (attr);
13002                 }
13003               else
13004                 {
13005                   /* The size of the anonymous object containing
13006                      the bit field must be inferred from the type
13007                      attribute of the data member containing the
13008                      bit field.  */
13009                   anonymous_size = TYPE_LENGTH (fp->type);
13010                 }
13011               SET_FIELD_BITPOS (*fp,
13012                                 (FIELD_BITPOS (*fp)
13013                                  + anonymous_size * bits_per_byte
13014                                  - bit_offset - FIELD_BITSIZE (*fp)));
13015             }
13016         }
13017       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13018       if (attr != NULL)
13019         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13020                                 + dwarf2_get_attr_constant_value (attr, 0)));
13021
13022       /* Get name of field.  */
13023       fieldname = dwarf2_name (die, cu);
13024       if (fieldname == NULL)
13025         fieldname = "";
13026
13027       /* The name is already allocated along with this objfile, so we don't
13028          need to duplicate it for the type.  */
13029       fp->name = fieldname;
13030
13031       /* Change accessibility for artificial fields (e.g. virtual table
13032          pointer or virtual base class pointer) to private.  */
13033       if (dwarf2_attr (die, DW_AT_artificial, cu))
13034         {
13035           FIELD_ARTIFICIAL (*fp) = 1;
13036           new_field->accessibility = DW_ACCESS_private;
13037           fip->non_public_fields = 1;
13038         }
13039     }
13040   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13041     {
13042       /* C++ static member.  */
13043
13044       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13045          is a declaration, but all versions of G++ as of this writing
13046          (so through at least 3.2.1) incorrectly generate
13047          DW_TAG_variable tags.  */
13048
13049       const char *physname;
13050
13051       /* Get name of field.  */
13052       fieldname = dwarf2_name (die, cu);
13053       if (fieldname == NULL)
13054         return;
13055
13056       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13057       if (attr
13058           /* Only create a symbol if this is an external value.
13059              new_symbol checks this and puts the value in the global symbol
13060              table, which we want.  If it is not external, new_symbol
13061              will try to put the value in cu->list_in_scope which is wrong.  */
13062           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13063         {
13064           /* A static const member, not much different than an enum as far as
13065              we're concerned, except that we can support more types.  */
13066           new_symbol (die, NULL, cu);
13067         }
13068
13069       /* Get physical name.  */
13070       physname = dwarf2_physname (fieldname, die, cu);
13071
13072       /* The name is already allocated along with this objfile, so we don't
13073          need to duplicate it for the type.  */
13074       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13075       FIELD_TYPE (*fp) = die_type (die, cu);
13076       FIELD_NAME (*fp) = fieldname;
13077     }
13078   else if (die->tag == DW_TAG_inheritance)
13079     {
13080       LONGEST offset;
13081
13082       /* C++ base class field.  */
13083       if (handle_data_member_location (die, cu, &offset))
13084         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13085       FIELD_BITSIZE (*fp) = 0;
13086       FIELD_TYPE (*fp) = die_type (die, cu);
13087       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13088       fip->nbaseclasses++;
13089     }
13090 }
13091
13092 /* Add a typedef defined in the scope of the FIP's class.  */
13093
13094 static void
13095 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13096                     struct dwarf2_cu *cu)
13097 {
13098   struct typedef_field_list *new_field;
13099   struct typedef_field *fp;
13100
13101   /* Allocate a new field list entry and link it in.  */
13102   new_field = XCNEW (struct typedef_field_list);
13103   make_cleanup (xfree, new_field);
13104
13105   gdb_assert (die->tag == DW_TAG_typedef);
13106
13107   fp = &new_field->field;
13108
13109   /* Get name of field.  */
13110   fp->name = dwarf2_name (die, cu);
13111   if (fp->name == NULL)
13112     return;
13113
13114   fp->type = read_type_die (die, cu);
13115
13116   new_field->next = fip->typedef_field_list;
13117   fip->typedef_field_list = new_field;
13118   fip->typedef_field_list_count++;
13119 }
13120
13121 /* Create the vector of fields, and attach it to the type.  */
13122
13123 static void
13124 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13125                               struct dwarf2_cu *cu)
13126 {
13127   int nfields = fip->nfields;
13128
13129   /* Record the field count, allocate space for the array of fields,
13130      and create blank accessibility bitfields if necessary.  */
13131   TYPE_NFIELDS (type) = nfields;
13132   TYPE_FIELDS (type) = (struct field *)
13133     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13134   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13135
13136   if (fip->non_public_fields && cu->language != language_ada)
13137     {
13138       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13139
13140       TYPE_FIELD_PRIVATE_BITS (type) =
13141         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13142       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13143
13144       TYPE_FIELD_PROTECTED_BITS (type) =
13145         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13146       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13147
13148       TYPE_FIELD_IGNORE_BITS (type) =
13149         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13150       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13151     }
13152
13153   /* If the type has baseclasses, allocate and clear a bit vector for
13154      TYPE_FIELD_VIRTUAL_BITS.  */
13155   if (fip->nbaseclasses && cu->language != language_ada)
13156     {
13157       int num_bytes = B_BYTES (fip->nbaseclasses);
13158       unsigned char *pointer;
13159
13160       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13161       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13162       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13163       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13164       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13165     }
13166
13167   /* Copy the saved-up fields into the field vector.  Start from the head of
13168      the list, adding to the tail of the field array, so that they end up in
13169      the same order in the array in which they were added to the list.  */
13170   while (nfields-- > 0)
13171     {
13172       struct nextfield *fieldp;
13173
13174       if (fip->fields)
13175         {
13176           fieldp = fip->fields;
13177           fip->fields = fieldp->next;
13178         }
13179       else
13180         {
13181           fieldp = fip->baseclasses;
13182           fip->baseclasses = fieldp->next;
13183         }
13184
13185       TYPE_FIELD (type, nfields) = fieldp->field;
13186       switch (fieldp->accessibility)
13187         {
13188         case DW_ACCESS_private:
13189           if (cu->language != language_ada)
13190             SET_TYPE_FIELD_PRIVATE (type, nfields);
13191           break;
13192
13193         case DW_ACCESS_protected:
13194           if (cu->language != language_ada)
13195             SET_TYPE_FIELD_PROTECTED (type, nfields);
13196           break;
13197
13198         case DW_ACCESS_public:
13199           break;
13200
13201         default:
13202           /* Unknown accessibility.  Complain and treat it as public.  */
13203           {
13204             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13205                        fieldp->accessibility);
13206           }
13207           break;
13208         }
13209       if (nfields < fip->nbaseclasses)
13210         {
13211           switch (fieldp->virtuality)
13212             {
13213             case DW_VIRTUALITY_virtual:
13214             case DW_VIRTUALITY_pure_virtual:
13215               if (cu->language == language_ada)
13216                 error (_("unexpected virtuality in component of Ada type"));
13217               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13218               break;
13219             }
13220         }
13221     }
13222 }
13223
13224 /* Return true if this member function is a constructor, false
13225    otherwise.  */
13226
13227 static int
13228 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13229 {
13230   const char *fieldname;
13231   const char *type_name;
13232   int len;
13233
13234   if (die->parent == NULL)
13235     return 0;
13236
13237   if (die->parent->tag != DW_TAG_structure_type
13238       && die->parent->tag != DW_TAG_union_type
13239       && die->parent->tag != DW_TAG_class_type)
13240     return 0;
13241
13242   fieldname = dwarf2_name (die, cu);
13243   type_name = dwarf2_name (die->parent, cu);
13244   if (fieldname == NULL || type_name == NULL)
13245     return 0;
13246
13247   len = strlen (fieldname);
13248   return (strncmp (fieldname, type_name, len) == 0
13249           && (type_name[len] == '\0' || type_name[len] == '<'));
13250 }
13251
13252 /* Add a member function to the proper fieldlist.  */
13253
13254 static void
13255 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13256                       struct type *type, struct dwarf2_cu *cu)
13257 {
13258   struct objfile *objfile = cu->objfile;
13259   struct attribute *attr;
13260   struct fnfieldlist *flp;
13261   int i;
13262   struct fn_field *fnp;
13263   const char *fieldname;
13264   struct nextfnfield *new_fnfield;
13265   struct type *this_type;
13266   enum dwarf_access_attribute accessibility;
13267
13268   if (cu->language == language_ada)
13269     error (_("unexpected member function in Ada type"));
13270
13271   /* Get name of member function.  */
13272   fieldname = dwarf2_name (die, cu);
13273   if (fieldname == NULL)
13274     return;
13275
13276   /* Look up member function name in fieldlist.  */
13277   for (i = 0; i < fip->nfnfields; i++)
13278     {
13279       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13280         break;
13281     }
13282
13283   /* Create new list element if necessary.  */
13284   if (i < fip->nfnfields)
13285     flp = &fip->fnfieldlists[i];
13286   else
13287     {
13288       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13289         {
13290           fip->fnfieldlists = (struct fnfieldlist *)
13291             xrealloc (fip->fnfieldlists,
13292                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13293                       * sizeof (struct fnfieldlist));
13294           if (fip->nfnfields == 0)
13295             make_cleanup (free_current_contents, &fip->fnfieldlists);
13296         }
13297       flp = &fip->fnfieldlists[fip->nfnfields];
13298       flp->name = fieldname;
13299       flp->length = 0;
13300       flp->head = NULL;
13301       i = fip->nfnfields++;
13302     }
13303
13304   /* Create a new member function field and chain it to the field list
13305      entry.  */
13306   new_fnfield = XNEW (struct nextfnfield);
13307   make_cleanup (xfree, new_fnfield);
13308   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13309   new_fnfield->next = flp->head;
13310   flp->head = new_fnfield;
13311   flp->length++;
13312
13313   /* Fill in the member function field info.  */
13314   fnp = &new_fnfield->fnfield;
13315
13316   /* Delay processing of the physname until later.  */
13317   if (cu->language == language_cplus)
13318     {
13319       add_to_method_list (type, i, flp->length - 1, fieldname,
13320                           die, cu);
13321     }
13322   else
13323     {
13324       const char *physname = dwarf2_physname (fieldname, die, cu);
13325       fnp->physname = physname ? physname : "";
13326     }
13327
13328   fnp->type = alloc_type (objfile);
13329   this_type = read_type_die (die, cu);
13330   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13331     {
13332       int nparams = TYPE_NFIELDS (this_type);
13333
13334       /* TYPE is the domain of this method, and THIS_TYPE is the type
13335            of the method itself (TYPE_CODE_METHOD).  */
13336       smash_to_method_type (fnp->type, type,
13337                             TYPE_TARGET_TYPE (this_type),
13338                             TYPE_FIELDS (this_type),
13339                             TYPE_NFIELDS (this_type),
13340                             TYPE_VARARGS (this_type));
13341
13342       /* Handle static member functions.
13343          Dwarf2 has no clean way to discern C++ static and non-static
13344          member functions.  G++ helps GDB by marking the first
13345          parameter for non-static member functions (which is the this
13346          pointer) as artificial.  We obtain this information from
13347          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13348       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13349         fnp->voffset = VOFFSET_STATIC;
13350     }
13351   else
13352     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13353                dwarf2_full_name (fieldname, die, cu));
13354
13355   /* Get fcontext from DW_AT_containing_type if present.  */
13356   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13357     fnp->fcontext = die_containing_type (die, cu);
13358
13359   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13360      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13361
13362   /* Get accessibility.  */
13363   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13364   if (attr)
13365     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13366   else
13367     accessibility = dwarf2_default_access_attribute (die, cu);
13368   switch (accessibility)
13369     {
13370     case DW_ACCESS_private:
13371       fnp->is_private = 1;
13372       break;
13373     case DW_ACCESS_protected:
13374       fnp->is_protected = 1;
13375       break;
13376     }
13377
13378   /* Check for artificial methods.  */
13379   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13380   if (attr && DW_UNSND (attr) != 0)
13381     fnp->is_artificial = 1;
13382
13383   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13384
13385   /* Get index in virtual function table if it is a virtual member
13386      function.  For older versions of GCC, this is an offset in the
13387      appropriate virtual table, as specified by DW_AT_containing_type.
13388      For everyone else, it is an expression to be evaluated relative
13389      to the object address.  */
13390
13391   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13392   if (attr)
13393     {
13394       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13395         {
13396           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13397             {
13398               /* Old-style GCC.  */
13399               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13400             }
13401           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13402                    || (DW_BLOCK (attr)->size > 1
13403                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13404                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13405             {
13406               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13407               if ((fnp->voffset % cu->header.addr_size) != 0)
13408                 dwarf2_complex_location_expr_complaint ();
13409               else
13410                 fnp->voffset /= cu->header.addr_size;
13411               fnp->voffset += 2;
13412             }
13413           else
13414             dwarf2_complex_location_expr_complaint ();
13415
13416           if (!fnp->fcontext)
13417             {
13418               /* If there is no `this' field and no DW_AT_containing_type,
13419                  we cannot actually find a base class context for the
13420                  vtable!  */
13421               if (TYPE_NFIELDS (this_type) == 0
13422                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13423                 {
13424                   complaint (&symfile_complaints,
13425                              _("cannot determine context for virtual member "
13426                                "function \"%s\" (offset %d)"),
13427                              fieldname, to_underlying (die->sect_off));
13428                 }
13429               else
13430                 {
13431                   fnp->fcontext
13432                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13433                 }
13434             }
13435         }
13436       else if (attr_form_is_section_offset (attr))
13437         {
13438           dwarf2_complex_location_expr_complaint ();
13439         }
13440       else
13441         {
13442           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13443                                                  fieldname);
13444         }
13445     }
13446   else
13447     {
13448       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13449       if (attr && DW_UNSND (attr))
13450         {
13451           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13452           complaint (&symfile_complaints,
13453                      _("Member function \"%s\" (offset %d) is virtual "
13454                        "but the vtable offset is not specified"),
13455                      fieldname, to_underlying (die->sect_off));
13456           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13457           TYPE_CPLUS_DYNAMIC (type) = 1;
13458         }
13459     }
13460 }
13461
13462 /* Create the vector of member function fields, and attach it to the type.  */
13463
13464 static void
13465 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13466                                  struct dwarf2_cu *cu)
13467 {
13468   struct fnfieldlist *flp;
13469   int i;
13470
13471   if (cu->language == language_ada)
13472     error (_("unexpected member functions in Ada type"));
13473
13474   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13475   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13476     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13477
13478   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13479     {
13480       struct nextfnfield *nfp = flp->head;
13481       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13482       int k;
13483
13484       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13485       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13486       fn_flp->fn_fields = (struct fn_field *)
13487         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13488       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13489         fn_flp->fn_fields[k] = nfp->fnfield;
13490     }
13491
13492   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13493 }
13494
13495 /* Returns non-zero if NAME is the name of a vtable member in CU's
13496    language, zero otherwise.  */
13497 static int
13498 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13499 {
13500   static const char vptr[] = "_vptr";
13501   static const char vtable[] = "vtable";
13502
13503   /* Look for the C++ form of the vtable.  */
13504   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13505     return 1;
13506
13507   return 0;
13508 }
13509
13510 /* GCC outputs unnamed structures that are really pointers to member
13511    functions, with the ABI-specified layout.  If TYPE describes
13512    such a structure, smash it into a member function type.
13513
13514    GCC shouldn't do this; it should just output pointer to member DIEs.
13515    This is GCC PR debug/28767.  */
13516
13517 static void
13518 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13519 {
13520   struct type *pfn_type, *self_type, *new_type;
13521
13522   /* Check for a structure with no name and two children.  */
13523   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13524     return;
13525
13526   /* Check for __pfn and __delta members.  */
13527   if (TYPE_FIELD_NAME (type, 0) == NULL
13528       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13529       || TYPE_FIELD_NAME (type, 1) == NULL
13530       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13531     return;
13532
13533   /* Find the type of the method.  */
13534   pfn_type = TYPE_FIELD_TYPE (type, 0);
13535   if (pfn_type == NULL
13536       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13537       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13538     return;
13539
13540   /* Look for the "this" argument.  */
13541   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13542   if (TYPE_NFIELDS (pfn_type) == 0
13543       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13544       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13545     return;
13546
13547   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13548   new_type = alloc_type (objfile);
13549   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13550                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13551                         TYPE_VARARGS (pfn_type));
13552   smash_to_methodptr_type (type, new_type);
13553 }
13554
13555
13556 /* Called when we find the DIE that starts a structure or union scope
13557    (definition) to create a type for the structure or union.  Fill in
13558    the type's name and general properties; the members will not be
13559    processed until process_structure_scope.  A symbol table entry for
13560    the type will also not be done until process_structure_scope (assuming
13561    the type has a name).
13562
13563    NOTE: we need to call these functions regardless of whether or not the
13564    DIE has a DW_AT_name attribute, since it might be an anonymous
13565    structure or union.  This gets the type entered into our set of
13566    user defined types.  */
13567
13568 static struct type *
13569 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13570 {
13571   struct objfile *objfile = cu->objfile;
13572   struct type *type;
13573   struct attribute *attr;
13574   const char *name;
13575
13576   /* If the definition of this type lives in .debug_types, read that type.
13577      Don't follow DW_AT_specification though, that will take us back up
13578      the chain and we want to go down.  */
13579   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13580   if (attr)
13581     {
13582       type = get_DW_AT_signature_type (die, attr, cu);
13583
13584       /* The type's CU may not be the same as CU.
13585          Ensure TYPE is recorded with CU in die_type_hash.  */
13586       return set_die_type (die, type, cu);
13587     }
13588
13589   type = alloc_type (objfile);
13590   INIT_CPLUS_SPECIFIC (type);
13591
13592   name = dwarf2_name (die, cu);
13593   if (name != NULL)
13594     {
13595       if (cu->language == language_cplus
13596           || cu->language == language_d
13597           || cu->language == language_rust)
13598         {
13599           const char *full_name = dwarf2_full_name (name, die, cu);
13600
13601           /* dwarf2_full_name might have already finished building the DIE's
13602              type.  If so, there is no need to continue.  */
13603           if (get_die_type (die, cu) != NULL)
13604             return get_die_type (die, cu);
13605
13606           TYPE_TAG_NAME (type) = full_name;
13607           if (die->tag == DW_TAG_structure_type
13608               || die->tag == DW_TAG_class_type)
13609             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13610         }
13611       else
13612         {
13613           /* The name is already allocated along with this objfile, so
13614              we don't need to duplicate it for the type.  */
13615           TYPE_TAG_NAME (type) = name;
13616           if (die->tag == DW_TAG_class_type)
13617             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13618         }
13619     }
13620
13621   if (die->tag == DW_TAG_structure_type)
13622     {
13623       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13624     }
13625   else if (die->tag == DW_TAG_union_type)
13626     {
13627       TYPE_CODE (type) = TYPE_CODE_UNION;
13628     }
13629   else
13630     {
13631       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13632     }
13633
13634   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13635     TYPE_DECLARED_CLASS (type) = 1;
13636
13637   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13638   if (attr)
13639     {
13640       if (attr_form_is_constant (attr))
13641         TYPE_LENGTH (type) = DW_UNSND (attr);
13642       else
13643         {
13644           /* For the moment, dynamic type sizes are not supported
13645              by GDB's struct type.  The actual size is determined
13646              on-demand when resolving the type of a given object,
13647              so set the type's length to zero for now.  Otherwise,
13648              we record an expression as the length, and that expression
13649              could lead to a very large value, which could eventually
13650              lead to us trying to allocate that much memory when creating
13651              a value of that type.  */
13652           TYPE_LENGTH (type) = 0;
13653         }
13654     }
13655   else
13656     {
13657       TYPE_LENGTH (type) = 0;
13658     }
13659
13660   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
13661     {
13662       /* ICC<14 does not output the required DW_AT_declaration on
13663          incomplete types, but gives them a size of zero.  */
13664       TYPE_STUB (type) = 1;
13665     }
13666   else
13667     TYPE_STUB_SUPPORTED (type) = 1;
13668
13669   if (die_is_declaration (die, cu))
13670     TYPE_STUB (type) = 1;
13671   else if (attr == NULL && die->child == NULL
13672            && producer_is_realview (cu->producer))
13673     /* RealView does not output the required DW_AT_declaration
13674        on incomplete types.  */
13675     TYPE_STUB (type) = 1;
13676
13677   /* We need to add the type field to the die immediately so we don't
13678      infinitely recurse when dealing with pointers to the structure
13679      type within the structure itself.  */
13680   set_die_type (die, type, cu);
13681
13682   /* set_die_type should be already done.  */
13683   set_descriptive_type (type, die, cu);
13684
13685   return type;
13686 }
13687
13688 /* Finish creating a structure or union type, including filling in
13689    its members and creating a symbol for it.  */
13690
13691 static void
13692 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
13693 {
13694   struct objfile *objfile = cu->objfile;
13695   struct die_info *child_die;
13696   struct type *type;
13697
13698   type = get_die_type (die, cu);
13699   if (type == NULL)
13700     type = read_structure_type (die, cu);
13701
13702   if (die->child != NULL && ! die_is_declaration (die, cu))
13703     {
13704       struct field_info fi;
13705       VEC (symbolp) *template_args = NULL;
13706       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
13707
13708       memset (&fi, 0, sizeof (struct field_info));
13709
13710       child_die = die->child;
13711
13712       while (child_die && child_die->tag)
13713         {
13714           if (child_die->tag == DW_TAG_member
13715               || child_die->tag == DW_TAG_variable)
13716             {
13717               /* NOTE: carlton/2002-11-05: A C++ static data member
13718                  should be a DW_TAG_member that is a declaration, but
13719                  all versions of G++ as of this writing (so through at
13720                  least 3.2.1) incorrectly generate DW_TAG_variable
13721                  tags for them instead.  */
13722               dwarf2_add_field (&fi, child_die, cu);
13723             }
13724           else if (child_die->tag == DW_TAG_subprogram)
13725             {
13726               /* Rust doesn't have member functions in the C++ sense.
13727                  However, it does emit ordinary functions as children
13728                  of a struct DIE.  */
13729               if (cu->language == language_rust)
13730                 read_func_scope (child_die, cu);
13731               else
13732                 {
13733                   /* C++ member function.  */
13734                   dwarf2_add_member_fn (&fi, child_die, type, cu);
13735                 }
13736             }
13737           else if (child_die->tag == DW_TAG_inheritance)
13738             {
13739               /* C++ base class field.  */
13740               dwarf2_add_field (&fi, child_die, cu);
13741             }
13742           else if (child_die->tag == DW_TAG_typedef)
13743             dwarf2_add_typedef (&fi, child_die, cu);
13744           else if (child_die->tag == DW_TAG_template_type_param
13745                    || child_die->tag == DW_TAG_template_value_param)
13746             {
13747               struct symbol *arg = new_symbol (child_die, NULL, cu);
13748
13749               if (arg != NULL)
13750                 VEC_safe_push (symbolp, template_args, arg);
13751             }
13752
13753           child_die = sibling_die (child_die);
13754         }
13755
13756       /* Attach template arguments to type.  */
13757       if (! VEC_empty (symbolp, template_args))
13758         {
13759           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13760           TYPE_N_TEMPLATE_ARGUMENTS (type)
13761             = VEC_length (symbolp, template_args);
13762           TYPE_TEMPLATE_ARGUMENTS (type)
13763             = XOBNEWVEC (&objfile->objfile_obstack,
13764                          struct symbol *,
13765                          TYPE_N_TEMPLATE_ARGUMENTS (type));
13766           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
13767                   VEC_address (symbolp, template_args),
13768                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
13769                    * sizeof (struct symbol *)));
13770           VEC_free (symbolp, template_args);
13771         }
13772
13773       /* Attach fields and member functions to the type.  */
13774       if (fi.nfields)
13775         dwarf2_attach_fields_to_type (&fi, type, cu);
13776       if (fi.nfnfields)
13777         {
13778           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
13779
13780           /* Get the type which refers to the base class (possibly this
13781              class itself) which contains the vtable pointer for the current
13782              class from the DW_AT_containing_type attribute.  This use of
13783              DW_AT_containing_type is a GNU extension.  */
13784
13785           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13786             {
13787               struct type *t = die_containing_type (die, cu);
13788
13789               set_type_vptr_basetype (type, t);
13790               if (type == t)
13791                 {
13792                   int i;
13793
13794                   /* Our own class provides vtbl ptr.  */
13795                   for (i = TYPE_NFIELDS (t) - 1;
13796                        i >= TYPE_N_BASECLASSES (t);
13797                        --i)
13798                     {
13799                       const char *fieldname = TYPE_FIELD_NAME (t, i);
13800
13801                       if (is_vtable_name (fieldname, cu))
13802                         {
13803                           set_type_vptr_fieldno (type, i);
13804                           break;
13805                         }
13806                     }
13807
13808                   /* Complain if virtual function table field not found.  */
13809                   if (i < TYPE_N_BASECLASSES (t))
13810                     complaint (&symfile_complaints,
13811                                _("virtual function table pointer "
13812                                  "not found when defining class '%s'"),
13813                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
13814                                "");
13815                 }
13816               else
13817                 {
13818                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
13819                 }
13820             }
13821           else if (cu->producer
13822                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
13823             {
13824               /* The IBM XLC compiler does not provide direct indication
13825                  of the containing type, but the vtable pointer is
13826                  always named __vfp.  */
13827
13828               int i;
13829
13830               for (i = TYPE_NFIELDS (type) - 1;
13831                    i >= TYPE_N_BASECLASSES (type);
13832                    --i)
13833                 {
13834                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
13835                     {
13836                       set_type_vptr_fieldno (type, i);
13837                       set_type_vptr_basetype (type, type);
13838                       break;
13839                     }
13840                 }
13841             }
13842         }
13843
13844       /* Copy fi.typedef_field_list linked list elements content into the
13845          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
13846       if (fi.typedef_field_list)
13847         {
13848           int i = fi.typedef_field_list_count;
13849
13850           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13851           TYPE_TYPEDEF_FIELD_ARRAY (type)
13852             = ((struct typedef_field *)
13853                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
13854           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
13855
13856           /* Reverse the list order to keep the debug info elements order.  */
13857           while (--i >= 0)
13858             {
13859               struct typedef_field *dest, *src;
13860
13861               dest = &TYPE_TYPEDEF_FIELD (type, i);
13862               src = &fi.typedef_field_list->field;
13863               fi.typedef_field_list = fi.typedef_field_list->next;
13864               *dest = *src;
13865             }
13866         }
13867
13868       do_cleanups (back_to);
13869     }
13870
13871   quirk_gcc_member_function_pointer (type, objfile);
13872
13873   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
13874      snapshots) has been known to create a die giving a declaration
13875      for a class that has, as a child, a die giving a definition for a
13876      nested class.  So we have to process our children even if the
13877      current die is a declaration.  Normally, of course, a declaration
13878      won't have any children at all.  */
13879
13880   child_die = die->child;
13881
13882   while (child_die != NULL && child_die->tag)
13883     {
13884       if (child_die->tag == DW_TAG_member
13885           || child_die->tag == DW_TAG_variable
13886           || child_die->tag == DW_TAG_inheritance
13887           || child_die->tag == DW_TAG_template_value_param
13888           || child_die->tag == DW_TAG_template_type_param)
13889         {
13890           /* Do nothing.  */
13891         }
13892       else
13893         process_die (child_die, cu);
13894
13895       child_die = sibling_die (child_die);
13896     }
13897
13898   /* Do not consider external references.  According to the DWARF standard,
13899      these DIEs are identified by the fact that they have no byte_size
13900      attribute, and a declaration attribute.  */
13901   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
13902       || !die_is_declaration (die, cu))
13903     new_symbol (die, type, cu);
13904 }
13905
13906 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
13907    update TYPE using some information only available in DIE's children.  */
13908
13909 static void
13910 update_enumeration_type_from_children (struct die_info *die,
13911                                        struct type *type,
13912                                        struct dwarf2_cu *cu)
13913 {
13914   struct die_info *child_die;
13915   int unsigned_enum = 1;
13916   int flag_enum = 1;
13917   ULONGEST mask = 0;
13918
13919   auto_obstack obstack;
13920
13921   for (child_die = die->child;
13922        child_die != NULL && child_die->tag;
13923        child_die = sibling_die (child_die))
13924     {
13925       struct attribute *attr;
13926       LONGEST value;
13927       const gdb_byte *bytes;
13928       struct dwarf2_locexpr_baton *baton;
13929       const char *name;
13930
13931       if (child_die->tag != DW_TAG_enumerator)
13932         continue;
13933
13934       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
13935       if (attr == NULL)
13936         continue;
13937
13938       name = dwarf2_name (child_die, cu);
13939       if (name == NULL)
13940         name = "<anonymous enumerator>";
13941
13942       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
13943                                &value, &bytes, &baton);
13944       if (value < 0)
13945         {
13946           unsigned_enum = 0;
13947           flag_enum = 0;
13948         }
13949       else if ((mask & value) != 0)
13950         flag_enum = 0;
13951       else
13952         mask |= value;
13953
13954       /* If we already know that the enum type is neither unsigned, nor
13955          a flag type, no need to look at the rest of the enumerates.  */
13956       if (!unsigned_enum && !flag_enum)
13957         break;
13958     }
13959
13960   if (unsigned_enum)
13961     TYPE_UNSIGNED (type) = 1;
13962   if (flag_enum)
13963     TYPE_FLAG_ENUM (type) = 1;
13964 }
13965
13966 /* Given a DW_AT_enumeration_type die, set its type.  We do not
13967    complete the type's fields yet, or create any symbols.  */
13968
13969 static struct type *
13970 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
13971 {
13972   struct objfile *objfile = cu->objfile;
13973   struct type *type;
13974   struct attribute *attr;
13975   const char *name;
13976
13977   /* If the definition of this type lives in .debug_types, read that type.
13978      Don't follow DW_AT_specification though, that will take us back up
13979      the chain and we want to go down.  */
13980   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13981   if (attr)
13982     {
13983       type = get_DW_AT_signature_type (die, attr, cu);
13984
13985       /* The type's CU may not be the same as CU.
13986          Ensure TYPE is recorded with CU in die_type_hash.  */
13987       return set_die_type (die, type, cu);
13988     }
13989
13990   type = alloc_type (objfile);
13991
13992   TYPE_CODE (type) = TYPE_CODE_ENUM;
13993   name = dwarf2_full_name (NULL, die, cu);
13994   if (name != NULL)
13995     TYPE_TAG_NAME (type) = name;
13996
13997   attr = dwarf2_attr (die, DW_AT_type, cu);
13998   if (attr != NULL)
13999     {
14000       struct type *underlying_type = die_type (die, cu);
14001
14002       TYPE_TARGET_TYPE (type) = underlying_type;
14003     }
14004
14005   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14006   if (attr)
14007     {
14008       TYPE_LENGTH (type) = DW_UNSND (attr);
14009     }
14010   else
14011     {
14012       TYPE_LENGTH (type) = 0;
14013     }
14014
14015   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14016      declared as private in the package spec, and then defined only
14017      inside the package body.  Such types are known as Taft Amendment
14018      Types.  When another package uses such a type, an incomplete DIE
14019      may be generated by the compiler.  */
14020   if (die_is_declaration (die, cu))
14021     TYPE_STUB (type) = 1;
14022
14023   /* Finish the creation of this type by using the enum's children.
14024      We must call this even when the underlying type has been provided
14025      so that we can determine if we're looking at a "flag" enum.  */
14026   update_enumeration_type_from_children (die, type, cu);
14027
14028   /* If this type has an underlying type that is not a stub, then we
14029      may use its attributes.  We always use the "unsigned" attribute
14030      in this situation, because ordinarily we guess whether the type
14031      is unsigned -- but the guess can be wrong and the underlying type
14032      can tell us the reality.  However, we defer to a local size
14033      attribute if one exists, because this lets the compiler override
14034      the underlying type if needed.  */
14035   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14036     {
14037       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14038       if (TYPE_LENGTH (type) == 0)
14039         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14040     }
14041
14042   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14043
14044   return set_die_type (die, type, cu);
14045 }
14046
14047 /* Given a pointer to a die which begins an enumeration, process all
14048    the dies that define the members of the enumeration, and create the
14049    symbol for the enumeration type.
14050
14051    NOTE: We reverse the order of the element list.  */
14052
14053 static void
14054 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14055 {
14056   struct type *this_type;
14057
14058   this_type = get_die_type (die, cu);
14059   if (this_type == NULL)
14060     this_type = read_enumeration_type (die, cu);
14061
14062   if (die->child != NULL)
14063     {
14064       struct die_info *child_die;
14065       struct symbol *sym;
14066       struct field *fields = NULL;
14067       int num_fields = 0;
14068       const char *name;
14069
14070       child_die = die->child;
14071       while (child_die && child_die->tag)
14072         {
14073           if (child_die->tag != DW_TAG_enumerator)
14074             {
14075               process_die (child_die, cu);
14076             }
14077           else
14078             {
14079               name = dwarf2_name (child_die, cu);
14080               if (name)
14081                 {
14082                   sym = new_symbol (child_die, this_type, cu);
14083
14084                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14085                     {
14086                       fields = (struct field *)
14087                         xrealloc (fields,
14088                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14089                                   * sizeof (struct field));
14090                     }
14091
14092                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14093                   FIELD_TYPE (fields[num_fields]) = NULL;
14094                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14095                   FIELD_BITSIZE (fields[num_fields]) = 0;
14096
14097                   num_fields++;
14098                 }
14099             }
14100
14101           child_die = sibling_die (child_die);
14102         }
14103
14104       if (num_fields)
14105         {
14106           TYPE_NFIELDS (this_type) = num_fields;
14107           TYPE_FIELDS (this_type) = (struct field *)
14108             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14109           memcpy (TYPE_FIELDS (this_type), fields,
14110                   sizeof (struct field) * num_fields);
14111           xfree (fields);
14112         }
14113     }
14114
14115   /* If we are reading an enum from a .debug_types unit, and the enum
14116      is a declaration, and the enum is not the signatured type in the
14117      unit, then we do not want to add a symbol for it.  Adding a
14118      symbol would in some cases obscure the true definition of the
14119      enum, giving users an incomplete type when the definition is
14120      actually available.  Note that we do not want to do this for all
14121      enums which are just declarations, because C++0x allows forward
14122      enum declarations.  */
14123   if (cu->per_cu->is_debug_types
14124       && die_is_declaration (die, cu))
14125     {
14126       struct signatured_type *sig_type;
14127
14128       sig_type = (struct signatured_type *) cu->per_cu;
14129       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14130       if (sig_type->type_offset_in_section != die->sect_off)
14131         return;
14132     }
14133
14134   new_symbol (die, this_type, cu);
14135 }
14136
14137 /* Extract all information from a DW_TAG_array_type DIE and put it in
14138    the DIE's type field.  For now, this only handles one dimensional
14139    arrays.  */
14140
14141 static struct type *
14142 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14143 {
14144   struct objfile *objfile = cu->objfile;
14145   struct die_info *child_die;
14146   struct type *type;
14147   struct type *element_type, *range_type, *index_type;
14148   struct attribute *attr;
14149   const char *name;
14150   unsigned int bit_stride = 0;
14151
14152   element_type = die_type (die, cu);
14153
14154   /* The die_type call above may have already set the type for this DIE.  */
14155   type = get_die_type (die, cu);
14156   if (type)
14157     return type;
14158
14159   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14160   if (attr != NULL)
14161     bit_stride = DW_UNSND (attr) * 8;
14162
14163   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14164   if (attr != NULL)
14165     bit_stride = DW_UNSND (attr);
14166
14167   /* Irix 6.2 native cc creates array types without children for
14168      arrays with unspecified length.  */
14169   if (die->child == NULL)
14170     {
14171       index_type = objfile_type (objfile)->builtin_int;
14172       range_type = create_static_range_type (NULL, index_type, 0, -1);
14173       type = create_array_type_with_stride (NULL, element_type, range_type,
14174                                             bit_stride);
14175       return set_die_type (die, type, cu);
14176     }
14177
14178   std::vector<struct type *> range_types;
14179   child_die = die->child;
14180   while (child_die && child_die->tag)
14181     {
14182       if (child_die->tag == DW_TAG_subrange_type)
14183         {
14184           struct type *child_type = read_type_die (child_die, cu);
14185
14186           if (child_type != NULL)
14187             {
14188               /* The range type was succesfully read.  Save it for the
14189                  array type creation.  */
14190               range_types.push_back (child_type);
14191             }
14192         }
14193       child_die = sibling_die (child_die);
14194     }
14195
14196   /* Dwarf2 dimensions are output from left to right, create the
14197      necessary array types in backwards order.  */
14198
14199   type = element_type;
14200
14201   if (read_array_order (die, cu) == DW_ORD_col_major)
14202     {
14203       int i = 0;
14204
14205       while (i < range_types.size ())
14206         type = create_array_type_with_stride (NULL, type, range_types[i++],
14207                                               bit_stride);
14208     }
14209   else
14210     {
14211       size_t ndim = range_types.size ();
14212       while (ndim-- > 0)
14213         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14214                                               bit_stride);
14215     }
14216
14217   /* Understand Dwarf2 support for vector types (like they occur on
14218      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14219      array type.  This is not part of the Dwarf2/3 standard yet, but a
14220      custom vendor extension.  The main difference between a regular
14221      array and the vector variant is that vectors are passed by value
14222      to functions.  */
14223   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14224   if (attr)
14225     make_vector_type (type);
14226
14227   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14228      implementation may choose to implement triple vectors using this
14229      attribute.  */
14230   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14231   if (attr)
14232     {
14233       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14234         TYPE_LENGTH (type) = DW_UNSND (attr);
14235       else
14236         complaint (&symfile_complaints,
14237                    _("DW_AT_byte_size for array type smaller "
14238                      "than the total size of elements"));
14239     }
14240
14241   name = dwarf2_name (die, cu);
14242   if (name)
14243     TYPE_NAME (type) = name;
14244
14245   /* Install the type in the die.  */
14246   set_die_type (die, type, cu);
14247
14248   /* set_die_type should be already done.  */
14249   set_descriptive_type (type, die, cu);
14250
14251   return type;
14252 }
14253
14254 static enum dwarf_array_dim_ordering
14255 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14256 {
14257   struct attribute *attr;
14258
14259   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14260
14261   if (attr)
14262     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14263
14264   /* GNU F77 is a special case, as at 08/2004 array type info is the
14265      opposite order to the dwarf2 specification, but data is still
14266      laid out as per normal fortran.
14267
14268      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14269      version checking.  */
14270
14271   if (cu->language == language_fortran
14272       && cu->producer && strstr (cu->producer, "GNU F77"))
14273     {
14274       return DW_ORD_row_major;
14275     }
14276
14277   switch (cu->language_defn->la_array_ordering)
14278     {
14279     case array_column_major:
14280       return DW_ORD_col_major;
14281     case array_row_major:
14282     default:
14283       return DW_ORD_row_major;
14284     };
14285 }
14286
14287 /* Extract all information from a DW_TAG_set_type DIE and put it in
14288    the DIE's type field.  */
14289
14290 static struct type *
14291 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14292 {
14293   struct type *domain_type, *set_type;
14294   struct attribute *attr;
14295
14296   domain_type = die_type (die, cu);
14297
14298   /* The die_type call above may have already set the type for this DIE.  */
14299   set_type = get_die_type (die, cu);
14300   if (set_type)
14301     return set_type;
14302
14303   set_type = create_set_type (NULL, domain_type);
14304
14305   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14306   if (attr)
14307     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14308
14309   return set_die_type (die, set_type, cu);
14310 }
14311
14312 /* A helper for read_common_block that creates a locexpr baton.
14313    SYM is the symbol which we are marking as computed.
14314    COMMON_DIE is the DIE for the common block.
14315    COMMON_LOC is the location expression attribute for the common
14316    block itself.
14317    MEMBER_LOC is the location expression attribute for the particular
14318    member of the common block that we are processing.
14319    CU is the CU from which the above come.  */
14320
14321 static void
14322 mark_common_block_symbol_computed (struct symbol *sym,
14323                                    struct die_info *common_die,
14324                                    struct attribute *common_loc,
14325                                    struct attribute *member_loc,
14326                                    struct dwarf2_cu *cu)
14327 {
14328   struct objfile *objfile = dwarf2_per_objfile->objfile;
14329   struct dwarf2_locexpr_baton *baton;
14330   gdb_byte *ptr;
14331   unsigned int cu_off;
14332   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14333   LONGEST offset = 0;
14334
14335   gdb_assert (common_loc && member_loc);
14336   gdb_assert (attr_form_is_block (common_loc));
14337   gdb_assert (attr_form_is_block (member_loc)
14338               || attr_form_is_constant (member_loc));
14339
14340   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14341   baton->per_cu = cu->per_cu;
14342   gdb_assert (baton->per_cu);
14343
14344   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14345
14346   if (attr_form_is_constant (member_loc))
14347     {
14348       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14349       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14350     }
14351   else
14352     baton->size += DW_BLOCK (member_loc)->size;
14353
14354   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14355   baton->data = ptr;
14356
14357   *ptr++ = DW_OP_call4;
14358   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14359   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14360   ptr += 4;
14361
14362   if (attr_form_is_constant (member_loc))
14363     {
14364       *ptr++ = DW_OP_addr;
14365       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14366       ptr += cu->header.addr_size;
14367     }
14368   else
14369     {
14370       /* We have to copy the data here, because DW_OP_call4 will only
14371          use a DW_AT_location attribute.  */
14372       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14373       ptr += DW_BLOCK (member_loc)->size;
14374     }
14375
14376   *ptr++ = DW_OP_plus;
14377   gdb_assert (ptr - baton->data == baton->size);
14378
14379   SYMBOL_LOCATION_BATON (sym) = baton;
14380   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14381 }
14382
14383 /* Create appropriate locally-scoped variables for all the
14384    DW_TAG_common_block entries.  Also create a struct common_block
14385    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14386    is used to sepate the common blocks name namespace from regular
14387    variable names.  */
14388
14389 static void
14390 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14391 {
14392   struct attribute *attr;
14393
14394   attr = dwarf2_attr (die, DW_AT_location, cu);
14395   if (attr)
14396     {
14397       /* Support the .debug_loc offsets.  */
14398       if (attr_form_is_block (attr))
14399         {
14400           /* Ok.  */
14401         }
14402       else if (attr_form_is_section_offset (attr))
14403         {
14404           dwarf2_complex_location_expr_complaint ();
14405           attr = NULL;
14406         }
14407       else
14408         {
14409           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14410                                                  "common block member");
14411           attr = NULL;
14412         }
14413     }
14414
14415   if (die->child != NULL)
14416     {
14417       struct objfile *objfile = cu->objfile;
14418       struct die_info *child_die;
14419       size_t n_entries = 0, size;
14420       struct common_block *common_block;
14421       struct symbol *sym;
14422
14423       for (child_die = die->child;
14424            child_die && child_die->tag;
14425            child_die = sibling_die (child_die))
14426         ++n_entries;
14427
14428       size = (sizeof (struct common_block)
14429               + (n_entries - 1) * sizeof (struct symbol *));
14430       common_block
14431         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14432                                                  size);
14433       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14434       common_block->n_entries = 0;
14435
14436       for (child_die = die->child;
14437            child_die && child_die->tag;
14438            child_die = sibling_die (child_die))
14439         {
14440           /* Create the symbol in the DW_TAG_common_block block in the current
14441              symbol scope.  */
14442           sym = new_symbol (child_die, NULL, cu);
14443           if (sym != NULL)
14444             {
14445               struct attribute *member_loc;
14446
14447               common_block->contents[common_block->n_entries++] = sym;
14448
14449               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14450                                         cu);
14451               if (member_loc)
14452                 {
14453                   /* GDB has handled this for a long time, but it is
14454                      not specified by DWARF.  It seems to have been
14455                      emitted by gfortran at least as recently as:
14456                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14457                   complaint (&symfile_complaints,
14458                              _("Variable in common block has "
14459                                "DW_AT_data_member_location "
14460                                "- DIE at 0x%x [in module %s]"),
14461                              to_underlying (child_die->sect_off),
14462                              objfile_name (cu->objfile));
14463
14464                   if (attr_form_is_section_offset (member_loc))
14465                     dwarf2_complex_location_expr_complaint ();
14466                   else if (attr_form_is_constant (member_loc)
14467                            || attr_form_is_block (member_loc))
14468                     {
14469                       if (attr)
14470                         mark_common_block_symbol_computed (sym, die, attr,
14471                                                            member_loc, cu);
14472                     }
14473                   else
14474                     dwarf2_complex_location_expr_complaint ();
14475                 }
14476             }
14477         }
14478
14479       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14480       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14481     }
14482 }
14483
14484 /* Create a type for a C++ namespace.  */
14485
14486 static struct type *
14487 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14488 {
14489   struct objfile *objfile = cu->objfile;
14490   const char *previous_prefix, *name;
14491   int is_anonymous;
14492   struct type *type;
14493
14494   /* For extensions, reuse the type of the original namespace.  */
14495   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14496     {
14497       struct die_info *ext_die;
14498       struct dwarf2_cu *ext_cu = cu;
14499
14500       ext_die = dwarf2_extension (die, &ext_cu);
14501       type = read_type_die (ext_die, ext_cu);
14502
14503       /* EXT_CU may not be the same as CU.
14504          Ensure TYPE is recorded with CU in die_type_hash.  */
14505       return set_die_type (die, type, cu);
14506     }
14507
14508   name = namespace_name (die, &is_anonymous, cu);
14509
14510   /* Now build the name of the current namespace.  */
14511
14512   previous_prefix = determine_prefix (die, cu);
14513   if (previous_prefix[0] != '\0')
14514     name = typename_concat (&objfile->objfile_obstack,
14515                             previous_prefix, name, 0, cu);
14516
14517   /* Create the type.  */
14518   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14519   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14520
14521   return set_die_type (die, type, cu);
14522 }
14523
14524 /* Read a namespace scope.  */
14525
14526 static void
14527 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14528 {
14529   struct objfile *objfile = cu->objfile;
14530   int is_anonymous;
14531
14532   /* Add a symbol associated to this if we haven't seen the namespace
14533      before.  Also, add a using directive if it's an anonymous
14534      namespace.  */
14535
14536   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14537     {
14538       struct type *type;
14539
14540       type = read_type_die (die, cu);
14541       new_symbol (die, type, cu);
14542
14543       namespace_name (die, &is_anonymous, cu);
14544       if (is_anonymous)
14545         {
14546           const char *previous_prefix = determine_prefix (die, cu);
14547
14548           std::vector<const char *> excludes;
14549           add_using_directive (using_directives (cu->language),
14550                                previous_prefix, TYPE_NAME (type), NULL,
14551                                NULL, excludes, 0, &objfile->objfile_obstack);
14552         }
14553     }
14554
14555   if (die->child != NULL)
14556     {
14557       struct die_info *child_die = die->child;
14558
14559       while (child_die && child_die->tag)
14560         {
14561           process_die (child_die, cu);
14562           child_die = sibling_die (child_die);
14563         }
14564     }
14565 }
14566
14567 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14568    imported module.  Still we need that type as local Fortran "use ... only"
14569    declaration imports depend on the created type in determine_prefix.  */
14570
14571 static struct type *
14572 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14573 {
14574   struct objfile *objfile = cu->objfile;
14575   const char *module_name;
14576   struct type *type;
14577
14578   module_name = dwarf2_name (die, cu);
14579   if (!module_name)
14580     complaint (&symfile_complaints,
14581                _("DW_TAG_module has no name, offset 0x%x"),
14582                to_underlying (die->sect_off));
14583   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14584
14585   /* determine_prefix uses TYPE_TAG_NAME.  */
14586   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14587
14588   return set_die_type (die, type, cu);
14589 }
14590
14591 /* Read a Fortran module.  */
14592
14593 static void
14594 read_module (struct die_info *die, struct dwarf2_cu *cu)
14595 {
14596   struct die_info *child_die = die->child;
14597   struct type *type;
14598
14599   type = read_type_die (die, cu);
14600   new_symbol (die, type, cu);
14601
14602   while (child_die && child_die->tag)
14603     {
14604       process_die (child_die, cu);
14605       child_die = sibling_die (child_die);
14606     }
14607 }
14608
14609 /* Return the name of the namespace represented by DIE.  Set
14610    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14611    namespace.  */
14612
14613 static const char *
14614 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14615 {
14616   struct die_info *current_die;
14617   const char *name = NULL;
14618
14619   /* Loop through the extensions until we find a name.  */
14620
14621   for (current_die = die;
14622        current_die != NULL;
14623        current_die = dwarf2_extension (die, &cu))
14624     {
14625       /* We don't use dwarf2_name here so that we can detect the absence
14626          of a name -> anonymous namespace.  */
14627       name = dwarf2_string_attr (die, DW_AT_name, cu);
14628
14629       if (name != NULL)
14630         break;
14631     }
14632
14633   /* Is it an anonymous namespace?  */
14634
14635   *is_anonymous = (name == NULL);
14636   if (*is_anonymous)
14637     name = CP_ANONYMOUS_NAMESPACE_STR;
14638
14639   return name;
14640 }
14641
14642 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14643    the user defined type vector.  */
14644
14645 static struct type *
14646 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14647 {
14648   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14649   struct comp_unit_head *cu_header = &cu->header;
14650   struct type *type;
14651   struct attribute *attr_byte_size;
14652   struct attribute *attr_address_class;
14653   int byte_size, addr_class;
14654   struct type *target_type;
14655
14656   target_type = die_type (die, cu);
14657
14658   /* The die_type call above may have already set the type for this DIE.  */
14659   type = get_die_type (die, cu);
14660   if (type)
14661     return type;
14662
14663   type = lookup_pointer_type (target_type);
14664
14665   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14666   if (attr_byte_size)
14667     byte_size = DW_UNSND (attr_byte_size);
14668   else
14669     byte_size = cu_header->addr_size;
14670
14671   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14672   if (attr_address_class)
14673     addr_class = DW_UNSND (attr_address_class);
14674   else
14675     addr_class = DW_ADDR_none;
14676
14677   /* If the pointer size or address class is different than the
14678      default, create a type variant marked as such and set the
14679      length accordingly.  */
14680   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
14681     {
14682       if (gdbarch_address_class_type_flags_p (gdbarch))
14683         {
14684           int type_flags;
14685
14686           type_flags = gdbarch_address_class_type_flags
14687                          (gdbarch, byte_size, addr_class);
14688           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
14689                       == 0);
14690           type = make_type_with_address_space (type, type_flags);
14691         }
14692       else if (TYPE_LENGTH (type) != byte_size)
14693         {
14694           complaint (&symfile_complaints,
14695                      _("invalid pointer size %d"), byte_size);
14696         }
14697       else
14698         {
14699           /* Should we also complain about unhandled address classes?  */
14700         }
14701     }
14702
14703   TYPE_LENGTH (type) = byte_size;
14704   return set_die_type (die, type, cu);
14705 }
14706
14707 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
14708    the user defined type vector.  */
14709
14710 static struct type *
14711 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
14712 {
14713   struct type *type;
14714   struct type *to_type;
14715   struct type *domain;
14716
14717   to_type = die_type (die, cu);
14718   domain = die_containing_type (die, cu);
14719
14720   /* The calls above may have already set the type for this DIE.  */
14721   type = get_die_type (die, cu);
14722   if (type)
14723     return type;
14724
14725   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
14726     type = lookup_methodptr_type (to_type);
14727   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
14728     {
14729       struct type *new_type = alloc_type (cu->objfile);
14730
14731       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
14732                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
14733                             TYPE_VARARGS (to_type));
14734       type = lookup_methodptr_type (new_type);
14735     }
14736   else
14737     type = lookup_memberptr_type (to_type, domain);
14738
14739   return set_die_type (die, type, cu);
14740 }
14741
14742 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
14743    the user defined type vector.  */
14744
14745 static struct type *
14746 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
14747                           enum type_code refcode)
14748 {
14749   struct comp_unit_head *cu_header = &cu->header;
14750   struct type *type, *target_type;
14751   struct attribute *attr;
14752
14753   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
14754
14755   target_type = die_type (die, cu);
14756
14757   /* The die_type call above may have already set the type for this DIE.  */
14758   type = get_die_type (die, cu);
14759   if (type)
14760     return type;
14761
14762   type = lookup_reference_type (target_type, refcode);
14763   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14764   if (attr)
14765     {
14766       TYPE_LENGTH (type) = DW_UNSND (attr);
14767     }
14768   else
14769     {
14770       TYPE_LENGTH (type) = cu_header->addr_size;
14771     }
14772   return set_die_type (die, type, cu);
14773 }
14774
14775 /* Add the given cv-qualifiers to the element type of the array.  GCC
14776    outputs DWARF type qualifiers that apply to an array, not the
14777    element type.  But GDB relies on the array element type to carry
14778    the cv-qualifiers.  This mimics section 6.7.3 of the C99
14779    specification.  */
14780
14781 static struct type *
14782 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
14783                    struct type *base_type, int cnst, int voltl)
14784 {
14785   struct type *el_type, *inner_array;
14786
14787   base_type = copy_type (base_type);
14788   inner_array = base_type;
14789
14790   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
14791     {
14792       TYPE_TARGET_TYPE (inner_array) =
14793         copy_type (TYPE_TARGET_TYPE (inner_array));
14794       inner_array = TYPE_TARGET_TYPE (inner_array);
14795     }
14796
14797   el_type = TYPE_TARGET_TYPE (inner_array);
14798   cnst |= TYPE_CONST (el_type);
14799   voltl |= TYPE_VOLATILE (el_type);
14800   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
14801
14802   return set_die_type (die, base_type, cu);
14803 }
14804
14805 static struct type *
14806 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
14807 {
14808   struct type *base_type, *cv_type;
14809
14810   base_type = die_type (die, cu);
14811
14812   /* The die_type call above may have already set the type for this DIE.  */
14813   cv_type = get_die_type (die, cu);
14814   if (cv_type)
14815     return cv_type;
14816
14817   /* In case the const qualifier is applied to an array type, the element type
14818      is so qualified, not the array type (section 6.7.3 of C99).  */
14819   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14820     return add_array_cv_type (die, cu, base_type, 1, 0);
14821
14822   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
14823   return set_die_type (die, cv_type, cu);
14824 }
14825
14826 static struct type *
14827 read_tag_volatile_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 volatile qualifier is applied to an array type, the
14839      element type is so qualified, not the array type (section 6.7.3
14840      of C99).  */
14841   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
14842     return add_array_cv_type (die, cu, base_type, 0, 1);
14843
14844   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
14845   return set_die_type (die, cv_type, cu);
14846 }
14847
14848 /* Handle DW_TAG_restrict_type.  */
14849
14850 static struct type *
14851 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
14852 {
14853   struct type *base_type, *cv_type;
14854
14855   base_type = die_type (die, cu);
14856
14857   /* The die_type call above may have already set the type for this DIE.  */
14858   cv_type = get_die_type (die, cu);
14859   if (cv_type)
14860     return cv_type;
14861
14862   cv_type = make_restrict_type (base_type);
14863   return set_die_type (die, cv_type, cu);
14864 }
14865
14866 /* Handle DW_TAG_atomic_type.  */
14867
14868 static struct type *
14869 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
14870 {
14871   struct type *base_type, *cv_type;
14872
14873   base_type = die_type (die, cu);
14874
14875   /* The die_type call above may have already set the type for this DIE.  */
14876   cv_type = get_die_type (die, cu);
14877   if (cv_type)
14878     return cv_type;
14879
14880   cv_type = make_atomic_type (base_type);
14881   return set_die_type (die, cv_type, cu);
14882 }
14883
14884 /* Extract all information from a DW_TAG_string_type DIE and add to
14885    the user defined type vector.  It isn't really a user defined type,
14886    but it behaves like one, with other DIE's using an AT_user_def_type
14887    attribute to reference it.  */
14888
14889 static struct type *
14890 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
14891 {
14892   struct objfile *objfile = cu->objfile;
14893   struct gdbarch *gdbarch = get_objfile_arch (objfile);
14894   struct type *type, *range_type, *index_type, *char_type;
14895   struct attribute *attr;
14896   unsigned int length;
14897
14898   attr = dwarf2_attr (die, DW_AT_string_length, cu);
14899   if (attr)
14900     {
14901       length = DW_UNSND (attr);
14902     }
14903   else
14904     {
14905       /* Check for the DW_AT_byte_size attribute.  */
14906       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14907       if (attr)
14908         {
14909           length = DW_UNSND (attr);
14910         }
14911       else
14912         {
14913           length = 1;
14914         }
14915     }
14916
14917   index_type = objfile_type (objfile)->builtin_int;
14918   range_type = create_static_range_type (NULL, index_type, 1, length);
14919   char_type = language_string_char_type (cu->language_defn, gdbarch);
14920   type = create_string_type (NULL, char_type, range_type);
14921
14922   return set_die_type (die, type, cu);
14923 }
14924
14925 /* Assuming that DIE corresponds to a function, returns nonzero
14926    if the function is prototyped.  */
14927
14928 static int
14929 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
14930 {
14931   struct attribute *attr;
14932
14933   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
14934   if (attr && (DW_UNSND (attr) != 0))
14935     return 1;
14936
14937   /* The DWARF standard implies that the DW_AT_prototyped attribute
14938      is only meaninful for C, but the concept also extends to other
14939      languages that allow unprototyped functions (Eg: Objective C).
14940      For all other languages, assume that functions are always
14941      prototyped.  */
14942   if (cu->language != language_c
14943       && cu->language != language_objc
14944       && cu->language != language_opencl)
14945     return 1;
14946
14947   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
14948      prototyped and unprototyped functions; default to prototyped,
14949      since that is more common in modern code (and RealView warns
14950      about unprototyped functions).  */
14951   if (producer_is_realview (cu->producer))
14952     return 1;
14953
14954   return 0;
14955 }
14956
14957 /* Handle DIES due to C code like:
14958
14959    struct foo
14960    {
14961    int (*funcp)(int a, long l);
14962    int b;
14963    };
14964
14965    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
14966
14967 static struct type *
14968 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
14969 {
14970   struct objfile *objfile = cu->objfile;
14971   struct type *type;            /* Type that this function returns.  */
14972   struct type *ftype;           /* Function that returns above type.  */
14973   struct attribute *attr;
14974
14975   type = die_type (die, cu);
14976
14977   /* The die_type call above may have already set the type for this DIE.  */
14978   ftype = get_die_type (die, cu);
14979   if (ftype)
14980     return ftype;
14981
14982   ftype = lookup_function_type (type);
14983
14984   if (prototyped_function_p (die, cu))
14985     TYPE_PROTOTYPED (ftype) = 1;
14986
14987   /* Store the calling convention in the type if it's available in
14988      the subroutine die.  Otherwise set the calling convention to
14989      the default value DW_CC_normal.  */
14990   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
14991   if (attr)
14992     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
14993   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
14994     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
14995   else
14996     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
14997
14998   /* Record whether the function returns normally to its caller or not
14999      if the DWARF producer set that information.  */
15000   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15001   if (attr && (DW_UNSND (attr) != 0))
15002     TYPE_NO_RETURN (ftype) = 1;
15003
15004   /* We need to add the subroutine type to the die immediately so
15005      we don't infinitely recurse when dealing with parameters
15006      declared as the same subroutine type.  */
15007   set_die_type (die, ftype, cu);
15008
15009   if (die->child != NULL)
15010     {
15011       struct type *void_type = objfile_type (objfile)->builtin_void;
15012       struct die_info *child_die;
15013       int nparams, iparams;
15014
15015       /* Count the number of parameters.
15016          FIXME: GDB currently ignores vararg functions, but knows about
15017          vararg member functions.  */
15018       nparams = 0;
15019       child_die = die->child;
15020       while (child_die && child_die->tag)
15021         {
15022           if (child_die->tag == DW_TAG_formal_parameter)
15023             nparams++;
15024           else if (child_die->tag == DW_TAG_unspecified_parameters)
15025             TYPE_VARARGS (ftype) = 1;
15026           child_die = sibling_die (child_die);
15027         }
15028
15029       /* Allocate storage for parameters and fill them in.  */
15030       TYPE_NFIELDS (ftype) = nparams;
15031       TYPE_FIELDS (ftype) = (struct field *)
15032         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15033
15034       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15035          even if we error out during the parameters reading below.  */
15036       for (iparams = 0; iparams < nparams; iparams++)
15037         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15038
15039       iparams = 0;
15040       child_die = die->child;
15041       while (child_die && child_die->tag)
15042         {
15043           if (child_die->tag == DW_TAG_formal_parameter)
15044             {
15045               struct type *arg_type;
15046
15047               /* DWARF version 2 has no clean way to discern C++
15048                  static and non-static member functions.  G++ helps
15049                  GDB by marking the first parameter for non-static
15050                  member functions (which is the this pointer) as
15051                  artificial.  We pass this information to
15052                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15053
15054                  DWARF version 3 added DW_AT_object_pointer, which GCC
15055                  4.5 does not yet generate.  */
15056               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15057               if (attr)
15058                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15059               else
15060                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15061               arg_type = die_type (child_die, cu);
15062
15063               /* RealView does not mark THIS as const, which the testsuite
15064                  expects.  GCC marks THIS as const in method definitions,
15065                  but not in the class specifications (GCC PR 43053).  */
15066               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15067                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15068                 {
15069                   int is_this = 0;
15070                   struct dwarf2_cu *arg_cu = cu;
15071                   const char *name = dwarf2_name (child_die, cu);
15072
15073                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15074                   if (attr)
15075                     {
15076                       /* If the compiler emits this, use it.  */
15077                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15078                         is_this = 1;
15079                     }
15080                   else if (name && strcmp (name, "this") == 0)
15081                     /* Function definitions will have the argument names.  */
15082                     is_this = 1;
15083                   else if (name == NULL && iparams == 0)
15084                     /* Declarations may not have the names, so like
15085                        elsewhere in GDB, assume an artificial first
15086                        argument is "this".  */
15087                     is_this = 1;
15088
15089                   if (is_this)
15090                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15091                                              arg_type, 0);
15092                 }
15093
15094               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15095               iparams++;
15096             }
15097           child_die = sibling_die (child_die);
15098         }
15099     }
15100
15101   return ftype;
15102 }
15103
15104 static struct type *
15105 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15106 {
15107   struct objfile *objfile = cu->objfile;
15108   const char *name = NULL;
15109   struct type *this_type, *target_type;
15110
15111   name = dwarf2_full_name (NULL, die, cu);
15112   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15113   TYPE_TARGET_STUB (this_type) = 1;
15114   set_die_type (die, this_type, cu);
15115   target_type = die_type (die, cu);
15116   if (target_type != this_type)
15117     TYPE_TARGET_TYPE (this_type) = target_type;
15118   else
15119     {
15120       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15121          spec and cause infinite loops in GDB.  */
15122       complaint (&symfile_complaints,
15123                  _("Self-referential DW_TAG_typedef "
15124                    "- DIE at 0x%x [in module %s]"),
15125                  to_underlying (die->sect_off), objfile_name (objfile));
15126       TYPE_TARGET_TYPE (this_type) = NULL;
15127     }
15128   return this_type;
15129 }
15130
15131 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15132    (which may be different from NAME) to the architecture back-end to allow
15133    it to guess the correct format if necessary.  */
15134
15135 static struct type *
15136 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15137                         const char *name_hint)
15138 {
15139   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15140   const struct floatformat **format;
15141   struct type *type;
15142
15143   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15144   if (format)
15145     type = init_float_type (objfile, bits, name, format);
15146   else
15147     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15148
15149   return type;
15150 }
15151
15152 /* Find a representation of a given base type and install
15153    it in the TYPE field of the die.  */
15154
15155 static struct type *
15156 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15157 {
15158   struct objfile *objfile = cu->objfile;
15159   struct type *type;
15160   struct attribute *attr;
15161   int encoding = 0, bits = 0;
15162   const char *name;
15163
15164   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15165   if (attr)
15166     {
15167       encoding = DW_UNSND (attr);
15168     }
15169   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15170   if (attr)
15171     {
15172       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15173     }
15174   name = dwarf2_name (die, cu);
15175   if (!name)
15176     {
15177       complaint (&symfile_complaints,
15178                  _("DW_AT_name missing from DW_TAG_base_type"));
15179     }
15180
15181   switch (encoding)
15182     {
15183       case DW_ATE_address:
15184         /* Turn DW_ATE_address into a void * pointer.  */
15185         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
15186         type = init_pointer_type (objfile, bits, name, type);
15187         break;
15188       case DW_ATE_boolean:
15189         type = init_boolean_type (objfile, bits, 1, name);
15190         break;
15191       case DW_ATE_complex_float:
15192         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15193         type = init_complex_type (objfile, name, type);
15194         break;
15195       case DW_ATE_decimal_float:
15196         type = init_decfloat_type (objfile, bits, name);
15197         break;
15198       case DW_ATE_float:
15199         type = dwarf2_init_float_type (objfile, bits, name, name);
15200         break;
15201       case DW_ATE_signed:
15202         type = init_integer_type (objfile, bits, 0, name);
15203         break;
15204       case DW_ATE_unsigned:
15205         if (cu->language == language_fortran
15206             && name
15207             && startswith (name, "character("))
15208           type = init_character_type (objfile, bits, 1, name);
15209         else
15210           type = init_integer_type (objfile, bits, 1, name);
15211         break;
15212       case DW_ATE_signed_char:
15213         if (cu->language == language_ada || cu->language == language_m2
15214             || cu->language == language_pascal
15215             || cu->language == language_fortran)
15216           type = init_character_type (objfile, bits, 0, name);
15217         else
15218           type = init_integer_type (objfile, bits, 0, name);
15219         break;
15220       case DW_ATE_unsigned_char:
15221         if (cu->language == language_ada || cu->language == language_m2
15222             || cu->language == language_pascal
15223             || cu->language == language_fortran
15224             || cu->language == language_rust)
15225           type = init_character_type (objfile, bits, 1, name);
15226         else
15227           type = init_integer_type (objfile, bits, 1, name);
15228         break;
15229       case DW_ATE_UTF:
15230         {
15231           gdbarch *arch = get_objfile_arch (objfile);
15232
15233           if (bits == 16)
15234             type = builtin_type (arch)->builtin_char16;
15235           else if (bits == 32)
15236             type = builtin_type (arch)->builtin_char32;
15237           else
15238             {
15239               complaint (&symfile_complaints,
15240                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15241                          bits);
15242               type = init_integer_type (objfile, bits, 1, name);
15243             }
15244           return set_die_type (die, type, cu);
15245         }
15246         break;
15247
15248       default:
15249         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15250                    dwarf_type_encoding_name (encoding));
15251         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15252         break;
15253     }
15254
15255   if (name && strcmp (name, "char") == 0)
15256     TYPE_NOSIGN (type) = 1;
15257
15258   return set_die_type (die, type, cu);
15259 }
15260
15261 /* Parse dwarf attribute if it's a block, reference or constant and put the
15262    resulting value of the attribute into struct bound_prop.
15263    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15264
15265 static int
15266 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15267                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15268 {
15269   struct dwarf2_property_baton *baton;
15270   struct obstack *obstack = &cu->objfile->objfile_obstack;
15271
15272   if (attr == NULL || prop == NULL)
15273     return 0;
15274
15275   if (attr_form_is_block (attr))
15276     {
15277       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15278       baton->referenced_type = NULL;
15279       baton->locexpr.per_cu = cu->per_cu;
15280       baton->locexpr.size = DW_BLOCK (attr)->size;
15281       baton->locexpr.data = DW_BLOCK (attr)->data;
15282       prop->data.baton = baton;
15283       prop->kind = PROP_LOCEXPR;
15284       gdb_assert (prop->data.baton != NULL);
15285     }
15286   else if (attr_form_is_ref (attr))
15287     {
15288       struct dwarf2_cu *target_cu = cu;
15289       struct die_info *target_die;
15290       struct attribute *target_attr;
15291
15292       target_die = follow_die_ref (die, attr, &target_cu);
15293       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15294       if (target_attr == NULL)
15295         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15296                                    target_cu);
15297       if (target_attr == NULL)
15298         return 0;
15299
15300       switch (target_attr->name)
15301         {
15302           case DW_AT_location:
15303             if (attr_form_is_section_offset (target_attr))
15304               {
15305                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15306                 baton->referenced_type = die_type (target_die, target_cu);
15307                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15308                 prop->data.baton = baton;
15309                 prop->kind = PROP_LOCLIST;
15310                 gdb_assert (prop->data.baton != NULL);
15311               }
15312             else if (attr_form_is_block (target_attr))
15313               {
15314                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15315                 baton->referenced_type = die_type (target_die, target_cu);
15316                 baton->locexpr.per_cu = cu->per_cu;
15317                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15318                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15319                 prop->data.baton = baton;
15320                 prop->kind = PROP_LOCEXPR;
15321                 gdb_assert (prop->data.baton != NULL);
15322               }
15323             else
15324               {
15325                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15326                                                        "dynamic property");
15327                 return 0;
15328               }
15329             break;
15330           case DW_AT_data_member_location:
15331             {
15332               LONGEST offset;
15333
15334               if (!handle_data_member_location (target_die, target_cu,
15335                                                 &offset))
15336                 return 0;
15337
15338               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15339               baton->referenced_type = read_type_die (target_die->parent,
15340                                                       target_cu);
15341               baton->offset_info.offset = offset;
15342               baton->offset_info.type = die_type (target_die, target_cu);
15343               prop->data.baton = baton;
15344               prop->kind = PROP_ADDR_OFFSET;
15345               break;
15346             }
15347         }
15348     }
15349   else if (attr_form_is_constant (attr))
15350     {
15351       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15352       prop->kind = PROP_CONST;
15353     }
15354   else
15355     {
15356       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15357                                              dwarf2_name (die, cu));
15358       return 0;
15359     }
15360
15361   return 1;
15362 }
15363
15364 /* Read the given DW_AT_subrange DIE.  */
15365
15366 static struct type *
15367 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15368 {
15369   struct type *base_type, *orig_base_type;
15370   struct type *range_type;
15371   struct attribute *attr;
15372   struct dynamic_prop low, high;
15373   int low_default_is_valid;
15374   int high_bound_is_count = 0;
15375   const char *name;
15376   LONGEST negative_mask;
15377
15378   orig_base_type = die_type (die, cu);
15379   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15380      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15381      creating the range type, but we use the result of check_typedef
15382      when examining properties of the type.  */
15383   base_type = check_typedef (orig_base_type);
15384
15385   /* The die_type call above may have already set the type for this DIE.  */
15386   range_type = get_die_type (die, cu);
15387   if (range_type)
15388     return range_type;
15389
15390   low.kind = PROP_CONST;
15391   high.kind = PROP_CONST;
15392   high.data.const_val = 0;
15393
15394   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15395      omitting DW_AT_lower_bound.  */
15396   switch (cu->language)
15397     {
15398     case language_c:
15399     case language_cplus:
15400       low.data.const_val = 0;
15401       low_default_is_valid = 1;
15402       break;
15403     case language_fortran:
15404       low.data.const_val = 1;
15405       low_default_is_valid = 1;
15406       break;
15407     case language_d:
15408     case language_objc:
15409     case language_rust:
15410       low.data.const_val = 0;
15411       low_default_is_valid = (cu->header.version >= 4);
15412       break;
15413     case language_ada:
15414     case language_m2:
15415     case language_pascal:
15416       low.data.const_val = 1;
15417       low_default_is_valid = (cu->header.version >= 4);
15418       break;
15419     default:
15420       low.data.const_val = 0;
15421       low_default_is_valid = 0;
15422       break;
15423     }
15424
15425   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15426   if (attr)
15427     attr_to_dynamic_prop (attr, die, cu, &low);
15428   else if (!low_default_is_valid)
15429     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15430                                       "- DIE at 0x%x [in module %s]"),
15431                to_underlying (die->sect_off), objfile_name (cu->objfile));
15432
15433   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15434   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15435     {
15436       attr = dwarf2_attr (die, DW_AT_count, cu);
15437       if (attr_to_dynamic_prop (attr, die, cu, &high))
15438         {
15439           /* If bounds are constant do the final calculation here.  */
15440           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15441             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15442           else
15443             high_bound_is_count = 1;
15444         }
15445     }
15446
15447   /* Dwarf-2 specifications explicitly allows to create subrange types
15448      without specifying a base type.
15449      In that case, the base type must be set to the type of
15450      the lower bound, upper bound or count, in that order, if any of these
15451      three attributes references an object that has a type.
15452      If no base type is found, the Dwarf-2 specifications say that
15453      a signed integer type of size equal to the size of an address should
15454      be used.
15455      For the following C code: `extern char gdb_int [];'
15456      GCC produces an empty range DIE.
15457      FIXME: muller/2010-05-28: Possible references to object for low bound,
15458      high bound or count are not yet handled by this code.  */
15459   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15460     {
15461       struct objfile *objfile = cu->objfile;
15462       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15463       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15464       struct type *int_type = objfile_type (objfile)->builtin_int;
15465
15466       /* Test "int", "long int", and "long long int" objfile types,
15467          and select the first one having a size above or equal to the
15468          architecture address size.  */
15469       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15470         base_type = int_type;
15471       else
15472         {
15473           int_type = objfile_type (objfile)->builtin_long;
15474           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15475             base_type = int_type;
15476           else
15477             {
15478               int_type = objfile_type (objfile)->builtin_long_long;
15479               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15480                 base_type = int_type;
15481             }
15482         }
15483     }
15484
15485   /* Normally, the DWARF producers are expected to use a signed
15486      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15487      But this is unfortunately not always the case, as witnessed
15488      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15489      is used instead.  To work around that ambiguity, we treat
15490      the bounds as signed, and thus sign-extend their values, when
15491      the base type is signed.  */
15492   negative_mask =
15493     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15494   if (low.kind == PROP_CONST
15495       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15496     low.data.const_val |= negative_mask;
15497   if (high.kind == PROP_CONST
15498       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15499     high.data.const_val |= negative_mask;
15500
15501   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15502
15503   if (high_bound_is_count)
15504     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15505
15506   /* Ada expects an empty array on no boundary attributes.  */
15507   if (attr == NULL && cu->language != language_ada)
15508     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15509
15510   name = dwarf2_name (die, cu);
15511   if (name)
15512     TYPE_NAME (range_type) = name;
15513
15514   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15515   if (attr)
15516     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15517
15518   set_die_type (die, range_type, cu);
15519
15520   /* set_die_type should be already done.  */
15521   set_descriptive_type (range_type, die, cu);
15522
15523   return range_type;
15524 }
15525
15526 static struct type *
15527 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15528 {
15529   struct type *type;
15530
15531   /* For now, we only support the C meaning of an unspecified type: void.  */
15532
15533   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15534   TYPE_NAME (type) = dwarf2_name (die, cu);
15535
15536   return set_die_type (die, type, cu);
15537 }
15538
15539 /* Read a single die and all its descendents.  Set the die's sibling
15540    field to NULL; set other fields in the die correctly, and set all
15541    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15542    location of the info_ptr after reading all of those dies.  PARENT
15543    is the parent of the die in question.  */
15544
15545 static struct die_info *
15546 read_die_and_children (const struct die_reader_specs *reader,
15547                        const gdb_byte *info_ptr,
15548                        const gdb_byte **new_info_ptr,
15549                        struct die_info *parent)
15550 {
15551   struct die_info *die;
15552   const gdb_byte *cur_ptr;
15553   int has_children;
15554
15555   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15556   if (die == NULL)
15557     {
15558       *new_info_ptr = cur_ptr;
15559       return NULL;
15560     }
15561   store_in_ref_table (die, reader->cu);
15562
15563   if (has_children)
15564     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15565   else
15566     {
15567       die->child = NULL;
15568       *new_info_ptr = cur_ptr;
15569     }
15570
15571   die->sibling = NULL;
15572   die->parent = parent;
15573   return die;
15574 }
15575
15576 /* Read a die, all of its descendents, and all of its siblings; set
15577    all of the fields of all of the dies correctly.  Arguments are as
15578    in read_die_and_children.  */
15579
15580 static struct die_info *
15581 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15582                          const gdb_byte *info_ptr,
15583                          const gdb_byte **new_info_ptr,
15584                          struct die_info *parent)
15585 {
15586   struct die_info *first_die, *last_sibling;
15587   const gdb_byte *cur_ptr;
15588
15589   cur_ptr = info_ptr;
15590   first_die = last_sibling = NULL;
15591
15592   while (1)
15593     {
15594       struct die_info *die
15595         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15596
15597       if (die == NULL)
15598         {
15599           *new_info_ptr = cur_ptr;
15600           return first_die;
15601         }
15602
15603       if (!first_die)
15604         first_die = die;
15605       else
15606         last_sibling->sibling = die;
15607
15608       last_sibling = die;
15609     }
15610 }
15611
15612 /* Read a die, all of its descendents, and all of its siblings; set
15613    all of the fields of all of the dies correctly.  Arguments are as
15614    in read_die_and_children.
15615    This the main entry point for reading a DIE and all its children.  */
15616
15617 static struct die_info *
15618 read_die_and_siblings (const struct die_reader_specs *reader,
15619                        const gdb_byte *info_ptr,
15620                        const gdb_byte **new_info_ptr,
15621                        struct die_info *parent)
15622 {
15623   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15624                                                   new_info_ptr, parent);
15625
15626   if (dwarf_die_debug)
15627     {
15628       fprintf_unfiltered (gdb_stdlog,
15629                           "Read die from %s@0x%x of %s:\n",
15630                           get_section_name (reader->die_section),
15631                           (unsigned) (info_ptr - reader->die_section->buffer),
15632                           bfd_get_filename (reader->abfd));
15633       dump_die (die, dwarf_die_debug);
15634     }
15635
15636   return die;
15637 }
15638
15639 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15640    attributes.
15641    The caller is responsible for filling in the extra attributes
15642    and updating (*DIEP)->num_attrs.
15643    Set DIEP to point to a newly allocated die with its information,
15644    except for its child, sibling, and parent fields.
15645    Set HAS_CHILDREN to tell whether the die has children or not.  */
15646
15647 static const gdb_byte *
15648 read_full_die_1 (const struct die_reader_specs *reader,
15649                  struct die_info **diep, const gdb_byte *info_ptr,
15650                  int *has_children, int num_extra_attrs)
15651 {
15652   unsigned int abbrev_number, bytes_read, i;
15653   struct abbrev_info *abbrev;
15654   struct die_info *die;
15655   struct dwarf2_cu *cu = reader->cu;
15656   bfd *abfd = reader->abfd;
15657
15658   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15659   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15660   info_ptr += bytes_read;
15661   if (!abbrev_number)
15662     {
15663       *diep = NULL;
15664       *has_children = 0;
15665       return info_ptr;
15666     }
15667
15668   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15669   if (!abbrev)
15670     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15671            abbrev_number,
15672            bfd_get_filename (abfd));
15673
15674   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
15675   die->sect_off = sect_off;
15676   die->tag = abbrev->tag;
15677   die->abbrev = abbrev_number;
15678
15679   /* Make the result usable.
15680      The caller needs to update num_attrs after adding the extra
15681      attributes.  */
15682   die->num_attrs = abbrev->num_attrs;
15683
15684   for (i = 0; i < abbrev->num_attrs; ++i)
15685     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
15686                                info_ptr);
15687
15688   *diep = die;
15689   *has_children = abbrev->has_children;
15690   return info_ptr;
15691 }
15692
15693 /* Read a die and all its attributes.
15694    Set DIEP to point to a newly allocated die with its information,
15695    except for its child, sibling, and parent fields.
15696    Set HAS_CHILDREN to tell whether the die has children or not.  */
15697
15698 static const gdb_byte *
15699 read_full_die (const struct die_reader_specs *reader,
15700                struct die_info **diep, const gdb_byte *info_ptr,
15701                int *has_children)
15702 {
15703   const gdb_byte *result;
15704
15705   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
15706
15707   if (dwarf_die_debug)
15708     {
15709       fprintf_unfiltered (gdb_stdlog,
15710                           "Read die from %s@0x%x of %s:\n",
15711                           get_section_name (reader->die_section),
15712                           (unsigned) (info_ptr - reader->die_section->buffer),
15713                           bfd_get_filename (reader->abfd));
15714       dump_die (*diep, dwarf_die_debug);
15715     }
15716
15717   return result;
15718 }
15719 \f
15720 /* Abbreviation tables.
15721
15722    In DWARF version 2, the description of the debugging information is
15723    stored in a separate .debug_abbrev section.  Before we read any
15724    dies from a section we read in all abbreviations and install them
15725    in a hash table.  */
15726
15727 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
15728
15729 static struct abbrev_info *
15730 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
15731 {
15732   struct abbrev_info *abbrev;
15733
15734   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
15735   memset (abbrev, 0, sizeof (struct abbrev_info));
15736
15737   return abbrev;
15738 }
15739
15740 /* Add an abbreviation to the table.  */
15741
15742 static void
15743 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
15744                          unsigned int abbrev_number,
15745                          struct abbrev_info *abbrev)
15746 {
15747   unsigned int hash_number;
15748
15749   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15750   abbrev->next = abbrev_table->abbrevs[hash_number];
15751   abbrev_table->abbrevs[hash_number] = abbrev;
15752 }
15753
15754 /* Look up an abbrev in the table.
15755    Returns NULL if the abbrev is not found.  */
15756
15757 static struct abbrev_info *
15758 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
15759                             unsigned int abbrev_number)
15760 {
15761   unsigned int hash_number;
15762   struct abbrev_info *abbrev;
15763
15764   hash_number = abbrev_number % ABBREV_HASH_SIZE;
15765   abbrev = abbrev_table->abbrevs[hash_number];
15766
15767   while (abbrev)
15768     {
15769       if (abbrev->number == abbrev_number)
15770         return abbrev;
15771       abbrev = abbrev->next;
15772     }
15773   return NULL;
15774 }
15775
15776 /* Read in an abbrev table.  */
15777
15778 static struct abbrev_table *
15779 abbrev_table_read_table (struct dwarf2_section_info *section,
15780                          sect_offset sect_off)
15781 {
15782   struct objfile *objfile = dwarf2_per_objfile->objfile;
15783   bfd *abfd = get_section_bfd_owner (section);
15784   struct abbrev_table *abbrev_table;
15785   const gdb_byte *abbrev_ptr;
15786   struct abbrev_info *cur_abbrev;
15787   unsigned int abbrev_number, bytes_read, abbrev_name;
15788   unsigned int abbrev_form;
15789   struct attr_abbrev *cur_attrs;
15790   unsigned int allocated_attrs;
15791
15792   abbrev_table = XNEW (struct abbrev_table);
15793   abbrev_table->sect_off = sect_off;
15794   obstack_init (&abbrev_table->abbrev_obstack);
15795   abbrev_table->abbrevs =
15796     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
15797                ABBREV_HASH_SIZE);
15798   memset (abbrev_table->abbrevs, 0,
15799           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
15800
15801   dwarf2_read_section (objfile, section);
15802   abbrev_ptr = section->buffer + to_underlying (sect_off);
15803   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15804   abbrev_ptr += bytes_read;
15805
15806   allocated_attrs = ATTR_ALLOC_CHUNK;
15807   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
15808
15809   /* Loop until we reach an abbrev number of 0.  */
15810   while (abbrev_number)
15811     {
15812       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
15813
15814       /* read in abbrev header */
15815       cur_abbrev->number = abbrev_number;
15816       cur_abbrev->tag
15817         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15818       abbrev_ptr += bytes_read;
15819       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
15820       abbrev_ptr += 1;
15821
15822       /* now read in declarations */
15823       for (;;)
15824         {
15825           LONGEST implicit_const;
15826
15827           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15828           abbrev_ptr += bytes_read;
15829           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15830           abbrev_ptr += bytes_read;
15831           if (abbrev_form == DW_FORM_implicit_const)
15832             {
15833               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
15834                                                    &bytes_read);
15835               abbrev_ptr += bytes_read;
15836             }
15837           else
15838             {
15839               /* Initialize it due to a false compiler warning.  */
15840               implicit_const = -1;
15841             }
15842
15843           if (abbrev_name == 0)
15844             break;
15845
15846           if (cur_abbrev->num_attrs == allocated_attrs)
15847             {
15848               allocated_attrs += ATTR_ALLOC_CHUNK;
15849               cur_attrs
15850                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
15851             }
15852
15853           cur_attrs[cur_abbrev->num_attrs].name
15854             = (enum dwarf_attribute) abbrev_name;
15855           cur_attrs[cur_abbrev->num_attrs].form
15856             = (enum dwarf_form) abbrev_form;
15857           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
15858           ++cur_abbrev->num_attrs;
15859         }
15860
15861       cur_abbrev->attrs =
15862         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
15863                    cur_abbrev->num_attrs);
15864       memcpy (cur_abbrev->attrs, cur_attrs,
15865               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
15866
15867       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
15868
15869       /* Get next abbreviation.
15870          Under Irix6 the abbreviations for a compilation unit are not
15871          always properly terminated with an abbrev number of 0.
15872          Exit loop if we encounter an abbreviation which we have
15873          already read (which means we are about to read the abbreviations
15874          for the next compile unit) or if the end of the abbreviation
15875          table is reached.  */
15876       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
15877         break;
15878       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
15879       abbrev_ptr += bytes_read;
15880       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
15881         break;
15882     }
15883
15884   xfree (cur_attrs);
15885   return abbrev_table;
15886 }
15887
15888 /* Free the resources held by ABBREV_TABLE.  */
15889
15890 static void
15891 abbrev_table_free (struct abbrev_table *abbrev_table)
15892 {
15893   obstack_free (&abbrev_table->abbrev_obstack, NULL);
15894   xfree (abbrev_table);
15895 }
15896
15897 /* Same as abbrev_table_free but as a cleanup.
15898    We pass in a pointer to the pointer to the table so that we can
15899    set the pointer to NULL when we're done.  It also simplifies
15900    build_type_psymtabs_1.  */
15901
15902 static void
15903 abbrev_table_free_cleanup (void *table_ptr)
15904 {
15905   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
15906
15907   if (*abbrev_table_ptr != NULL)
15908     abbrev_table_free (*abbrev_table_ptr);
15909   *abbrev_table_ptr = NULL;
15910 }
15911
15912 /* Read the abbrev table for CU from ABBREV_SECTION.  */
15913
15914 static void
15915 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
15916                      struct dwarf2_section_info *abbrev_section)
15917 {
15918   cu->abbrev_table =
15919     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
15920 }
15921
15922 /* Release the memory used by the abbrev table for a compilation unit.  */
15923
15924 static void
15925 dwarf2_free_abbrev_table (void *ptr_to_cu)
15926 {
15927   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
15928
15929   if (cu->abbrev_table != NULL)
15930     abbrev_table_free (cu->abbrev_table);
15931   /* Set this to NULL so that we SEGV if we try to read it later,
15932      and also because free_comp_unit verifies this is NULL.  */
15933   cu->abbrev_table = NULL;
15934 }
15935 \f
15936 /* Returns nonzero if TAG represents a type that we might generate a partial
15937    symbol for.  */
15938
15939 static int
15940 is_type_tag_for_partial (int tag)
15941 {
15942   switch (tag)
15943     {
15944 #if 0
15945     /* Some types that would be reasonable to generate partial symbols for,
15946        that we don't at present.  */
15947     case DW_TAG_array_type:
15948     case DW_TAG_file_type:
15949     case DW_TAG_ptr_to_member_type:
15950     case DW_TAG_set_type:
15951     case DW_TAG_string_type:
15952     case DW_TAG_subroutine_type:
15953 #endif
15954     case DW_TAG_base_type:
15955     case DW_TAG_class_type:
15956     case DW_TAG_interface_type:
15957     case DW_TAG_enumeration_type:
15958     case DW_TAG_structure_type:
15959     case DW_TAG_subrange_type:
15960     case DW_TAG_typedef:
15961     case DW_TAG_union_type:
15962       return 1;
15963     default:
15964       return 0;
15965     }
15966 }
15967
15968 /* Load all DIEs that are interesting for partial symbols into memory.  */
15969
15970 static struct partial_die_info *
15971 load_partial_dies (const struct die_reader_specs *reader,
15972                    const gdb_byte *info_ptr, int building_psymtab)
15973 {
15974   struct dwarf2_cu *cu = reader->cu;
15975   struct objfile *objfile = cu->objfile;
15976   struct partial_die_info *part_die;
15977   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
15978   struct abbrev_info *abbrev;
15979   unsigned int bytes_read;
15980   unsigned int load_all = 0;
15981   int nesting_level = 1;
15982
15983   parent_die = NULL;
15984   last_die = NULL;
15985
15986   gdb_assert (cu->per_cu != NULL);
15987   if (cu->per_cu->load_all_dies)
15988     load_all = 1;
15989
15990   cu->partial_dies
15991     = htab_create_alloc_ex (cu->header.length / 12,
15992                             partial_die_hash,
15993                             partial_die_eq,
15994                             NULL,
15995                             &cu->comp_unit_obstack,
15996                             hashtab_obstack_allocate,
15997                             dummy_obstack_deallocate);
15998
15999   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16000
16001   while (1)
16002     {
16003       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16004
16005       /* A NULL abbrev means the end of a series of children.  */
16006       if (abbrev == NULL)
16007         {
16008           if (--nesting_level == 0)
16009             {
16010               /* PART_DIE was probably the last thing allocated on the
16011                  comp_unit_obstack, so we could call obstack_free
16012                  here.  We don't do that because the waste is small,
16013                  and will be cleaned up when we're done with this
16014                  compilation unit.  This way, we're also more robust
16015                  against other users of the comp_unit_obstack.  */
16016               return first_die;
16017             }
16018           info_ptr += bytes_read;
16019           last_die = parent_die;
16020           parent_die = parent_die->die_parent;
16021           continue;
16022         }
16023
16024       /* Check for template arguments.  We never save these; if
16025          they're seen, we just mark the parent, and go on our way.  */
16026       if (parent_die != NULL
16027           && cu->language == language_cplus
16028           && (abbrev->tag == DW_TAG_template_type_param
16029               || abbrev->tag == DW_TAG_template_value_param))
16030         {
16031           parent_die->has_template_arguments = 1;
16032
16033           if (!load_all)
16034             {
16035               /* We don't need a partial DIE for the template argument.  */
16036               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16037               continue;
16038             }
16039         }
16040
16041       /* We only recurse into c++ subprograms looking for template arguments.
16042          Skip their other children.  */
16043       if (!load_all
16044           && cu->language == language_cplus
16045           && parent_die != NULL
16046           && parent_die->tag == DW_TAG_subprogram)
16047         {
16048           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16049           continue;
16050         }
16051
16052       /* Check whether this DIE is interesting enough to save.  Normally
16053          we would not be interested in members here, but there may be
16054          later variables referencing them via DW_AT_specification (for
16055          static members).  */
16056       if (!load_all
16057           && !is_type_tag_for_partial (abbrev->tag)
16058           && abbrev->tag != DW_TAG_constant
16059           && abbrev->tag != DW_TAG_enumerator
16060           && abbrev->tag != DW_TAG_subprogram
16061           && abbrev->tag != DW_TAG_lexical_block
16062           && abbrev->tag != DW_TAG_variable
16063           && abbrev->tag != DW_TAG_namespace
16064           && abbrev->tag != DW_TAG_module
16065           && abbrev->tag != DW_TAG_member
16066           && abbrev->tag != DW_TAG_imported_unit
16067           && abbrev->tag != DW_TAG_imported_declaration)
16068         {
16069           /* Otherwise we skip to the next sibling, if any.  */
16070           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16071           continue;
16072         }
16073
16074       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16075                                    info_ptr);
16076
16077       /* This two-pass algorithm for processing partial symbols has a
16078          high cost in cache pressure.  Thus, handle some simple cases
16079          here which cover the majority of C partial symbols.  DIEs
16080          which neither have specification tags in them, nor could have
16081          specification tags elsewhere pointing at them, can simply be
16082          processed and discarded.
16083
16084          This segment is also optional; scan_partial_symbols and
16085          add_partial_symbol will handle these DIEs if we chain
16086          them in normally.  When compilers which do not emit large
16087          quantities of duplicate debug information are more common,
16088          this code can probably be removed.  */
16089
16090       /* Any complete simple types at the top level (pretty much all
16091          of them, for a language without namespaces), can be processed
16092          directly.  */
16093       if (parent_die == NULL
16094           && part_die->has_specification == 0
16095           && part_die->is_declaration == 0
16096           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16097               || part_die->tag == DW_TAG_base_type
16098               || part_die->tag == DW_TAG_subrange_type))
16099         {
16100           if (building_psymtab && part_die->name != NULL)
16101             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16102                                  VAR_DOMAIN, LOC_TYPEDEF,
16103                                  &objfile->static_psymbols,
16104                                  0, cu->language, objfile);
16105           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16106           continue;
16107         }
16108
16109       /* The exception for DW_TAG_typedef with has_children above is
16110          a workaround of GCC PR debug/47510.  In the case of this complaint
16111          type_name_no_tag_or_error will error on such types later.
16112
16113          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16114          it could not find the child DIEs referenced later, this is checked
16115          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16116
16117       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16118         complaint (&symfile_complaints,
16119                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16120                      "- DIE at 0x%x [in module %s]"),
16121                    to_underlying (part_die->sect_off), objfile_name (objfile));
16122
16123       /* If we're at the second level, and we're an enumerator, and
16124          our parent has no specification (meaning possibly lives in a
16125          namespace elsewhere), then we can add the partial symbol now
16126          instead of queueing it.  */
16127       if (part_die->tag == DW_TAG_enumerator
16128           && parent_die != NULL
16129           && parent_die->die_parent == NULL
16130           && parent_die->tag == DW_TAG_enumeration_type
16131           && parent_die->has_specification == 0)
16132         {
16133           if (part_die->name == NULL)
16134             complaint (&symfile_complaints,
16135                        _("malformed enumerator DIE ignored"));
16136           else if (building_psymtab)
16137             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16138                                  VAR_DOMAIN, LOC_CONST,
16139                                  cu->language == language_cplus
16140                                  ? &objfile->global_psymbols
16141                                  : &objfile->static_psymbols,
16142                                  0, cu->language, objfile);
16143
16144           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16145           continue;
16146         }
16147
16148       /* We'll save this DIE so link it in.  */
16149       part_die->die_parent = parent_die;
16150       part_die->die_sibling = NULL;
16151       part_die->die_child = NULL;
16152
16153       if (last_die && last_die == parent_die)
16154         last_die->die_child = part_die;
16155       else if (last_die)
16156         last_die->die_sibling = part_die;
16157
16158       last_die = part_die;
16159
16160       if (first_die == NULL)
16161         first_die = part_die;
16162
16163       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16164          find interesting need to be in the hash table, because we
16165          also have the parent/sibling/child chains; only those that we
16166          might refer to by offset later during partial symbol reading.
16167
16168          For now this means things that might have be the target of a
16169          DW_AT_specification, DW_AT_abstract_origin, or
16170          DW_AT_extension.  DW_AT_extension will refer only to
16171          namespaces; DW_AT_abstract_origin refers to functions (and
16172          many things under the function DIE, but we do not recurse
16173          into function DIEs during partial symbol reading) and
16174          possibly variables as well; DW_AT_specification refers to
16175          declarations.  Declarations ought to have the DW_AT_declaration
16176          flag.  It happens that GCC forgets to put it in sometimes, but
16177          only for functions, not for types.
16178
16179          Adding more things than necessary to the hash table is harmless
16180          except for the performance cost.  Adding too few will result in
16181          wasted time in find_partial_die, when we reread the compilation
16182          unit with load_all_dies set.  */
16183
16184       if (load_all
16185           || abbrev->tag == DW_TAG_constant
16186           || abbrev->tag == DW_TAG_subprogram
16187           || abbrev->tag == DW_TAG_variable
16188           || abbrev->tag == DW_TAG_namespace
16189           || part_die->is_declaration)
16190         {
16191           void **slot;
16192
16193           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16194                                            to_underlying (part_die->sect_off),
16195                                            INSERT);
16196           *slot = part_die;
16197         }
16198
16199       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16200
16201       /* For some DIEs we want to follow their children (if any).  For C
16202          we have no reason to follow the children of structures; for other
16203          languages we have to, so that we can get at method physnames
16204          to infer fully qualified class names, for DW_AT_specification,
16205          and for C++ template arguments.  For C++, we also look one level
16206          inside functions to find template arguments (if the name of the
16207          function does not already contain the template arguments).
16208
16209          For Ada, we need to scan the children of subprograms and lexical
16210          blocks as well because Ada allows the definition of nested
16211          entities that could be interesting for the debugger, such as
16212          nested subprograms for instance.  */
16213       if (last_die->has_children
16214           && (load_all
16215               || last_die->tag == DW_TAG_namespace
16216               || last_die->tag == DW_TAG_module
16217               || last_die->tag == DW_TAG_enumeration_type
16218               || (cu->language == language_cplus
16219                   && last_die->tag == DW_TAG_subprogram
16220                   && (last_die->name == NULL
16221                       || strchr (last_die->name, '<') == NULL))
16222               || (cu->language != language_c
16223                   && (last_die->tag == DW_TAG_class_type
16224                       || last_die->tag == DW_TAG_interface_type
16225                       || last_die->tag == DW_TAG_structure_type
16226                       || last_die->tag == DW_TAG_union_type))
16227               || (cu->language == language_ada
16228                   && (last_die->tag == DW_TAG_subprogram
16229                       || last_die->tag == DW_TAG_lexical_block))))
16230         {
16231           nesting_level++;
16232           parent_die = last_die;
16233           continue;
16234         }
16235
16236       /* Otherwise we skip to the next sibling, if any.  */
16237       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16238
16239       /* Back to the top, do it again.  */
16240     }
16241 }
16242
16243 /* Read a minimal amount of information into the minimal die structure.  */
16244
16245 static const gdb_byte *
16246 read_partial_die (const struct die_reader_specs *reader,
16247                   struct partial_die_info *part_die,
16248                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16249                   const gdb_byte *info_ptr)
16250 {
16251   struct dwarf2_cu *cu = reader->cu;
16252   struct objfile *objfile = cu->objfile;
16253   const gdb_byte *buffer = reader->buffer;
16254   unsigned int i;
16255   struct attribute attr;
16256   int has_low_pc_attr = 0;
16257   int has_high_pc_attr = 0;
16258   int high_pc_relative = 0;
16259
16260   memset (part_die, 0, sizeof (struct partial_die_info));
16261
16262   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16263
16264   info_ptr += abbrev_len;
16265
16266   if (abbrev == NULL)
16267     return info_ptr;
16268
16269   part_die->tag = abbrev->tag;
16270   part_die->has_children = abbrev->has_children;
16271
16272   for (i = 0; i < abbrev->num_attrs; ++i)
16273     {
16274       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16275
16276       /* Store the data if it is of an attribute we want to keep in a
16277          partial symbol table.  */
16278       switch (attr.name)
16279         {
16280         case DW_AT_name:
16281           switch (part_die->tag)
16282             {
16283             case DW_TAG_compile_unit:
16284             case DW_TAG_partial_unit:
16285             case DW_TAG_type_unit:
16286               /* Compilation units have a DW_AT_name that is a filename, not
16287                  a source language identifier.  */
16288             case DW_TAG_enumeration_type:
16289             case DW_TAG_enumerator:
16290               /* These tags always have simple identifiers already; no need
16291                  to canonicalize them.  */
16292               part_die->name = DW_STRING (&attr);
16293               break;
16294             default:
16295               part_die->name
16296                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16297                                             &objfile->per_bfd->storage_obstack);
16298               break;
16299             }
16300           break;
16301         case DW_AT_linkage_name:
16302         case DW_AT_MIPS_linkage_name:
16303           /* Note that both forms of linkage name might appear.  We
16304              assume they will be the same, and we only store the last
16305              one we see.  */
16306           if (cu->language == language_ada)
16307             part_die->name = DW_STRING (&attr);
16308           part_die->linkage_name = DW_STRING (&attr);
16309           break;
16310         case DW_AT_low_pc:
16311           has_low_pc_attr = 1;
16312           part_die->lowpc = attr_value_as_address (&attr);
16313           break;
16314         case DW_AT_high_pc:
16315           has_high_pc_attr = 1;
16316           part_die->highpc = attr_value_as_address (&attr);
16317           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16318                 high_pc_relative = 1;
16319           break;
16320         case DW_AT_location:
16321           /* Support the .debug_loc offsets.  */
16322           if (attr_form_is_block (&attr))
16323             {
16324                part_die->d.locdesc = DW_BLOCK (&attr);
16325             }
16326           else if (attr_form_is_section_offset (&attr))
16327             {
16328               dwarf2_complex_location_expr_complaint ();
16329             }
16330           else
16331             {
16332               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16333                                                      "partial symbol information");
16334             }
16335           break;
16336         case DW_AT_external:
16337           part_die->is_external = DW_UNSND (&attr);
16338           break;
16339         case DW_AT_declaration:
16340           part_die->is_declaration = DW_UNSND (&attr);
16341           break;
16342         case DW_AT_type:
16343           part_die->has_type = 1;
16344           break;
16345         case DW_AT_abstract_origin:
16346         case DW_AT_specification:
16347         case DW_AT_extension:
16348           part_die->has_specification = 1;
16349           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16350           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16351                                    || cu->per_cu->is_dwz);
16352           break;
16353         case DW_AT_sibling:
16354           /* Ignore absolute siblings, they might point outside of
16355              the current compile unit.  */
16356           if (attr.form == DW_FORM_ref_addr)
16357             complaint (&symfile_complaints,
16358                        _("ignoring absolute DW_AT_sibling"));
16359           else
16360             {
16361               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16362               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16363
16364               if (sibling_ptr < info_ptr)
16365                 complaint (&symfile_complaints,
16366                            _("DW_AT_sibling points backwards"));
16367               else if (sibling_ptr > reader->buffer_end)
16368                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16369               else
16370                 part_die->sibling = sibling_ptr;
16371             }
16372           break;
16373         case DW_AT_byte_size:
16374           part_die->has_byte_size = 1;
16375           break;
16376         case DW_AT_const_value:
16377           part_die->has_const_value = 1;
16378           break;
16379         case DW_AT_calling_convention:
16380           /* DWARF doesn't provide a way to identify a program's source-level
16381              entry point.  DW_AT_calling_convention attributes are only meant
16382              to describe functions' calling conventions.
16383
16384              However, because it's a necessary piece of information in
16385              Fortran, and before DWARF 4 DW_CC_program was the only
16386              piece of debugging information whose definition refers to
16387              a 'main program' at all, several compilers marked Fortran
16388              main programs with DW_CC_program --- even when those
16389              functions use the standard calling conventions.
16390
16391              Although DWARF now specifies a way to provide this
16392              information, we support this practice for backward
16393              compatibility.  */
16394           if (DW_UNSND (&attr) == DW_CC_program
16395               && cu->language == language_fortran)
16396             part_die->main_subprogram = 1;
16397           break;
16398         case DW_AT_inline:
16399           if (DW_UNSND (&attr) == DW_INL_inlined
16400               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16401             part_die->may_be_inlined = 1;
16402           break;
16403
16404         case DW_AT_import:
16405           if (part_die->tag == DW_TAG_imported_unit)
16406             {
16407               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16408               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16409                                   || cu->per_cu->is_dwz);
16410             }
16411           break;
16412
16413         case DW_AT_main_subprogram:
16414           part_die->main_subprogram = DW_UNSND (&attr);
16415           break;
16416
16417         default:
16418           break;
16419         }
16420     }
16421
16422   if (high_pc_relative)
16423     part_die->highpc += part_die->lowpc;
16424
16425   if (has_low_pc_attr && has_high_pc_attr)
16426     {
16427       /* When using the GNU linker, .gnu.linkonce. sections are used to
16428          eliminate duplicate copies of functions and vtables and such.
16429          The linker will arbitrarily choose one and discard the others.
16430          The AT_*_pc values for such functions refer to local labels in
16431          these sections.  If the section from that file was discarded, the
16432          labels are not in the output, so the relocs get a value of 0.
16433          If this is a discarded function, mark the pc bounds as invalid,
16434          so that GDB will ignore it.  */
16435       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16436         {
16437           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16438
16439           complaint (&symfile_complaints,
16440                      _("DW_AT_low_pc %s is zero "
16441                        "for DIE at 0x%x [in module %s]"),
16442                      paddress (gdbarch, part_die->lowpc),
16443                      to_underlying (part_die->sect_off), objfile_name (objfile));
16444         }
16445       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16446       else if (part_die->lowpc >= part_die->highpc)
16447         {
16448           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16449
16450           complaint (&symfile_complaints,
16451                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16452                        "for DIE at 0x%x [in module %s]"),
16453                      paddress (gdbarch, part_die->lowpc),
16454                      paddress (gdbarch, part_die->highpc),
16455                      to_underlying (part_die->sect_off),
16456                      objfile_name (objfile));
16457         }
16458       else
16459         part_die->has_pc_info = 1;
16460     }
16461
16462   return info_ptr;
16463 }
16464
16465 /* Find a cached partial DIE at OFFSET in CU.  */
16466
16467 static struct partial_die_info *
16468 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16469 {
16470   struct partial_die_info *lookup_die = NULL;
16471   struct partial_die_info part_die;
16472
16473   part_die.sect_off = sect_off;
16474   lookup_die = ((struct partial_die_info *)
16475                 htab_find_with_hash (cu->partial_dies, &part_die,
16476                                      to_underlying (sect_off)));
16477
16478   return lookup_die;
16479 }
16480
16481 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16482    except in the case of .debug_types DIEs which do not reference
16483    outside their CU (they do however referencing other types via
16484    DW_FORM_ref_sig8).  */
16485
16486 static struct partial_die_info *
16487 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16488 {
16489   struct objfile *objfile = cu->objfile;
16490   struct dwarf2_per_cu_data *per_cu = NULL;
16491   struct partial_die_info *pd = NULL;
16492
16493   if (offset_in_dwz == cu->per_cu->is_dwz
16494       && offset_in_cu_p (&cu->header, sect_off))
16495     {
16496       pd = find_partial_die_in_comp_unit (sect_off, cu);
16497       if (pd != NULL)
16498         return pd;
16499       /* We missed recording what we needed.
16500          Load all dies and try again.  */
16501       per_cu = cu->per_cu;
16502     }
16503   else
16504     {
16505       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16506       if (cu->per_cu->is_debug_types)
16507         {
16508           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16509                    " external reference to offset 0x%x [in module %s].\n"),
16510                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16511                  bfd_get_filename (objfile->obfd));
16512         }
16513       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16514                                                  objfile);
16515
16516       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16517         load_partial_comp_unit (per_cu);
16518
16519       per_cu->cu->last_used = 0;
16520       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16521     }
16522
16523   /* If we didn't find it, and not all dies have been loaded,
16524      load them all and try again.  */
16525
16526   if (pd == NULL && per_cu->load_all_dies == 0)
16527     {
16528       per_cu->load_all_dies = 1;
16529
16530       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16531          THIS_CU->cu may already be in use.  So we can't just free it and
16532          replace its DIEs with the ones we read in.  Instead, we leave those
16533          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16534          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16535          set.  */
16536       load_partial_comp_unit (per_cu);
16537
16538       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16539     }
16540
16541   if (pd == NULL)
16542     internal_error (__FILE__, __LINE__,
16543                     _("could not find partial DIE 0x%x "
16544                       "in cache [from module %s]\n"),
16545                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16546   return pd;
16547 }
16548
16549 /* See if we can figure out if the class lives in a namespace.  We do
16550    this by looking for a member function; its demangled name will
16551    contain namespace info, if there is any.  */
16552
16553 static void
16554 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16555                                   struct dwarf2_cu *cu)
16556 {
16557   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16558      what template types look like, because the demangler
16559      frequently doesn't give the same name as the debug info.  We
16560      could fix this by only using the demangled name to get the
16561      prefix (but see comment in read_structure_type).  */
16562
16563   struct partial_die_info *real_pdi;
16564   struct partial_die_info *child_pdi;
16565
16566   /* If this DIE (this DIE's specification, if any) has a parent, then
16567      we should not do this.  We'll prepend the parent's fully qualified
16568      name when we create the partial symbol.  */
16569
16570   real_pdi = struct_pdi;
16571   while (real_pdi->has_specification)
16572     real_pdi = find_partial_die (real_pdi->spec_offset,
16573                                  real_pdi->spec_is_dwz, cu);
16574
16575   if (real_pdi->die_parent != NULL)
16576     return;
16577
16578   for (child_pdi = struct_pdi->die_child;
16579        child_pdi != NULL;
16580        child_pdi = child_pdi->die_sibling)
16581     {
16582       if (child_pdi->tag == DW_TAG_subprogram
16583           && child_pdi->linkage_name != NULL)
16584         {
16585           char *actual_class_name
16586             = language_class_name_from_physname (cu->language_defn,
16587                                                  child_pdi->linkage_name);
16588           if (actual_class_name != NULL)
16589             {
16590               struct_pdi->name
16591                 = ((const char *)
16592                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16593                                   actual_class_name,
16594                                   strlen (actual_class_name)));
16595               xfree (actual_class_name);
16596             }
16597           break;
16598         }
16599     }
16600 }
16601
16602 /* Adjust PART_DIE before generating a symbol for it.  This function
16603    may set the is_external flag or change the DIE's name.  */
16604
16605 static void
16606 fixup_partial_die (struct partial_die_info *part_die,
16607                    struct dwarf2_cu *cu)
16608 {
16609   /* Once we've fixed up a die, there's no point in doing so again.
16610      This also avoids a memory leak if we were to call
16611      guess_partial_die_structure_name multiple times.  */
16612   if (part_die->fixup_called)
16613     return;
16614
16615   /* If we found a reference attribute and the DIE has no name, try
16616      to find a name in the referred to DIE.  */
16617
16618   if (part_die->name == NULL && part_die->has_specification)
16619     {
16620       struct partial_die_info *spec_die;
16621
16622       spec_die = find_partial_die (part_die->spec_offset,
16623                                    part_die->spec_is_dwz, cu);
16624
16625       fixup_partial_die (spec_die, cu);
16626
16627       if (spec_die->name)
16628         {
16629           part_die->name = spec_die->name;
16630
16631           /* Copy DW_AT_external attribute if it is set.  */
16632           if (spec_die->is_external)
16633             part_die->is_external = spec_die->is_external;
16634         }
16635     }
16636
16637   /* Set default names for some unnamed DIEs.  */
16638
16639   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16640     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16641
16642   /* If there is no parent die to provide a namespace, and there are
16643      children, see if we can determine the namespace from their linkage
16644      name.  */
16645   if (cu->language == language_cplus
16646       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16647       && part_die->die_parent == NULL
16648       && part_die->has_children
16649       && (part_die->tag == DW_TAG_class_type
16650           || part_die->tag == DW_TAG_structure_type
16651           || part_die->tag == DW_TAG_union_type))
16652     guess_partial_die_structure_name (part_die, cu);
16653
16654   /* GCC might emit a nameless struct or union that has a linkage
16655      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16656   if (part_die->name == NULL
16657       && (part_die->tag == DW_TAG_class_type
16658           || part_die->tag == DW_TAG_interface_type
16659           || part_die->tag == DW_TAG_structure_type
16660           || part_die->tag == DW_TAG_union_type)
16661       && part_die->linkage_name != NULL)
16662     {
16663       char *demangled;
16664
16665       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16666       if (demangled)
16667         {
16668           const char *base;
16669
16670           /* Strip any leading namespaces/classes, keep only the base name.
16671              DW_AT_name for named DIEs does not contain the prefixes.  */
16672           base = strrchr (demangled, ':');
16673           if (base && base > demangled && base[-1] == ':')
16674             base++;
16675           else
16676             base = demangled;
16677
16678           part_die->name
16679             = ((const char *)
16680                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16681                               base, strlen (base)));
16682           xfree (demangled);
16683         }
16684     }
16685
16686   part_die->fixup_called = 1;
16687 }
16688
16689 /* Read an attribute value described by an attribute form.  */
16690
16691 static const gdb_byte *
16692 read_attribute_value (const struct die_reader_specs *reader,
16693                       struct attribute *attr, unsigned form,
16694                       LONGEST implicit_const, const gdb_byte *info_ptr)
16695 {
16696   struct dwarf2_cu *cu = reader->cu;
16697   struct objfile *objfile = cu->objfile;
16698   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16699   bfd *abfd = reader->abfd;
16700   struct comp_unit_head *cu_header = &cu->header;
16701   unsigned int bytes_read;
16702   struct dwarf_block *blk;
16703
16704   attr->form = (enum dwarf_form) form;
16705   switch (form)
16706     {
16707     case DW_FORM_ref_addr:
16708       if (cu->header.version == 2)
16709         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16710       else
16711         DW_UNSND (attr) = read_offset (abfd, info_ptr,
16712                                        &cu->header, &bytes_read);
16713       info_ptr += bytes_read;
16714       break;
16715     case DW_FORM_GNU_ref_alt:
16716       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16717       info_ptr += bytes_read;
16718       break;
16719     case DW_FORM_addr:
16720       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
16721       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
16722       info_ptr += bytes_read;
16723       break;
16724     case DW_FORM_block2:
16725       blk = dwarf_alloc_block (cu);
16726       blk->size = read_2_bytes (abfd, info_ptr);
16727       info_ptr += 2;
16728       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16729       info_ptr += blk->size;
16730       DW_BLOCK (attr) = blk;
16731       break;
16732     case DW_FORM_block4:
16733       blk = dwarf_alloc_block (cu);
16734       blk->size = read_4_bytes (abfd, info_ptr);
16735       info_ptr += 4;
16736       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16737       info_ptr += blk->size;
16738       DW_BLOCK (attr) = blk;
16739       break;
16740     case DW_FORM_data2:
16741       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
16742       info_ptr += 2;
16743       break;
16744     case DW_FORM_data4:
16745       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
16746       info_ptr += 4;
16747       break;
16748     case DW_FORM_data8:
16749       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
16750       info_ptr += 8;
16751       break;
16752     case DW_FORM_data16:
16753       blk = dwarf_alloc_block (cu);
16754       blk->size = 16;
16755       blk->data = read_n_bytes (abfd, info_ptr, 16);
16756       info_ptr += 16;
16757       DW_BLOCK (attr) = blk;
16758       break;
16759     case DW_FORM_sec_offset:
16760       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
16761       info_ptr += bytes_read;
16762       break;
16763     case DW_FORM_string:
16764       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
16765       DW_STRING_IS_CANONICAL (attr) = 0;
16766       info_ptr += bytes_read;
16767       break;
16768     case DW_FORM_strp:
16769       if (!cu->per_cu->is_dwz)
16770         {
16771           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
16772                                                    &bytes_read);
16773           DW_STRING_IS_CANONICAL (attr) = 0;
16774           info_ptr += bytes_read;
16775           break;
16776         }
16777       /* FALLTHROUGH */
16778     case DW_FORM_line_strp:
16779       if (!cu->per_cu->is_dwz)
16780         {
16781           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
16782                                                         cu_header, &bytes_read);
16783           DW_STRING_IS_CANONICAL (attr) = 0;
16784           info_ptr += bytes_read;
16785           break;
16786         }
16787       /* FALLTHROUGH */
16788     case DW_FORM_GNU_strp_alt:
16789       {
16790         struct dwz_file *dwz = dwarf2_get_dwz_file ();
16791         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
16792                                           &bytes_read);
16793
16794         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
16795         DW_STRING_IS_CANONICAL (attr) = 0;
16796         info_ptr += bytes_read;
16797       }
16798       break;
16799     case DW_FORM_exprloc:
16800     case DW_FORM_block:
16801       blk = dwarf_alloc_block (cu);
16802       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16803       info_ptr += bytes_read;
16804       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16805       info_ptr += blk->size;
16806       DW_BLOCK (attr) = blk;
16807       break;
16808     case DW_FORM_block1:
16809       blk = dwarf_alloc_block (cu);
16810       blk->size = read_1_byte (abfd, info_ptr);
16811       info_ptr += 1;
16812       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
16813       info_ptr += blk->size;
16814       DW_BLOCK (attr) = blk;
16815       break;
16816     case DW_FORM_data1:
16817       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16818       info_ptr += 1;
16819       break;
16820     case DW_FORM_flag:
16821       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
16822       info_ptr += 1;
16823       break;
16824     case DW_FORM_flag_present:
16825       DW_UNSND (attr) = 1;
16826       break;
16827     case DW_FORM_sdata:
16828       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16829       info_ptr += bytes_read;
16830       break;
16831     case DW_FORM_udata:
16832       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16833       info_ptr += bytes_read;
16834       break;
16835     case DW_FORM_ref1:
16836       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16837                          + read_1_byte (abfd, info_ptr));
16838       info_ptr += 1;
16839       break;
16840     case DW_FORM_ref2:
16841       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16842                          + read_2_bytes (abfd, info_ptr));
16843       info_ptr += 2;
16844       break;
16845     case DW_FORM_ref4:
16846       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16847                          + read_4_bytes (abfd, info_ptr));
16848       info_ptr += 4;
16849       break;
16850     case DW_FORM_ref8:
16851       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16852                          + read_8_bytes (abfd, info_ptr));
16853       info_ptr += 8;
16854       break;
16855     case DW_FORM_ref_sig8:
16856       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
16857       info_ptr += 8;
16858       break;
16859     case DW_FORM_ref_udata:
16860       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
16861                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
16862       info_ptr += bytes_read;
16863       break;
16864     case DW_FORM_indirect:
16865       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16866       info_ptr += bytes_read;
16867       if (form == DW_FORM_implicit_const)
16868         {
16869           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
16870           info_ptr += bytes_read;
16871         }
16872       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
16873                                        info_ptr);
16874       break;
16875     case DW_FORM_implicit_const:
16876       DW_SND (attr) = implicit_const;
16877       break;
16878     case DW_FORM_GNU_addr_index:
16879       if (reader->dwo_file == NULL)
16880         {
16881           /* For now flag a hard error.
16882              Later we can turn this into a complaint.  */
16883           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16884                  dwarf_form_name (form),
16885                  bfd_get_filename (abfd));
16886         }
16887       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
16888       info_ptr += bytes_read;
16889       break;
16890     case DW_FORM_GNU_str_index:
16891       if (reader->dwo_file == NULL)
16892         {
16893           /* For now flag a hard error.
16894              Later we can turn this into a complaint if warranted.  */
16895           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
16896                  dwarf_form_name (form),
16897                  bfd_get_filename (abfd));
16898         }
16899       {
16900         ULONGEST str_index =
16901           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16902
16903         DW_STRING (attr) = read_str_index (reader, str_index);
16904         DW_STRING_IS_CANONICAL (attr) = 0;
16905         info_ptr += bytes_read;
16906       }
16907       break;
16908     default:
16909       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
16910              dwarf_form_name (form),
16911              bfd_get_filename (abfd));
16912     }
16913
16914   /* Super hack.  */
16915   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
16916     attr->form = DW_FORM_GNU_ref_alt;
16917
16918   /* We have seen instances where the compiler tried to emit a byte
16919      size attribute of -1 which ended up being encoded as an unsigned
16920      0xffffffff.  Although 0xffffffff is technically a valid size value,
16921      an object of this size seems pretty unlikely so we can relatively
16922      safely treat these cases as if the size attribute was invalid and
16923      treat them as zero by default.  */
16924   if (attr->name == DW_AT_byte_size
16925       && form == DW_FORM_data4
16926       && DW_UNSND (attr) >= 0xffffffff)
16927     {
16928       complaint
16929         (&symfile_complaints,
16930          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
16931          hex_string (DW_UNSND (attr)));
16932       DW_UNSND (attr) = 0;
16933     }
16934
16935   return info_ptr;
16936 }
16937
16938 /* Read an attribute described by an abbreviated attribute.  */
16939
16940 static const gdb_byte *
16941 read_attribute (const struct die_reader_specs *reader,
16942                 struct attribute *attr, struct attr_abbrev *abbrev,
16943                 const gdb_byte *info_ptr)
16944 {
16945   attr->name = abbrev->name;
16946   return read_attribute_value (reader, attr, abbrev->form,
16947                                abbrev->implicit_const, info_ptr);
16948 }
16949
16950 /* Read dwarf information from a buffer.  */
16951
16952 static unsigned int
16953 read_1_byte (bfd *abfd, const gdb_byte *buf)
16954 {
16955   return bfd_get_8 (abfd, buf);
16956 }
16957
16958 static int
16959 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
16960 {
16961   return bfd_get_signed_8 (abfd, buf);
16962 }
16963
16964 static unsigned int
16965 read_2_bytes (bfd *abfd, const gdb_byte *buf)
16966 {
16967   return bfd_get_16 (abfd, buf);
16968 }
16969
16970 static int
16971 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
16972 {
16973   return bfd_get_signed_16 (abfd, buf);
16974 }
16975
16976 static unsigned int
16977 read_4_bytes (bfd *abfd, const gdb_byte *buf)
16978 {
16979   return bfd_get_32 (abfd, buf);
16980 }
16981
16982 static int
16983 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
16984 {
16985   return bfd_get_signed_32 (abfd, buf);
16986 }
16987
16988 static ULONGEST
16989 read_8_bytes (bfd *abfd, const gdb_byte *buf)
16990 {
16991   return bfd_get_64 (abfd, buf);
16992 }
16993
16994 static CORE_ADDR
16995 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
16996               unsigned int *bytes_read)
16997 {
16998   struct comp_unit_head *cu_header = &cu->header;
16999   CORE_ADDR retval = 0;
17000
17001   if (cu_header->signed_addr_p)
17002     {
17003       switch (cu_header->addr_size)
17004         {
17005         case 2:
17006           retval = bfd_get_signed_16 (abfd, buf);
17007           break;
17008         case 4:
17009           retval = bfd_get_signed_32 (abfd, buf);
17010           break;
17011         case 8:
17012           retval = bfd_get_signed_64 (abfd, buf);
17013           break;
17014         default:
17015           internal_error (__FILE__, __LINE__,
17016                           _("read_address: bad switch, signed [in module %s]"),
17017                           bfd_get_filename (abfd));
17018         }
17019     }
17020   else
17021     {
17022       switch (cu_header->addr_size)
17023         {
17024         case 2:
17025           retval = bfd_get_16 (abfd, buf);
17026           break;
17027         case 4:
17028           retval = bfd_get_32 (abfd, buf);
17029           break;
17030         case 8:
17031           retval = bfd_get_64 (abfd, buf);
17032           break;
17033         default:
17034           internal_error (__FILE__, __LINE__,
17035                           _("read_address: bad switch, "
17036                             "unsigned [in module %s]"),
17037                           bfd_get_filename (abfd));
17038         }
17039     }
17040
17041   *bytes_read = cu_header->addr_size;
17042   return retval;
17043 }
17044
17045 /* Read the initial length from a section.  The (draft) DWARF 3
17046    specification allows the initial length to take up either 4 bytes
17047    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17048    bytes describe the length and all offsets will be 8 bytes in length
17049    instead of 4.
17050
17051    An older, non-standard 64-bit format is also handled by this
17052    function.  The older format in question stores the initial length
17053    as an 8-byte quantity without an escape value.  Lengths greater
17054    than 2^32 aren't very common which means that the initial 4 bytes
17055    is almost always zero.  Since a length value of zero doesn't make
17056    sense for the 32-bit format, this initial zero can be considered to
17057    be an escape value which indicates the presence of the older 64-bit
17058    format.  As written, the code can't detect (old format) lengths
17059    greater than 4GB.  If it becomes necessary to handle lengths
17060    somewhat larger than 4GB, we could allow other small values (such
17061    as the non-sensical values of 1, 2, and 3) to also be used as
17062    escape values indicating the presence of the old format.
17063
17064    The value returned via bytes_read should be used to increment the
17065    relevant pointer after calling read_initial_length().
17066
17067    [ Note:  read_initial_length() and read_offset() are based on the
17068      document entitled "DWARF Debugging Information Format", revision
17069      3, draft 8, dated November 19, 2001.  This document was obtained
17070      from:
17071
17072         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17073
17074      This document is only a draft and is subject to change.  (So beware.)
17075
17076      Details regarding the older, non-standard 64-bit format were
17077      determined empirically by examining 64-bit ELF files produced by
17078      the SGI toolchain on an IRIX 6.5 machine.
17079
17080      - Kevin, July 16, 2002
17081    ] */
17082
17083 static LONGEST
17084 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17085 {
17086   LONGEST length = bfd_get_32 (abfd, buf);
17087
17088   if (length == 0xffffffff)
17089     {
17090       length = bfd_get_64 (abfd, buf + 4);
17091       *bytes_read = 12;
17092     }
17093   else if (length == 0)
17094     {
17095       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17096       length = bfd_get_64 (abfd, buf);
17097       *bytes_read = 8;
17098     }
17099   else
17100     {
17101       *bytes_read = 4;
17102     }
17103
17104   return length;
17105 }
17106
17107 /* Cover function for read_initial_length.
17108    Returns the length of the object at BUF, and stores the size of the
17109    initial length in *BYTES_READ and stores the size that offsets will be in
17110    *OFFSET_SIZE.
17111    If the initial length size is not equivalent to that specified in
17112    CU_HEADER then issue a complaint.
17113    This is useful when reading non-comp-unit headers.  */
17114
17115 static LONGEST
17116 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17117                                         const struct comp_unit_head *cu_header,
17118                                         unsigned int *bytes_read,
17119                                         unsigned int *offset_size)
17120 {
17121   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17122
17123   gdb_assert (cu_header->initial_length_size == 4
17124               || cu_header->initial_length_size == 8
17125               || cu_header->initial_length_size == 12);
17126
17127   if (cu_header->initial_length_size != *bytes_read)
17128     complaint (&symfile_complaints,
17129                _("intermixed 32-bit and 64-bit DWARF sections"));
17130
17131   *offset_size = (*bytes_read == 4) ? 4 : 8;
17132   return length;
17133 }
17134
17135 /* Read an offset from the data stream.  The size of the offset is
17136    given by cu_header->offset_size.  */
17137
17138 static LONGEST
17139 read_offset (bfd *abfd, const gdb_byte *buf,
17140              const struct comp_unit_head *cu_header,
17141              unsigned int *bytes_read)
17142 {
17143   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17144
17145   *bytes_read = cu_header->offset_size;
17146   return offset;
17147 }
17148
17149 /* Read an offset from the data stream.  */
17150
17151 static LONGEST
17152 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17153 {
17154   LONGEST retval = 0;
17155
17156   switch (offset_size)
17157     {
17158     case 4:
17159       retval = bfd_get_32 (abfd, buf);
17160       break;
17161     case 8:
17162       retval = bfd_get_64 (abfd, buf);
17163       break;
17164     default:
17165       internal_error (__FILE__, __LINE__,
17166                       _("read_offset_1: bad switch [in module %s]"),
17167                       bfd_get_filename (abfd));
17168     }
17169
17170   return retval;
17171 }
17172
17173 static const gdb_byte *
17174 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17175 {
17176   /* If the size of a host char is 8 bits, we can return a pointer
17177      to the buffer, otherwise we have to copy the data to a buffer
17178      allocated on the temporary obstack.  */
17179   gdb_assert (HOST_CHAR_BIT == 8);
17180   return buf;
17181 }
17182
17183 static const char *
17184 read_direct_string (bfd *abfd, const gdb_byte *buf,
17185                     unsigned int *bytes_read_ptr)
17186 {
17187   /* If the size of a host char is 8 bits, we can return a pointer
17188      to the string, otherwise we have to copy the string to a buffer
17189      allocated on the temporary obstack.  */
17190   gdb_assert (HOST_CHAR_BIT == 8);
17191   if (*buf == '\0')
17192     {
17193       *bytes_read_ptr = 1;
17194       return NULL;
17195     }
17196   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17197   return (const char *) buf;
17198 }
17199
17200 /* Return pointer to string at section SECT offset STR_OFFSET with error
17201    reporting strings FORM_NAME and SECT_NAME.  */
17202
17203 static const char *
17204 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17205                                      struct dwarf2_section_info *sect,
17206                                      const char *form_name,
17207                                      const char *sect_name)
17208 {
17209   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17210   if (sect->buffer == NULL)
17211     error (_("%s used without %s section [in module %s]"),
17212            form_name, sect_name, bfd_get_filename (abfd));
17213   if (str_offset >= sect->size)
17214     error (_("%s pointing outside of %s section [in module %s]"),
17215            form_name, sect_name, bfd_get_filename (abfd));
17216   gdb_assert (HOST_CHAR_BIT == 8);
17217   if (sect->buffer[str_offset] == '\0')
17218     return NULL;
17219   return (const char *) (sect->buffer + str_offset);
17220 }
17221
17222 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17223
17224 static const char *
17225 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17226 {
17227   return read_indirect_string_at_offset_from (abfd, str_offset,
17228                                               &dwarf2_per_objfile->str,
17229                                               "DW_FORM_strp", ".debug_str");
17230 }
17231
17232 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17233
17234 static const char *
17235 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17236 {
17237   return read_indirect_string_at_offset_from (abfd, str_offset,
17238                                               &dwarf2_per_objfile->line_str,
17239                                               "DW_FORM_line_strp",
17240                                               ".debug_line_str");
17241 }
17242
17243 /* Read a string at offset STR_OFFSET in the .debug_str section from
17244    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17245    the string consists of a single NUL byte, return NULL; otherwise
17246    return a pointer to the string.  */
17247
17248 static const char *
17249 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17250 {
17251   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17252
17253   if (dwz->str.buffer == NULL)
17254     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17255              "section [in module %s]"),
17256            bfd_get_filename (dwz->dwz_bfd));
17257   if (str_offset >= dwz->str.size)
17258     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17259              ".debug_str section [in module %s]"),
17260            bfd_get_filename (dwz->dwz_bfd));
17261   gdb_assert (HOST_CHAR_BIT == 8);
17262   if (dwz->str.buffer[str_offset] == '\0')
17263     return NULL;
17264   return (const char *) (dwz->str.buffer + str_offset);
17265 }
17266
17267 /* Return pointer to string at .debug_str offset as read from BUF.
17268    BUF is assumed to be in a compilation unit described by CU_HEADER.
17269    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17270
17271 static const char *
17272 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17273                       const struct comp_unit_head *cu_header,
17274                       unsigned int *bytes_read_ptr)
17275 {
17276   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17277
17278   return read_indirect_string_at_offset (abfd, str_offset);
17279 }
17280
17281 /* Return pointer to string at .debug_line_str offset as read from BUF.
17282    BUF is assumed to be in a compilation unit described by CU_HEADER.
17283    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17284
17285 static const char *
17286 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17287                            const struct comp_unit_head *cu_header,
17288                            unsigned int *bytes_read_ptr)
17289 {
17290   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17291
17292   return read_indirect_line_string_at_offset (abfd, str_offset);
17293 }
17294
17295 ULONGEST
17296 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17297                           unsigned int *bytes_read_ptr)
17298 {
17299   ULONGEST result;
17300   unsigned int num_read;
17301   int shift;
17302   unsigned char byte;
17303
17304   result = 0;
17305   shift = 0;
17306   num_read = 0;
17307   while (1)
17308     {
17309       byte = bfd_get_8 (abfd, buf);
17310       buf++;
17311       num_read++;
17312       result |= ((ULONGEST) (byte & 127) << shift);
17313       if ((byte & 128) == 0)
17314         {
17315           break;
17316         }
17317       shift += 7;
17318     }
17319   *bytes_read_ptr = num_read;
17320   return result;
17321 }
17322
17323 static LONGEST
17324 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17325                     unsigned int *bytes_read_ptr)
17326 {
17327   LONGEST result;
17328   int shift, num_read;
17329   unsigned char byte;
17330
17331   result = 0;
17332   shift = 0;
17333   num_read = 0;
17334   while (1)
17335     {
17336       byte = bfd_get_8 (abfd, buf);
17337       buf++;
17338       num_read++;
17339       result |= ((LONGEST) (byte & 127) << shift);
17340       shift += 7;
17341       if ((byte & 128) == 0)
17342         {
17343           break;
17344         }
17345     }
17346   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17347     result |= -(((LONGEST) 1) << shift);
17348   *bytes_read_ptr = num_read;
17349   return result;
17350 }
17351
17352 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17353    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17354    ADDR_SIZE is the size of addresses from the CU header.  */
17355
17356 static CORE_ADDR
17357 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17358 {
17359   struct objfile *objfile = dwarf2_per_objfile->objfile;
17360   bfd *abfd = objfile->obfd;
17361   const gdb_byte *info_ptr;
17362
17363   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17364   if (dwarf2_per_objfile->addr.buffer == NULL)
17365     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17366            objfile_name (objfile));
17367   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17368     error (_("DW_FORM_addr_index pointing outside of "
17369              ".debug_addr section [in module %s]"),
17370            objfile_name (objfile));
17371   info_ptr = (dwarf2_per_objfile->addr.buffer
17372               + addr_base + addr_index * addr_size);
17373   if (addr_size == 4)
17374     return bfd_get_32 (abfd, info_ptr);
17375   else
17376     return bfd_get_64 (abfd, info_ptr);
17377 }
17378
17379 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17380
17381 static CORE_ADDR
17382 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17383 {
17384   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17385 }
17386
17387 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17388
17389 static CORE_ADDR
17390 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17391                              unsigned int *bytes_read)
17392 {
17393   bfd *abfd = cu->objfile->obfd;
17394   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17395
17396   return read_addr_index (cu, addr_index);
17397 }
17398
17399 /* Data structure to pass results from dwarf2_read_addr_index_reader
17400    back to dwarf2_read_addr_index.  */
17401
17402 struct dwarf2_read_addr_index_data
17403 {
17404   ULONGEST addr_base;
17405   int addr_size;
17406 };
17407
17408 /* die_reader_func for dwarf2_read_addr_index.  */
17409
17410 static void
17411 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17412                                const gdb_byte *info_ptr,
17413                                struct die_info *comp_unit_die,
17414                                int has_children,
17415                                void *data)
17416 {
17417   struct dwarf2_cu *cu = reader->cu;
17418   struct dwarf2_read_addr_index_data *aidata =
17419     (struct dwarf2_read_addr_index_data *) data;
17420
17421   aidata->addr_base = cu->addr_base;
17422   aidata->addr_size = cu->header.addr_size;
17423 }
17424
17425 /* Given an index in .debug_addr, fetch the value.
17426    NOTE: This can be called during dwarf expression evaluation,
17427    long after the debug information has been read, and thus per_cu->cu
17428    may no longer exist.  */
17429
17430 CORE_ADDR
17431 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17432                         unsigned int addr_index)
17433 {
17434   struct objfile *objfile = per_cu->objfile;
17435   struct dwarf2_cu *cu = per_cu->cu;
17436   ULONGEST addr_base;
17437   int addr_size;
17438
17439   /* This is intended to be called from outside this file.  */
17440   dw2_setup (objfile);
17441
17442   /* We need addr_base and addr_size.
17443      If we don't have PER_CU->cu, we have to get it.
17444      Nasty, but the alternative is storing the needed info in PER_CU,
17445      which at this point doesn't seem justified: it's not clear how frequently
17446      it would get used and it would increase the size of every PER_CU.
17447      Entry points like dwarf2_per_cu_addr_size do a similar thing
17448      so we're not in uncharted territory here.
17449      Alas we need to be a bit more complicated as addr_base is contained
17450      in the DIE.
17451
17452      We don't need to read the entire CU(/TU).
17453      We just need the header and top level die.
17454
17455      IWBN to use the aging mechanism to let us lazily later discard the CU.
17456      For now we skip this optimization.  */
17457
17458   if (cu != NULL)
17459     {
17460       addr_base = cu->addr_base;
17461       addr_size = cu->header.addr_size;
17462     }
17463   else
17464     {
17465       struct dwarf2_read_addr_index_data aidata;
17466
17467       /* Note: We can't use init_cutu_and_read_dies_simple here,
17468          we need addr_base.  */
17469       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17470                                dwarf2_read_addr_index_reader, &aidata);
17471       addr_base = aidata.addr_base;
17472       addr_size = aidata.addr_size;
17473     }
17474
17475   return read_addr_index_1 (addr_index, addr_base, addr_size);
17476 }
17477
17478 /* Given a DW_FORM_GNU_str_index, fetch the string.
17479    This is only used by the Fission support.  */
17480
17481 static const char *
17482 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17483 {
17484   struct objfile *objfile = dwarf2_per_objfile->objfile;
17485   const char *objf_name = objfile_name (objfile);
17486   bfd *abfd = objfile->obfd;
17487   struct dwarf2_cu *cu = reader->cu;
17488   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17489   struct dwarf2_section_info *str_offsets_section =
17490     &reader->dwo_file->sections.str_offsets;
17491   const gdb_byte *info_ptr;
17492   ULONGEST str_offset;
17493   static const char form_name[] = "DW_FORM_GNU_str_index";
17494
17495   dwarf2_read_section (objfile, str_section);
17496   dwarf2_read_section (objfile, str_offsets_section);
17497   if (str_section->buffer == NULL)
17498     error (_("%s used without .debug_str.dwo section"
17499              " in CU at offset 0x%x [in module %s]"),
17500            form_name, to_underlying (cu->header.sect_off), objf_name);
17501   if (str_offsets_section->buffer == NULL)
17502     error (_("%s used without .debug_str_offsets.dwo section"
17503              " in CU at offset 0x%x [in module %s]"),
17504            form_name, to_underlying (cu->header.sect_off), objf_name);
17505   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17506     error (_("%s pointing outside of .debug_str_offsets.dwo"
17507              " section in CU at offset 0x%x [in module %s]"),
17508            form_name, to_underlying (cu->header.sect_off), objf_name);
17509   info_ptr = (str_offsets_section->buffer
17510               + str_index * cu->header.offset_size);
17511   if (cu->header.offset_size == 4)
17512     str_offset = bfd_get_32 (abfd, info_ptr);
17513   else
17514     str_offset = bfd_get_64 (abfd, info_ptr);
17515   if (str_offset >= str_section->size)
17516     error (_("Offset from %s pointing outside of"
17517              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17518            form_name, to_underlying (cu->header.sect_off), objf_name);
17519   return (const char *) (str_section->buffer + str_offset);
17520 }
17521
17522 /* Return the length of an LEB128 number in BUF.  */
17523
17524 static int
17525 leb128_size (const gdb_byte *buf)
17526 {
17527   const gdb_byte *begin = buf;
17528   gdb_byte byte;
17529
17530   while (1)
17531     {
17532       byte = *buf++;
17533       if ((byte & 128) == 0)
17534         return buf - begin;
17535     }
17536 }
17537
17538 static void
17539 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17540 {
17541   switch (lang)
17542     {
17543     case DW_LANG_C89:
17544     case DW_LANG_C99:
17545     case DW_LANG_C11:
17546     case DW_LANG_C:
17547     case DW_LANG_UPC:
17548       cu->language = language_c;
17549       break;
17550     case DW_LANG_Java:
17551     case DW_LANG_C_plus_plus:
17552     case DW_LANG_C_plus_plus_11:
17553     case DW_LANG_C_plus_plus_14:
17554       cu->language = language_cplus;
17555       break;
17556     case DW_LANG_D:
17557       cu->language = language_d;
17558       break;
17559     case DW_LANG_Fortran77:
17560     case DW_LANG_Fortran90:
17561     case DW_LANG_Fortran95:
17562     case DW_LANG_Fortran03:
17563     case DW_LANG_Fortran08:
17564       cu->language = language_fortran;
17565       break;
17566     case DW_LANG_Go:
17567       cu->language = language_go;
17568       break;
17569     case DW_LANG_Mips_Assembler:
17570       cu->language = language_asm;
17571       break;
17572     case DW_LANG_Ada83:
17573     case DW_LANG_Ada95:
17574       cu->language = language_ada;
17575       break;
17576     case DW_LANG_Modula2:
17577       cu->language = language_m2;
17578       break;
17579     case DW_LANG_Pascal83:
17580       cu->language = language_pascal;
17581       break;
17582     case DW_LANG_ObjC:
17583       cu->language = language_objc;
17584       break;
17585     case DW_LANG_Rust:
17586     case DW_LANG_Rust_old:
17587       cu->language = language_rust;
17588       break;
17589     case DW_LANG_Cobol74:
17590     case DW_LANG_Cobol85:
17591     default:
17592       cu->language = language_minimal;
17593       break;
17594     }
17595   cu->language_defn = language_def (cu->language);
17596 }
17597
17598 /* Return the named attribute or NULL if not there.  */
17599
17600 static struct attribute *
17601 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17602 {
17603   for (;;)
17604     {
17605       unsigned int i;
17606       struct attribute *spec = NULL;
17607
17608       for (i = 0; i < die->num_attrs; ++i)
17609         {
17610           if (die->attrs[i].name == name)
17611             return &die->attrs[i];
17612           if (die->attrs[i].name == DW_AT_specification
17613               || die->attrs[i].name == DW_AT_abstract_origin)
17614             spec = &die->attrs[i];
17615         }
17616
17617       if (!spec)
17618         break;
17619
17620       die = follow_die_ref (die, spec, &cu);
17621     }
17622
17623   return NULL;
17624 }
17625
17626 /* Return the named attribute or NULL if not there,
17627    but do not follow DW_AT_specification, etc.
17628    This is for use in contexts where we're reading .debug_types dies.
17629    Following DW_AT_specification, DW_AT_abstract_origin will take us
17630    back up the chain, and we want to go down.  */
17631
17632 static struct attribute *
17633 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17634 {
17635   unsigned int i;
17636
17637   for (i = 0; i < die->num_attrs; ++i)
17638     if (die->attrs[i].name == name)
17639       return &die->attrs[i];
17640
17641   return NULL;
17642 }
17643
17644 /* Return the string associated with a string-typed attribute, or NULL if it
17645    is either not found or is of an incorrect type.  */
17646
17647 static const char *
17648 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17649 {
17650   struct attribute *attr;
17651   const char *str = NULL;
17652
17653   attr = dwarf2_attr (die, name, cu);
17654
17655   if (attr != NULL)
17656     {
17657       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17658           || attr->form == DW_FORM_string
17659           || attr->form == DW_FORM_GNU_str_index
17660           || attr->form == DW_FORM_GNU_strp_alt)
17661         str = DW_STRING (attr);
17662       else
17663         complaint (&symfile_complaints,
17664                    _("string type expected for attribute %s for "
17665                      "DIE at 0x%x in module %s"),
17666                    dwarf_attr_name (name), to_underlying (die->sect_off),
17667                    objfile_name (cu->objfile));
17668     }
17669
17670   return str;
17671 }
17672
17673 /* Return non-zero iff the attribute NAME is defined for the given DIE,
17674    and holds a non-zero value.  This function should only be used for
17675    DW_FORM_flag or DW_FORM_flag_present attributes.  */
17676
17677 static int
17678 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
17679 {
17680   struct attribute *attr = dwarf2_attr (die, name, cu);
17681
17682   return (attr && DW_UNSND (attr));
17683 }
17684
17685 static int
17686 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
17687 {
17688   /* A DIE is a declaration if it has a DW_AT_declaration attribute
17689      which value is non-zero.  However, we have to be careful with
17690      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
17691      (via dwarf2_flag_true_p) follows this attribute.  So we may
17692      end up accidently finding a declaration attribute that belongs
17693      to a different DIE referenced by the specification attribute,
17694      even though the given DIE does not have a declaration attribute.  */
17695   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
17696           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
17697 }
17698
17699 /* Return the die giving the specification for DIE, if there is
17700    one.  *SPEC_CU is the CU containing DIE on input, and the CU
17701    containing the return value on output.  If there is no
17702    specification, but there is an abstract origin, that is
17703    returned.  */
17704
17705 static struct die_info *
17706 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
17707 {
17708   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
17709                                              *spec_cu);
17710
17711   if (spec_attr == NULL)
17712     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
17713
17714   if (spec_attr == NULL)
17715     return NULL;
17716   else
17717     return follow_die_ref (die, spec_attr, spec_cu);
17718 }
17719
17720 /* Stub for free_line_header to match void * callback types.  */
17721
17722 static void
17723 free_line_header_voidp (void *arg)
17724 {
17725   struct line_header *lh = (struct line_header *) arg;
17726
17727   delete lh;
17728 }
17729
17730 void
17731 line_header::add_include_dir (const char *include_dir)
17732 {
17733   if (dwarf_line_debug >= 2)
17734     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
17735                         include_dirs.size () + 1, include_dir);
17736
17737   include_dirs.push_back (include_dir);
17738 }
17739
17740 void
17741 line_header::add_file_name (const char *name,
17742                             dir_index d_index,
17743                             unsigned int mod_time,
17744                             unsigned int length)
17745 {
17746   if (dwarf_line_debug >= 2)
17747     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
17748                         (unsigned) file_names.size () + 1, name);
17749
17750   file_names.emplace_back (name, d_index, mod_time, length);
17751 }
17752
17753 /* A convenience function to find the proper .debug_line section for a CU.  */
17754
17755 static struct dwarf2_section_info *
17756 get_debug_line_section (struct dwarf2_cu *cu)
17757 {
17758   struct dwarf2_section_info *section;
17759
17760   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
17761      DWO file.  */
17762   if (cu->dwo_unit && cu->per_cu->is_debug_types)
17763     section = &cu->dwo_unit->dwo_file->sections.line;
17764   else if (cu->per_cu->is_dwz)
17765     {
17766       struct dwz_file *dwz = dwarf2_get_dwz_file ();
17767
17768       section = &dwz->line;
17769     }
17770   else
17771     section = &dwarf2_per_objfile->line;
17772
17773   return section;
17774 }
17775
17776 /* Read directory or file name entry format, starting with byte of
17777    format count entries, ULEB128 pairs of entry formats, ULEB128 of
17778    entries count and the entries themselves in the described entry
17779    format.  */
17780
17781 static void
17782 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
17783                         struct line_header *lh,
17784                         const struct comp_unit_head *cu_header,
17785                         void (*callback) (struct line_header *lh,
17786                                           const char *name,
17787                                           dir_index d_index,
17788                                           unsigned int mod_time,
17789                                           unsigned int length))
17790 {
17791   gdb_byte format_count, formati;
17792   ULONGEST data_count, datai;
17793   const gdb_byte *buf = *bufp;
17794   const gdb_byte *format_header_data;
17795   int i;
17796   unsigned int bytes_read;
17797
17798   format_count = read_1_byte (abfd, buf);
17799   buf += 1;
17800   format_header_data = buf;
17801   for (formati = 0; formati < format_count; formati++)
17802     {
17803       read_unsigned_leb128 (abfd, buf, &bytes_read);
17804       buf += bytes_read;
17805       read_unsigned_leb128 (abfd, buf, &bytes_read);
17806       buf += bytes_read;
17807     }
17808
17809   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
17810   buf += bytes_read;
17811   for (datai = 0; datai < data_count; datai++)
17812     {
17813       const gdb_byte *format = format_header_data;
17814       struct file_entry fe;
17815
17816       for (formati = 0; formati < format_count; formati++)
17817         {
17818           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
17819           format += bytes_read;
17820
17821           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
17822           format += bytes_read;
17823
17824           gdb::optional<const char *> string;
17825           gdb::optional<unsigned int> uint;
17826
17827           switch (form)
17828             {
17829             case DW_FORM_string:
17830               string.emplace (read_direct_string (abfd, buf, &bytes_read));
17831               buf += bytes_read;
17832               break;
17833
17834             case DW_FORM_line_strp:
17835               string.emplace (read_indirect_line_string (abfd, buf,
17836                                                          cu_header,
17837                                                          &bytes_read));
17838               buf += bytes_read;
17839               break;
17840
17841             case DW_FORM_data1:
17842               uint.emplace (read_1_byte (abfd, buf));
17843               buf += 1;
17844               break;
17845
17846             case DW_FORM_data2:
17847               uint.emplace (read_2_bytes (abfd, buf));
17848               buf += 2;
17849               break;
17850
17851             case DW_FORM_data4:
17852               uint.emplace (read_4_bytes (abfd, buf));
17853               buf += 4;
17854               break;
17855
17856             case DW_FORM_data8:
17857               uint.emplace (read_8_bytes (abfd, buf));
17858               buf += 8;
17859               break;
17860
17861             case DW_FORM_udata:
17862               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
17863               buf += bytes_read;
17864               break;
17865
17866             case DW_FORM_block:
17867               /* It is valid only for DW_LNCT_timestamp which is ignored by
17868                  current GDB.  */
17869               break;
17870             }
17871
17872           switch (content_type)
17873             {
17874             case DW_LNCT_path:
17875               if (string.has_value ())
17876                 fe.name = *string;
17877               break;
17878             case DW_LNCT_directory_index:
17879               if (uint.has_value ())
17880                 fe.d_index = (dir_index) *uint;
17881               break;
17882             case DW_LNCT_timestamp:
17883               if (uint.has_value ())
17884                 fe.mod_time = *uint;
17885               break;
17886             case DW_LNCT_size:
17887               if (uint.has_value ())
17888                 fe.length = *uint;
17889               break;
17890             case DW_LNCT_MD5:
17891               break;
17892             default:
17893               complaint (&symfile_complaints,
17894                          _("Unknown format content type %s"),
17895                          pulongest (content_type));
17896             }
17897         }
17898
17899       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
17900     }
17901
17902   *bufp = buf;
17903 }
17904
17905 /* Read the statement program header starting at OFFSET in
17906    .debug_line, or .debug_line.dwo.  Return a pointer
17907    to a struct line_header, allocated using xmalloc.
17908    Returns NULL if there is a problem reading the header, e.g., if it
17909    has a version we don't understand.
17910
17911    NOTE: the strings in the include directory and file name tables of
17912    the returned object point into the dwarf line section buffer,
17913    and must not be freed.  */
17914
17915 static line_header_up
17916 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
17917 {
17918   const gdb_byte *line_ptr;
17919   unsigned int bytes_read, offset_size;
17920   int i;
17921   const char *cur_dir, *cur_file;
17922   struct dwarf2_section_info *section;
17923   bfd *abfd;
17924
17925   section = get_debug_line_section (cu);
17926   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
17927   if (section->buffer == NULL)
17928     {
17929       if (cu->dwo_unit && cu->per_cu->is_debug_types)
17930         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
17931       else
17932         complaint (&symfile_complaints, _("missing .debug_line section"));
17933       return 0;
17934     }
17935
17936   /* We can't do this until we know the section is non-empty.
17937      Only then do we know we have such a section.  */
17938   abfd = get_section_bfd_owner (section);
17939
17940   /* Make sure that at least there's room for the total_length field.
17941      That could be 12 bytes long, but we're just going to fudge that.  */
17942   if (to_underlying (sect_off) + 4 >= section->size)
17943     {
17944       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17945       return 0;
17946     }
17947
17948   line_header_up lh (new line_header ());
17949
17950   lh->sect_off = sect_off;
17951   lh->offset_in_dwz = cu->per_cu->is_dwz;
17952
17953   line_ptr = section->buffer + to_underlying (sect_off);
17954
17955   /* Read in the header.  */
17956   lh->total_length =
17957     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
17958                                             &bytes_read, &offset_size);
17959   line_ptr += bytes_read;
17960   if (line_ptr + lh->total_length > (section->buffer + section->size))
17961     {
17962       dwarf2_statement_list_fits_in_line_number_section_complaint ();
17963       return 0;
17964     }
17965   lh->statement_program_end = line_ptr + lh->total_length;
17966   lh->version = read_2_bytes (abfd, line_ptr);
17967   line_ptr += 2;
17968   if (lh->version > 5)
17969     {
17970       /* This is a version we don't understand.  The format could have
17971          changed in ways we don't handle properly so just punt.  */
17972       complaint (&symfile_complaints,
17973                  _("unsupported version in .debug_line section"));
17974       return NULL;
17975     }
17976   if (lh->version >= 5)
17977     {
17978       gdb_byte segment_selector_size;
17979
17980       /* Skip address size.  */
17981       read_1_byte (abfd, line_ptr);
17982       line_ptr += 1;
17983
17984       segment_selector_size = read_1_byte (abfd, line_ptr);
17985       line_ptr += 1;
17986       if (segment_selector_size != 0)
17987         {
17988           complaint (&symfile_complaints,
17989                      _("unsupported segment selector size %u "
17990                        "in .debug_line section"),
17991                      segment_selector_size);
17992           return NULL;
17993         }
17994     }
17995   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
17996   line_ptr += offset_size;
17997   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
17998   line_ptr += 1;
17999   if (lh->version >= 4)
18000     {
18001       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18002       line_ptr += 1;
18003     }
18004   else
18005     lh->maximum_ops_per_instruction = 1;
18006
18007   if (lh->maximum_ops_per_instruction == 0)
18008     {
18009       lh->maximum_ops_per_instruction = 1;
18010       complaint (&symfile_complaints,
18011                  _("invalid maximum_ops_per_instruction "
18012                    "in `.debug_line' section"));
18013     }
18014
18015   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18016   line_ptr += 1;
18017   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18018   line_ptr += 1;
18019   lh->line_range = read_1_byte (abfd, line_ptr);
18020   line_ptr += 1;
18021   lh->opcode_base = read_1_byte (abfd, line_ptr);
18022   line_ptr += 1;
18023   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18024
18025   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18026   for (i = 1; i < lh->opcode_base; ++i)
18027     {
18028       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18029       line_ptr += 1;
18030     }
18031
18032   if (lh->version >= 5)
18033     {
18034       /* Read directory table.  */
18035       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18036                               [] (struct line_header *lh, const char *name,
18037                                   dir_index d_index, unsigned int mod_time,
18038                                   unsigned int length)
18039         {
18040           lh->add_include_dir (name);
18041         });
18042
18043       /* Read file name table.  */
18044       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18045                               [] (struct line_header *lh, const char *name,
18046                                   dir_index d_index, unsigned int mod_time,
18047                                   unsigned int length)
18048         {
18049           lh->add_file_name (name, d_index, mod_time, length);
18050         });
18051     }
18052   else
18053     {
18054       /* Read directory table.  */
18055       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18056         {
18057           line_ptr += bytes_read;
18058           lh->add_include_dir (cur_dir);
18059         }
18060       line_ptr += bytes_read;
18061
18062       /* Read file name table.  */
18063       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18064         {
18065           unsigned int mod_time, length;
18066           dir_index d_index;
18067
18068           line_ptr += bytes_read;
18069           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18070           line_ptr += bytes_read;
18071           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18072           line_ptr += bytes_read;
18073           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18074           line_ptr += bytes_read;
18075
18076           lh->add_file_name (cur_file, d_index, mod_time, length);
18077         }
18078       line_ptr += bytes_read;
18079     }
18080   lh->statement_program_start = line_ptr;
18081
18082   if (line_ptr > (section->buffer + section->size))
18083     complaint (&symfile_complaints,
18084                _("line number info header doesn't "
18085                  "fit in `.debug_line' section"));
18086
18087   return lh;
18088 }
18089
18090 /* Subroutine of dwarf_decode_lines to simplify it.
18091    Return the file name of the psymtab for included file FILE_INDEX
18092    in line header LH of PST.
18093    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18094    If space for the result is malloc'd, it will be freed by a cleanup.
18095    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18096
18097    The function creates dangling cleanup registration.  */
18098
18099 static const char *
18100 psymtab_include_file_name (const struct line_header *lh, int file_index,
18101                            const struct partial_symtab *pst,
18102                            const char *comp_dir)
18103 {
18104   const file_entry &fe = lh->file_names[file_index];
18105   const char *include_name = fe.name;
18106   const char *include_name_to_compare = include_name;
18107   const char *pst_filename;
18108   char *copied_name = NULL;
18109   int file_is_pst;
18110
18111   const char *dir_name = fe.include_dir (lh);
18112
18113   if (!IS_ABSOLUTE_PATH (include_name)
18114       && (dir_name != NULL || comp_dir != NULL))
18115     {
18116       /* Avoid creating a duplicate psymtab for PST.
18117          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18118          Before we do the comparison, however, we need to account
18119          for DIR_NAME and COMP_DIR.
18120          First prepend dir_name (if non-NULL).  If we still don't
18121          have an absolute path prepend comp_dir (if non-NULL).
18122          However, the directory we record in the include-file's
18123          psymtab does not contain COMP_DIR (to match the
18124          corresponding symtab(s)).
18125
18126          Example:
18127
18128          bash$ cd /tmp
18129          bash$ gcc -g ./hello.c
18130          include_name = "hello.c"
18131          dir_name = "."
18132          DW_AT_comp_dir = comp_dir = "/tmp"
18133          DW_AT_name = "./hello.c"
18134
18135       */
18136
18137       if (dir_name != NULL)
18138         {
18139           char *tem = concat (dir_name, SLASH_STRING,
18140                               include_name, (char *)NULL);
18141
18142           make_cleanup (xfree, tem);
18143           include_name = tem;
18144           include_name_to_compare = include_name;
18145         }
18146       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18147         {
18148           char *tem = concat (comp_dir, SLASH_STRING,
18149                               include_name, (char *)NULL);
18150
18151           make_cleanup (xfree, tem);
18152           include_name_to_compare = tem;
18153         }
18154     }
18155
18156   pst_filename = pst->filename;
18157   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18158     {
18159       copied_name = concat (pst->dirname, SLASH_STRING,
18160                             pst_filename, (char *)NULL);
18161       pst_filename = copied_name;
18162     }
18163
18164   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18165
18166   if (copied_name != NULL)
18167     xfree (copied_name);
18168
18169   if (file_is_pst)
18170     return NULL;
18171   return include_name;
18172 }
18173
18174 /* State machine to track the state of the line number program.  */
18175
18176 class lnp_state_machine
18177 {
18178 public:
18179   /* Initialize a machine state for the start of a line number
18180      program.  */
18181   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18182
18183   file_entry *current_file ()
18184   {
18185     /* lh->file_names is 0-based, but the file name numbers in the
18186        statement program are 1-based.  */
18187     return m_line_header->file_name_at (m_file);
18188   }
18189
18190   /* Record the line in the state machine.  END_SEQUENCE is true if
18191      we're processing the end of a sequence.  */
18192   void record_line (bool end_sequence);
18193
18194   /* Check address and if invalid nop-out the rest of the lines in this
18195      sequence.  */
18196   void check_line_address (struct dwarf2_cu *cu,
18197                            const gdb_byte *line_ptr,
18198                            CORE_ADDR lowpc, CORE_ADDR address);
18199
18200   void handle_set_discriminator (unsigned int discriminator)
18201   {
18202     m_discriminator = discriminator;
18203     m_line_has_non_zero_discriminator |= discriminator != 0;
18204   }
18205
18206   /* Handle DW_LNE_set_address.  */
18207   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18208   {
18209     m_op_index = 0;
18210     address += baseaddr;
18211     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18212   }
18213
18214   /* Handle DW_LNS_advance_pc.  */
18215   void handle_advance_pc (CORE_ADDR adjust);
18216
18217   /* Handle a special opcode.  */
18218   void handle_special_opcode (unsigned char op_code);
18219
18220   /* Handle DW_LNS_advance_line.  */
18221   void handle_advance_line (int line_delta)
18222   {
18223     advance_line (line_delta);
18224   }
18225
18226   /* Handle DW_LNS_set_file.  */
18227   void handle_set_file (file_name_index file);
18228
18229   /* Handle DW_LNS_negate_stmt.  */
18230   void handle_negate_stmt ()
18231   {
18232     m_is_stmt = !m_is_stmt;
18233   }
18234
18235   /* Handle DW_LNS_const_add_pc.  */
18236   void handle_const_add_pc ();
18237
18238   /* Handle DW_LNS_fixed_advance_pc.  */
18239   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18240   {
18241     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18242     m_op_index = 0;
18243   }
18244
18245   /* Handle DW_LNS_copy.  */
18246   void handle_copy ()
18247   {
18248     record_line (false);
18249     m_discriminator = 0;
18250   }
18251
18252   /* Handle DW_LNE_end_sequence.  */
18253   void handle_end_sequence ()
18254   {
18255     m_record_line_callback = ::record_line;
18256   }
18257
18258 private:
18259   /* Advance the line by LINE_DELTA.  */
18260   void advance_line (int line_delta)
18261   {
18262     m_line += line_delta;
18263
18264     if (line_delta != 0)
18265       m_line_has_non_zero_discriminator = m_discriminator != 0;
18266   }
18267
18268   gdbarch *m_gdbarch;
18269
18270   /* True if we're recording lines.
18271      Otherwise we're building partial symtabs and are just interested in
18272      finding include files mentioned by the line number program.  */
18273   bool m_record_lines_p;
18274
18275   /* The line number header.  */
18276   line_header *m_line_header;
18277
18278   /* These are part of the standard DWARF line number state machine,
18279      and initialized according to the DWARF spec.  */
18280
18281   unsigned char m_op_index = 0;
18282   /* The line table index (1-based) of the current file.  */
18283   file_name_index m_file = (file_name_index) 1;
18284   unsigned int m_line = 1;
18285
18286   /* These are initialized in the constructor.  */
18287
18288   CORE_ADDR m_address;
18289   bool m_is_stmt;
18290   unsigned int m_discriminator;
18291
18292   /* Additional bits of state we need to track.  */
18293
18294   /* The last file that we called dwarf2_start_subfile for.
18295      This is only used for TLLs.  */
18296   unsigned int m_last_file = 0;
18297   /* The last file a line number was recorded for.  */
18298   struct subfile *m_last_subfile = NULL;
18299
18300   /* The function to call to record a line.  */
18301   record_line_ftype *m_record_line_callback = NULL;
18302
18303   /* The last line number that was recorded, used to coalesce
18304      consecutive entries for the same line.  This can happen, for
18305      example, when discriminators are present.  PR 17276.  */
18306   unsigned int m_last_line = 0;
18307   bool m_line_has_non_zero_discriminator = false;
18308 };
18309
18310 void
18311 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18312 {
18313   CORE_ADDR addr_adj = (((m_op_index + adjust)
18314                          / m_line_header->maximum_ops_per_instruction)
18315                         * m_line_header->minimum_instruction_length);
18316   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18317   m_op_index = ((m_op_index + adjust)
18318                 % m_line_header->maximum_ops_per_instruction);
18319 }
18320
18321 void
18322 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18323 {
18324   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18325   CORE_ADDR addr_adj = (((m_op_index
18326                           + (adj_opcode / m_line_header->line_range))
18327                          / m_line_header->maximum_ops_per_instruction)
18328                         * m_line_header->minimum_instruction_length);
18329   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18330   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18331                 % m_line_header->maximum_ops_per_instruction);
18332
18333   int line_delta = (m_line_header->line_base
18334                     + (adj_opcode % m_line_header->line_range));
18335   advance_line (line_delta);
18336   record_line (false);
18337   m_discriminator = 0;
18338 }
18339
18340 void
18341 lnp_state_machine::handle_set_file (file_name_index file)
18342 {
18343   m_file = file;
18344
18345   const file_entry *fe = current_file ();
18346   if (fe == NULL)
18347     dwarf2_debug_line_missing_file_complaint ();
18348   else if (m_record_lines_p)
18349     {
18350       const char *dir = fe->include_dir (m_line_header);
18351
18352       m_last_subfile = current_subfile;
18353       m_line_has_non_zero_discriminator = m_discriminator != 0;
18354       dwarf2_start_subfile (fe->name, dir);
18355     }
18356 }
18357
18358 void
18359 lnp_state_machine::handle_const_add_pc ()
18360 {
18361   CORE_ADDR adjust
18362     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18363
18364   CORE_ADDR addr_adj
18365     = (((m_op_index + adjust)
18366         / m_line_header->maximum_ops_per_instruction)
18367        * m_line_header->minimum_instruction_length);
18368
18369   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18370   m_op_index = ((m_op_index + adjust)
18371                 % m_line_header->maximum_ops_per_instruction);
18372 }
18373
18374 /* Ignore this record_line request.  */
18375
18376 static void
18377 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18378 {
18379   return;
18380 }
18381
18382 /* Return non-zero if we should add LINE to the line number table.
18383    LINE is the line to add, LAST_LINE is the last line that was added,
18384    LAST_SUBFILE is the subfile for LAST_LINE.
18385    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18386    had a non-zero discriminator.
18387
18388    We have to be careful in the presence of discriminators.
18389    E.g., for this line:
18390
18391      for (i = 0; i < 100000; i++);
18392
18393    clang can emit four line number entries for that one line,
18394    each with a different discriminator.
18395    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18396
18397    However, we want gdb to coalesce all four entries into one.
18398    Otherwise the user could stepi into the middle of the line and
18399    gdb would get confused about whether the pc really was in the
18400    middle of the line.
18401
18402    Things are further complicated by the fact that two consecutive
18403    line number entries for the same line is a heuristic used by gcc
18404    to denote the end of the prologue.  So we can't just discard duplicate
18405    entries, we have to be selective about it.  The heuristic we use is
18406    that we only collapse consecutive entries for the same line if at least
18407    one of those entries has a non-zero discriminator.  PR 17276.
18408
18409    Note: Addresses in the line number state machine can never go backwards
18410    within one sequence, thus this coalescing is ok.  */
18411
18412 static int
18413 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18414                      int line_has_non_zero_discriminator,
18415                      struct subfile *last_subfile)
18416 {
18417   if (current_subfile != last_subfile)
18418     return 1;
18419   if (line != last_line)
18420     return 1;
18421   /* Same line for the same file that we've seen already.
18422      As a last check, for pr 17276, only record the line if the line
18423      has never had a non-zero discriminator.  */
18424   if (!line_has_non_zero_discriminator)
18425     return 1;
18426   return 0;
18427 }
18428
18429 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18430    in the line table of subfile SUBFILE.  */
18431
18432 static void
18433 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18434                      unsigned int line, CORE_ADDR address,
18435                      record_line_ftype p_record_line)
18436 {
18437   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18438
18439   if (dwarf_line_debug)
18440     {
18441       fprintf_unfiltered (gdb_stdlog,
18442                           "Recording line %u, file %s, address %s\n",
18443                           line, lbasename (subfile->name),
18444                           paddress (gdbarch, address));
18445     }
18446
18447   (*p_record_line) (subfile, line, addr);
18448 }
18449
18450 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18451    Mark the end of a set of line number records.
18452    The arguments are the same as for dwarf_record_line_1.
18453    If SUBFILE is NULL the request is ignored.  */
18454
18455 static void
18456 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18457                    CORE_ADDR address, record_line_ftype p_record_line)
18458 {
18459   if (subfile == NULL)
18460     return;
18461
18462   if (dwarf_line_debug)
18463     {
18464       fprintf_unfiltered (gdb_stdlog,
18465                           "Finishing current line, file %s, address %s\n",
18466                           lbasename (subfile->name),
18467                           paddress (gdbarch, address));
18468     }
18469
18470   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18471 }
18472
18473 void
18474 lnp_state_machine::record_line (bool end_sequence)
18475 {
18476   if (dwarf_line_debug)
18477     {
18478       fprintf_unfiltered (gdb_stdlog,
18479                           "Processing actual line %u: file %u,"
18480                           " address %s, is_stmt %u, discrim %u\n",
18481                           m_line, to_underlying (m_file),
18482                           paddress (m_gdbarch, m_address),
18483                           m_is_stmt, m_discriminator);
18484     }
18485
18486   file_entry *fe = current_file ();
18487
18488   if (fe == NULL)
18489     dwarf2_debug_line_missing_file_complaint ();
18490   /* For now we ignore lines not starting on an instruction boundary.
18491      But not when processing end_sequence for compatibility with the
18492      previous version of the code.  */
18493   else if (m_op_index == 0 || end_sequence)
18494     {
18495       fe->included_p = 1;
18496       if (m_record_lines_p && m_is_stmt)
18497         {
18498           if (m_last_subfile != current_subfile || end_sequence)
18499             {
18500               dwarf_finish_line (m_gdbarch, m_last_subfile,
18501                                  m_address, m_record_line_callback);
18502             }
18503
18504           if (!end_sequence)
18505             {
18506               if (dwarf_record_line_p (m_line, m_last_line,
18507                                        m_line_has_non_zero_discriminator,
18508                                        m_last_subfile))
18509                 {
18510                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18511                                        m_line, m_address,
18512                                        m_record_line_callback);
18513                 }
18514               m_last_subfile = current_subfile;
18515               m_last_line = m_line;
18516             }
18517         }
18518     }
18519 }
18520
18521 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18522                                       bool record_lines_p)
18523 {
18524   m_gdbarch = arch;
18525   m_record_lines_p = record_lines_p;
18526   m_line_header = lh;
18527
18528   m_record_line_callback = ::record_line;
18529
18530   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18531      was a line entry for it so that the backend has a chance to adjust it
18532      and also record it in case it needs it.  This is currently used by MIPS
18533      code, cf. `mips_adjust_dwarf2_line'.  */
18534   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18535   m_is_stmt = lh->default_is_stmt;
18536   m_discriminator = 0;
18537 }
18538
18539 void
18540 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18541                                        const gdb_byte *line_ptr,
18542                                        CORE_ADDR lowpc, CORE_ADDR address)
18543 {
18544   /* If address < lowpc then it's not a usable value, it's outside the
18545      pc range of the CU.  However, we restrict the test to only address
18546      values of zero to preserve GDB's previous behaviour which is to
18547      handle the specific case of a function being GC'd by the linker.  */
18548
18549   if (address == 0 && address < lowpc)
18550     {
18551       /* This line table is for a function which has been
18552          GCd by the linker.  Ignore it.  PR gdb/12528 */
18553
18554       struct objfile *objfile = cu->objfile;
18555       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18556
18557       complaint (&symfile_complaints,
18558                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18559                  line_offset, objfile_name (objfile));
18560       m_record_line_callback = noop_record_line;
18561       /* Note: record_line_callback is left as noop_record_line until
18562          we see DW_LNE_end_sequence.  */
18563     }
18564 }
18565
18566 /* Subroutine of dwarf_decode_lines to simplify it.
18567    Process the line number information in LH.
18568    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18569    program in order to set included_p for every referenced header.  */
18570
18571 static void
18572 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18573                       const int decode_for_pst_p, CORE_ADDR lowpc)
18574 {
18575   const gdb_byte *line_ptr, *extended_end;
18576   const gdb_byte *line_end;
18577   unsigned int bytes_read, extended_len;
18578   unsigned char op_code, extended_op;
18579   CORE_ADDR baseaddr;
18580   struct objfile *objfile = cu->objfile;
18581   bfd *abfd = objfile->obfd;
18582   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18583   /* True if we're recording line info (as opposed to building partial
18584      symtabs and just interested in finding include files mentioned by
18585      the line number program).  */
18586   bool record_lines_p = !decode_for_pst_p;
18587
18588   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18589
18590   line_ptr = lh->statement_program_start;
18591   line_end = lh->statement_program_end;
18592
18593   /* Read the statement sequences until there's nothing left.  */
18594   while (line_ptr < line_end)
18595     {
18596       /* The DWARF line number program state machine.  Reset the state
18597          machine at the start of each sequence.  */
18598       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18599       bool end_sequence = false;
18600
18601       if (record_lines_p)
18602         {
18603           /* Start a subfile for the current file of the state
18604              machine.  */
18605           const file_entry *fe = state_machine.current_file ();
18606
18607           if (fe != NULL)
18608             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18609         }
18610
18611       /* Decode the table.  */
18612       while (line_ptr < line_end && !end_sequence)
18613         {
18614           op_code = read_1_byte (abfd, line_ptr);
18615           line_ptr += 1;
18616
18617           if (op_code >= lh->opcode_base)
18618             {
18619               /* Special opcode.  */
18620               state_machine.handle_special_opcode (op_code);
18621             }
18622           else switch (op_code)
18623             {
18624             case DW_LNS_extended_op:
18625               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18626                                                    &bytes_read);
18627               line_ptr += bytes_read;
18628               extended_end = line_ptr + extended_len;
18629               extended_op = read_1_byte (abfd, line_ptr);
18630               line_ptr += 1;
18631               switch (extended_op)
18632                 {
18633                 case DW_LNE_end_sequence:
18634                   state_machine.handle_end_sequence ();
18635                   end_sequence = true;
18636                   break;
18637                 case DW_LNE_set_address:
18638                   {
18639                     CORE_ADDR address
18640                       = read_address (abfd, line_ptr, cu, &bytes_read);
18641                     line_ptr += bytes_read;
18642
18643                     state_machine.check_line_address (cu, line_ptr,
18644                                                       lowpc, address);
18645                     state_machine.handle_set_address (baseaddr, address);
18646                   }
18647                   break;
18648                 case DW_LNE_define_file:
18649                   {
18650                     const char *cur_file;
18651                     unsigned int mod_time, length;
18652                     dir_index dindex;
18653
18654                     cur_file = read_direct_string (abfd, line_ptr,
18655                                                    &bytes_read);
18656                     line_ptr += bytes_read;
18657                     dindex = (dir_index)
18658                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18659                     line_ptr += bytes_read;
18660                     mod_time =
18661                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18662                     line_ptr += bytes_read;
18663                     length =
18664                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18665                     line_ptr += bytes_read;
18666                     lh->add_file_name (cur_file, dindex, mod_time, length);
18667                   }
18668                   break;
18669                 case DW_LNE_set_discriminator:
18670                   {
18671                     /* The discriminator is not interesting to the
18672                        debugger; just ignore it.  We still need to
18673                        check its value though:
18674                        if there are consecutive entries for the same
18675                        (non-prologue) line we want to coalesce them.
18676                        PR 17276.  */
18677                     unsigned int discr
18678                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18679                     line_ptr += bytes_read;
18680
18681                     state_machine.handle_set_discriminator (discr);
18682                   }
18683                   break;
18684                 default:
18685                   complaint (&symfile_complaints,
18686                              _("mangled .debug_line section"));
18687                   return;
18688                 }
18689               /* Make sure that we parsed the extended op correctly.  If e.g.
18690                  we expected a different address size than the producer used,
18691                  we may have read the wrong number of bytes.  */
18692               if (line_ptr != extended_end)
18693                 {
18694                   complaint (&symfile_complaints,
18695                              _("mangled .debug_line section"));
18696                   return;
18697                 }
18698               break;
18699             case DW_LNS_copy:
18700               state_machine.handle_copy ();
18701               break;
18702             case DW_LNS_advance_pc:
18703               {
18704                 CORE_ADDR adjust
18705                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18706                 line_ptr += bytes_read;
18707
18708                 state_machine.handle_advance_pc (adjust);
18709               }
18710               break;
18711             case DW_LNS_advance_line:
18712               {
18713                 int line_delta
18714                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
18715                 line_ptr += bytes_read;
18716
18717                 state_machine.handle_advance_line (line_delta);
18718               }
18719               break;
18720             case DW_LNS_set_file:
18721               {
18722                 file_name_index file
18723                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
18724                                                             &bytes_read);
18725                 line_ptr += bytes_read;
18726
18727                 state_machine.handle_set_file (file);
18728               }
18729               break;
18730             case DW_LNS_set_column:
18731               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18732               line_ptr += bytes_read;
18733               break;
18734             case DW_LNS_negate_stmt:
18735               state_machine.handle_negate_stmt ();
18736               break;
18737             case DW_LNS_set_basic_block:
18738               break;
18739             /* Add to the address register of the state machine the
18740                address increment value corresponding to special opcode
18741                255.  I.e., this value is scaled by the minimum
18742                instruction length since special opcode 255 would have
18743                scaled the increment.  */
18744             case DW_LNS_const_add_pc:
18745               state_machine.handle_const_add_pc ();
18746               break;
18747             case DW_LNS_fixed_advance_pc:
18748               {
18749                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
18750                 line_ptr += 2;
18751
18752                 state_machine.handle_fixed_advance_pc (addr_adj);
18753               }
18754               break;
18755             default:
18756               {
18757                 /* Unknown standard opcode, ignore it.  */
18758                 int i;
18759
18760                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
18761                   {
18762                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18763                     line_ptr += bytes_read;
18764                   }
18765               }
18766             }
18767         }
18768
18769       if (!end_sequence)
18770         dwarf2_debug_line_missing_end_sequence_complaint ();
18771
18772       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
18773          in which case we still finish recording the last line).  */
18774       state_machine.record_line (true);
18775     }
18776 }
18777
18778 /* Decode the Line Number Program (LNP) for the given line_header
18779    structure and CU.  The actual information extracted and the type
18780    of structures created from the LNP depends on the value of PST.
18781
18782    1. If PST is NULL, then this procedure uses the data from the program
18783       to create all necessary symbol tables, and their linetables.
18784
18785    2. If PST is not NULL, this procedure reads the program to determine
18786       the list of files included by the unit represented by PST, and
18787       builds all the associated partial symbol tables.
18788
18789    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18790    It is used for relative paths in the line table.
18791    NOTE: When processing partial symtabs (pst != NULL),
18792    comp_dir == pst->dirname.
18793
18794    NOTE: It is important that psymtabs have the same file name (via strcmp)
18795    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
18796    symtab we don't use it in the name of the psymtabs we create.
18797    E.g. expand_line_sal requires this when finding psymtabs to expand.
18798    A good testcase for this is mb-inline.exp.
18799
18800    LOWPC is the lowest address in CU (or 0 if not known).
18801
18802    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
18803    for its PC<->lines mapping information.  Otherwise only the filename
18804    table is read in.  */
18805
18806 static void
18807 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
18808                     struct dwarf2_cu *cu, struct partial_symtab *pst,
18809                     CORE_ADDR lowpc, int decode_mapping)
18810 {
18811   struct objfile *objfile = cu->objfile;
18812   const int decode_for_pst_p = (pst != NULL);
18813
18814   if (decode_mapping)
18815     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
18816
18817   if (decode_for_pst_p)
18818     {
18819       int file_index;
18820
18821       /* Now that we're done scanning the Line Header Program, we can
18822          create the psymtab of each included file.  */
18823       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
18824         if (lh->file_names[file_index].included_p == 1)
18825           {
18826             const char *include_name =
18827               psymtab_include_file_name (lh, file_index, pst, comp_dir);
18828             if (include_name != NULL)
18829               dwarf2_create_include_psymtab (include_name, pst, objfile);
18830           }
18831     }
18832   else
18833     {
18834       /* Make sure a symtab is created for every file, even files
18835          which contain only variables (i.e. no code with associated
18836          line numbers).  */
18837       struct compunit_symtab *cust = buildsym_compunit_symtab ();
18838       int i;
18839
18840       for (i = 0; i < lh->file_names.size (); i++)
18841         {
18842           file_entry &fe = lh->file_names[i];
18843
18844           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
18845
18846           if (current_subfile->symtab == NULL)
18847             {
18848               current_subfile->symtab
18849                 = allocate_symtab (cust, current_subfile->name);
18850             }
18851           fe.symtab = current_subfile->symtab;
18852         }
18853     }
18854 }
18855
18856 /* Start a subfile for DWARF.  FILENAME is the name of the file and
18857    DIRNAME the name of the source directory which contains FILENAME
18858    or NULL if not known.
18859    This routine tries to keep line numbers from identical absolute and
18860    relative file names in a common subfile.
18861
18862    Using the `list' example from the GDB testsuite, which resides in
18863    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
18864    of /srcdir/list0.c yields the following debugging information for list0.c:
18865
18866    DW_AT_name:          /srcdir/list0.c
18867    DW_AT_comp_dir:      /compdir
18868    files.files[0].name: list0.h
18869    files.files[0].dir:  /srcdir
18870    files.files[1].name: list0.c
18871    files.files[1].dir:  /srcdir
18872
18873    The line number information for list0.c has to end up in a single
18874    subfile, so that `break /srcdir/list0.c:1' works as expected.
18875    start_subfile will ensure that this happens provided that we pass the
18876    concatenation of files.files[1].dir and files.files[1].name as the
18877    subfile's name.  */
18878
18879 static void
18880 dwarf2_start_subfile (const char *filename, const char *dirname)
18881 {
18882   char *copy = NULL;
18883
18884   /* In order not to lose the line information directory,
18885      we concatenate it to the filename when it makes sense.
18886      Note that the Dwarf3 standard says (speaking of filenames in line
18887      information): ``The directory index is ignored for file names
18888      that represent full path names''.  Thus ignoring dirname in the
18889      `else' branch below isn't an issue.  */
18890
18891   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
18892     {
18893       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
18894       filename = copy;
18895     }
18896
18897   start_subfile (filename);
18898
18899   if (copy != NULL)
18900     xfree (copy);
18901 }
18902
18903 /* Start a symtab for DWARF.
18904    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
18905
18906 static struct compunit_symtab *
18907 dwarf2_start_symtab (struct dwarf2_cu *cu,
18908                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
18909 {
18910   struct compunit_symtab *cust
18911     = start_symtab (cu->objfile, name, comp_dir, low_pc);
18912
18913   record_debugformat ("DWARF 2");
18914   record_producer (cu->producer);
18915
18916   /* We assume that we're processing GCC output.  */
18917   processing_gcc_compilation = 2;
18918
18919   cu->processing_has_namespace_info = 0;
18920
18921   return cust;
18922 }
18923
18924 static void
18925 var_decode_location (struct attribute *attr, struct symbol *sym,
18926                      struct dwarf2_cu *cu)
18927 {
18928   struct objfile *objfile = cu->objfile;
18929   struct comp_unit_head *cu_header = &cu->header;
18930
18931   /* NOTE drow/2003-01-30: There used to be a comment and some special
18932      code here to turn a symbol with DW_AT_external and a
18933      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
18934      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
18935      with some versions of binutils) where shared libraries could have
18936      relocations against symbols in their debug information - the
18937      minimal symbol would have the right address, but the debug info
18938      would not.  It's no longer necessary, because we will explicitly
18939      apply relocations when we read in the debug information now.  */
18940
18941   /* A DW_AT_location attribute with no contents indicates that a
18942      variable has been optimized away.  */
18943   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
18944     {
18945       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
18946       return;
18947     }
18948
18949   /* Handle one degenerate form of location expression specially, to
18950      preserve GDB's previous behavior when section offsets are
18951      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
18952      then mark this symbol as LOC_STATIC.  */
18953
18954   if (attr_form_is_block (attr)
18955       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
18956            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
18957           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
18958               && (DW_BLOCK (attr)->size
18959                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
18960     {
18961       unsigned int dummy;
18962
18963       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
18964         SYMBOL_VALUE_ADDRESS (sym) =
18965           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
18966       else
18967         SYMBOL_VALUE_ADDRESS (sym) =
18968           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
18969       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
18970       fixup_symbol_section (sym, objfile);
18971       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
18972                                               SYMBOL_SECTION (sym));
18973       return;
18974     }
18975
18976   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
18977      expression evaluator, and use LOC_COMPUTED only when necessary
18978      (i.e. when the value of a register or memory location is
18979      referenced, or a thread-local block, etc.).  Then again, it might
18980      not be worthwhile.  I'm assuming that it isn't unless performance
18981      or memory numbers show me otherwise.  */
18982
18983   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
18984
18985   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
18986     cu->has_loclist = 1;
18987 }
18988
18989 /* Given a pointer to a DWARF information entry, figure out if we need
18990    to make a symbol table entry for it, and if so, create a new entry
18991    and return a pointer to it.
18992    If TYPE is NULL, determine symbol type from the die, otherwise
18993    used the passed type.
18994    If SPACE is not NULL, use it to hold the new symbol.  If it is
18995    NULL, allocate a new symbol on the objfile's obstack.  */
18996
18997 static struct symbol *
18998 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
18999                  struct symbol *space)
19000 {
19001   struct objfile *objfile = cu->objfile;
19002   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19003   struct symbol *sym = NULL;
19004   const char *name;
19005   struct attribute *attr = NULL;
19006   struct attribute *attr2 = NULL;
19007   CORE_ADDR baseaddr;
19008   struct pending **list_to_add = NULL;
19009
19010   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19011
19012   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19013
19014   name = dwarf2_name (die, cu);
19015   if (name)
19016     {
19017       const char *linkagename;
19018       int suppress_add = 0;
19019
19020       if (space)
19021         sym = space;
19022       else
19023         sym = allocate_symbol (objfile);
19024       OBJSTAT (objfile, n_syms++);
19025
19026       /* Cache this symbol's name and the name's demangled form (if any).  */
19027       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19028       linkagename = dwarf2_physname (name, die, cu);
19029       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19030
19031       /* Fortran does not have mangling standard and the mangling does differ
19032          between gfortran, iFort etc.  */
19033       if (cu->language == language_fortran
19034           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19035         symbol_set_demangled_name (&(sym->ginfo),
19036                                    dwarf2_full_name (name, die, cu),
19037                                    NULL);
19038
19039       /* Default assumptions.
19040          Use the passed type or decode it from the die.  */
19041       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19042       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19043       if (type != NULL)
19044         SYMBOL_TYPE (sym) = type;
19045       else
19046         SYMBOL_TYPE (sym) = die_type (die, cu);
19047       attr = dwarf2_attr (die,
19048                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19049                           cu);
19050       if (attr)
19051         {
19052           SYMBOL_LINE (sym) = DW_UNSND (attr);
19053         }
19054
19055       attr = dwarf2_attr (die,
19056                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19057                           cu);
19058       if (attr)
19059         {
19060           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19061           struct file_entry *fe;
19062
19063           if (cu->line_header != NULL)
19064             fe = cu->line_header->file_name_at (file_index);
19065           else
19066             fe = NULL;
19067
19068           if (fe == NULL)
19069             complaint (&symfile_complaints,
19070                        _("file index out of range"));
19071           else
19072             symbol_set_symtab (sym, fe->symtab);
19073         }
19074
19075       switch (die->tag)
19076         {
19077         case DW_TAG_label:
19078           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19079           if (attr)
19080             {
19081               CORE_ADDR addr;
19082
19083               addr = attr_value_as_address (attr);
19084               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19085               SYMBOL_VALUE_ADDRESS (sym) = addr;
19086             }
19087           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19088           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19089           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19090           add_symbol_to_list (sym, cu->list_in_scope);
19091           break;
19092         case DW_TAG_subprogram:
19093           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19094              finish_block.  */
19095           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19096           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19097           if ((attr2 && (DW_UNSND (attr2) != 0))
19098               || cu->language == language_ada)
19099             {
19100               /* Subprograms marked external are stored as a global symbol.
19101                  Ada subprograms, whether marked external or not, are always
19102                  stored as a global symbol, because we want to be able to
19103                  access them globally.  For instance, we want to be able
19104                  to break on a nested subprogram without having to
19105                  specify the context.  */
19106               list_to_add = &global_symbols;
19107             }
19108           else
19109             {
19110               list_to_add = cu->list_in_scope;
19111             }
19112           break;
19113         case DW_TAG_inlined_subroutine:
19114           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19115              finish_block.  */
19116           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19117           SYMBOL_INLINED (sym) = 1;
19118           list_to_add = cu->list_in_scope;
19119           break;
19120         case DW_TAG_template_value_param:
19121           suppress_add = 1;
19122           /* Fall through.  */
19123         case DW_TAG_constant:
19124         case DW_TAG_variable:
19125         case DW_TAG_member:
19126           /* Compilation with minimal debug info may result in
19127              variables with missing type entries.  Change the
19128              misleading `void' type to something sensible.  */
19129           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19130             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19131
19132           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19133           /* In the case of DW_TAG_member, we should only be called for
19134              static const members.  */
19135           if (die->tag == DW_TAG_member)
19136             {
19137               /* dwarf2_add_field uses die_is_declaration,
19138                  so we do the same.  */
19139               gdb_assert (die_is_declaration (die, cu));
19140               gdb_assert (attr);
19141             }
19142           if (attr)
19143             {
19144               dwarf2_const_value (attr, sym, cu);
19145               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19146               if (!suppress_add)
19147                 {
19148                   if (attr2 && (DW_UNSND (attr2) != 0))
19149                     list_to_add = &global_symbols;
19150                   else
19151                     list_to_add = cu->list_in_scope;
19152                 }
19153               break;
19154             }
19155           attr = dwarf2_attr (die, DW_AT_location, cu);
19156           if (attr)
19157             {
19158               var_decode_location (attr, sym, cu);
19159               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19160
19161               /* Fortran explicitly imports any global symbols to the local
19162                  scope by DW_TAG_common_block.  */
19163               if (cu->language == language_fortran && die->parent
19164                   && die->parent->tag == DW_TAG_common_block)
19165                 attr2 = NULL;
19166
19167               if (SYMBOL_CLASS (sym) == LOC_STATIC
19168                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19169                   && !dwarf2_per_objfile->has_section_at_zero)
19170                 {
19171                   /* When a static variable is eliminated by the linker,
19172                      the corresponding debug information is not stripped
19173                      out, but the variable address is set to null;
19174                      do not add such variables into symbol table.  */
19175                 }
19176               else if (attr2 && (DW_UNSND (attr2) != 0))
19177                 {
19178                   /* Workaround gfortran PR debug/40040 - it uses
19179                      DW_AT_location for variables in -fPIC libraries which may
19180                      get overriden by other libraries/executable and get
19181                      a different address.  Resolve it by the minimal symbol
19182                      which may come from inferior's executable using copy
19183                      relocation.  Make this workaround only for gfortran as for
19184                      other compilers GDB cannot guess the minimal symbol
19185                      Fortran mangling kind.  */
19186                   if (cu->language == language_fortran && die->parent
19187                       && die->parent->tag == DW_TAG_module
19188                       && cu->producer
19189                       && startswith (cu->producer, "GNU Fortran"))
19190                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19191
19192                   /* A variable with DW_AT_external is never static,
19193                      but it may be block-scoped.  */
19194                   list_to_add = (cu->list_in_scope == &file_symbols
19195                                  ? &global_symbols : cu->list_in_scope);
19196                 }
19197               else
19198                 list_to_add = cu->list_in_scope;
19199             }
19200           else
19201             {
19202               /* We do not know the address of this symbol.
19203                  If it is an external symbol and we have type information
19204                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19205                  The address of the variable will then be determined from
19206                  the minimal symbol table whenever the variable is
19207                  referenced.  */
19208               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19209
19210               /* Fortran explicitly imports any global symbols to the local
19211                  scope by DW_TAG_common_block.  */
19212               if (cu->language == language_fortran && die->parent
19213                   && die->parent->tag == DW_TAG_common_block)
19214                 {
19215                   /* SYMBOL_CLASS doesn't matter here because
19216                      read_common_block is going to reset it.  */
19217                   if (!suppress_add)
19218                     list_to_add = cu->list_in_scope;
19219                 }
19220               else if (attr2 && (DW_UNSND (attr2) != 0)
19221                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19222                 {
19223                   /* A variable with DW_AT_external is never static, but it
19224                      may be block-scoped.  */
19225                   list_to_add = (cu->list_in_scope == &file_symbols
19226                                  ? &global_symbols : cu->list_in_scope);
19227
19228                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19229                 }
19230               else if (!die_is_declaration (die, cu))
19231                 {
19232                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19233                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19234                   if (!suppress_add)
19235                     list_to_add = cu->list_in_scope;
19236                 }
19237             }
19238           break;
19239         case DW_TAG_formal_parameter:
19240           /* If we are inside a function, mark this as an argument.  If
19241              not, we might be looking at an argument to an inlined function
19242              when we do not have enough information to show inlined frames;
19243              pretend it's a local variable in that case so that the user can
19244              still see it.  */
19245           if (context_stack_depth > 0
19246               && context_stack[context_stack_depth - 1].name != NULL)
19247             SYMBOL_IS_ARGUMENT (sym) = 1;
19248           attr = dwarf2_attr (die, DW_AT_location, cu);
19249           if (attr)
19250             {
19251               var_decode_location (attr, sym, cu);
19252             }
19253           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19254           if (attr)
19255             {
19256               dwarf2_const_value (attr, sym, cu);
19257             }
19258
19259           list_to_add = cu->list_in_scope;
19260           break;
19261         case DW_TAG_unspecified_parameters:
19262           /* From varargs functions; gdb doesn't seem to have any
19263              interest in this information, so just ignore it for now.
19264              (FIXME?) */
19265           break;
19266         case DW_TAG_template_type_param:
19267           suppress_add = 1;
19268           /* Fall through.  */
19269         case DW_TAG_class_type:
19270         case DW_TAG_interface_type:
19271         case DW_TAG_structure_type:
19272         case DW_TAG_union_type:
19273         case DW_TAG_set_type:
19274         case DW_TAG_enumeration_type:
19275           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19276           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19277
19278           {
19279             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19280                really ever be static objects: otherwise, if you try
19281                to, say, break of a class's method and you're in a file
19282                which doesn't mention that class, it won't work unless
19283                the check for all static symbols in lookup_symbol_aux
19284                saves you.  See the OtherFileClass tests in
19285                gdb.c++/namespace.exp.  */
19286
19287             if (!suppress_add)
19288               {
19289                 list_to_add = (cu->list_in_scope == &file_symbols
19290                                && cu->language == language_cplus
19291                                ? &global_symbols : cu->list_in_scope);
19292
19293                 /* The semantics of C++ state that "struct foo {
19294                    ... }" also defines a typedef for "foo".  */
19295                 if (cu->language == language_cplus
19296                     || cu->language == language_ada
19297                     || cu->language == language_d
19298                     || cu->language == language_rust)
19299                   {
19300                     /* The symbol's name is already allocated along
19301                        with this objfile, so we don't need to
19302                        duplicate it for the type.  */
19303                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19304                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19305                   }
19306               }
19307           }
19308           break;
19309         case DW_TAG_typedef:
19310           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19311           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19312           list_to_add = cu->list_in_scope;
19313           break;
19314         case DW_TAG_base_type:
19315         case DW_TAG_subrange_type:
19316           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19317           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19318           list_to_add = cu->list_in_scope;
19319           break;
19320         case DW_TAG_enumerator:
19321           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19322           if (attr)
19323             {
19324               dwarf2_const_value (attr, sym, cu);
19325             }
19326           {
19327             /* NOTE: carlton/2003-11-10: See comment above in the
19328                DW_TAG_class_type, etc. block.  */
19329
19330             list_to_add = (cu->list_in_scope == &file_symbols
19331                            && cu->language == language_cplus
19332                            ? &global_symbols : cu->list_in_scope);
19333           }
19334           break;
19335         case DW_TAG_imported_declaration:
19336         case DW_TAG_namespace:
19337           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19338           list_to_add = &global_symbols;
19339           break;
19340         case DW_TAG_module:
19341           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19342           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19343           list_to_add = &global_symbols;
19344           break;
19345         case DW_TAG_common_block:
19346           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19347           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19348           add_symbol_to_list (sym, cu->list_in_scope);
19349           break;
19350         default:
19351           /* Not a tag we recognize.  Hopefully we aren't processing
19352              trash data, but since we must specifically ignore things
19353              we don't recognize, there is nothing else we should do at
19354              this point.  */
19355           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19356                      dwarf_tag_name (die->tag));
19357           break;
19358         }
19359
19360       if (suppress_add)
19361         {
19362           sym->hash_next = objfile->template_symbols;
19363           objfile->template_symbols = sym;
19364           list_to_add = NULL;
19365         }
19366
19367       if (list_to_add != NULL)
19368         add_symbol_to_list (sym, list_to_add);
19369
19370       /* For the benefit of old versions of GCC, check for anonymous
19371          namespaces based on the demangled name.  */
19372       if (!cu->processing_has_namespace_info
19373           && cu->language == language_cplus)
19374         cp_scan_for_anonymous_namespaces (sym, objfile);
19375     }
19376   return (sym);
19377 }
19378
19379 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19380
19381 static struct symbol *
19382 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19383 {
19384   return new_symbol_full (die, type, cu, NULL);
19385 }
19386
19387 /* Given an attr with a DW_FORM_dataN value in host byte order,
19388    zero-extend it as appropriate for the symbol's type.  The DWARF
19389    standard (v4) is not entirely clear about the meaning of using
19390    DW_FORM_dataN for a constant with a signed type, where the type is
19391    wider than the data.  The conclusion of a discussion on the DWARF
19392    list was that this is unspecified.  We choose to always zero-extend
19393    because that is the interpretation long in use by GCC.  */
19394
19395 static gdb_byte *
19396 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19397                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19398 {
19399   struct objfile *objfile = cu->objfile;
19400   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19401                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19402   LONGEST l = DW_UNSND (attr);
19403
19404   if (bits < sizeof (*value) * 8)
19405     {
19406       l &= ((LONGEST) 1 << bits) - 1;
19407       *value = l;
19408     }
19409   else if (bits == sizeof (*value) * 8)
19410     *value = l;
19411   else
19412     {
19413       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19414       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19415       return bytes;
19416     }
19417
19418   return NULL;
19419 }
19420
19421 /* Read a constant value from an attribute.  Either set *VALUE, or if
19422    the value does not fit in *VALUE, set *BYTES - either already
19423    allocated on the objfile obstack, or newly allocated on OBSTACK,
19424    or, set *BATON, if we translated the constant to a location
19425    expression.  */
19426
19427 static void
19428 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19429                          const char *name, struct obstack *obstack,
19430                          struct dwarf2_cu *cu,
19431                          LONGEST *value, const gdb_byte **bytes,
19432                          struct dwarf2_locexpr_baton **baton)
19433 {
19434   struct objfile *objfile = cu->objfile;
19435   struct comp_unit_head *cu_header = &cu->header;
19436   struct dwarf_block *blk;
19437   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19438                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19439
19440   *value = 0;
19441   *bytes = NULL;
19442   *baton = NULL;
19443
19444   switch (attr->form)
19445     {
19446     case DW_FORM_addr:
19447     case DW_FORM_GNU_addr_index:
19448       {
19449         gdb_byte *data;
19450
19451         if (TYPE_LENGTH (type) != cu_header->addr_size)
19452           dwarf2_const_value_length_mismatch_complaint (name,
19453                                                         cu_header->addr_size,
19454                                                         TYPE_LENGTH (type));
19455         /* Symbols of this form are reasonably rare, so we just
19456            piggyback on the existing location code rather than writing
19457            a new implementation of symbol_computed_ops.  */
19458         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19459         (*baton)->per_cu = cu->per_cu;
19460         gdb_assert ((*baton)->per_cu);
19461
19462         (*baton)->size = 2 + cu_header->addr_size;
19463         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19464         (*baton)->data = data;
19465
19466         data[0] = DW_OP_addr;
19467         store_unsigned_integer (&data[1], cu_header->addr_size,
19468                                 byte_order, DW_ADDR (attr));
19469         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19470       }
19471       break;
19472     case DW_FORM_string:
19473     case DW_FORM_strp:
19474     case DW_FORM_GNU_str_index:
19475     case DW_FORM_GNU_strp_alt:
19476       /* DW_STRING is already allocated on the objfile obstack, point
19477          directly to it.  */
19478       *bytes = (const gdb_byte *) DW_STRING (attr);
19479       break;
19480     case DW_FORM_block1:
19481     case DW_FORM_block2:
19482     case DW_FORM_block4:
19483     case DW_FORM_block:
19484     case DW_FORM_exprloc:
19485     case DW_FORM_data16:
19486       blk = DW_BLOCK (attr);
19487       if (TYPE_LENGTH (type) != blk->size)
19488         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19489                                                       TYPE_LENGTH (type));
19490       *bytes = blk->data;
19491       break;
19492
19493       /* The DW_AT_const_value attributes are supposed to carry the
19494          symbol's value "represented as it would be on the target
19495          architecture."  By the time we get here, it's already been
19496          converted to host endianness, so we just need to sign- or
19497          zero-extend it as appropriate.  */
19498     case DW_FORM_data1:
19499       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19500       break;
19501     case DW_FORM_data2:
19502       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19503       break;
19504     case DW_FORM_data4:
19505       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19506       break;
19507     case DW_FORM_data8:
19508       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19509       break;
19510
19511     case DW_FORM_sdata:
19512     case DW_FORM_implicit_const:
19513       *value = DW_SND (attr);
19514       break;
19515
19516     case DW_FORM_udata:
19517       *value = DW_UNSND (attr);
19518       break;
19519
19520     default:
19521       complaint (&symfile_complaints,
19522                  _("unsupported const value attribute form: '%s'"),
19523                  dwarf_form_name (attr->form));
19524       *value = 0;
19525       break;
19526     }
19527 }
19528
19529
19530 /* Copy constant value from an attribute to a symbol.  */
19531
19532 static void
19533 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19534                     struct dwarf2_cu *cu)
19535 {
19536   struct objfile *objfile = cu->objfile;
19537   LONGEST value;
19538   const gdb_byte *bytes;
19539   struct dwarf2_locexpr_baton *baton;
19540
19541   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19542                            SYMBOL_PRINT_NAME (sym),
19543                            &objfile->objfile_obstack, cu,
19544                            &value, &bytes, &baton);
19545
19546   if (baton != NULL)
19547     {
19548       SYMBOL_LOCATION_BATON (sym) = baton;
19549       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19550     }
19551   else if (bytes != NULL)
19552      {
19553       SYMBOL_VALUE_BYTES (sym) = bytes;
19554       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19555     }
19556   else
19557     {
19558       SYMBOL_VALUE (sym) = value;
19559       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19560     }
19561 }
19562
19563 /* Return the type of the die in question using its DW_AT_type attribute.  */
19564
19565 static struct type *
19566 die_type (struct die_info *die, struct dwarf2_cu *cu)
19567 {
19568   struct attribute *type_attr;
19569
19570   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19571   if (!type_attr)
19572     {
19573       /* A missing DW_AT_type represents a void type.  */
19574       return objfile_type (cu->objfile)->builtin_void;
19575     }
19576
19577   return lookup_die_type (die, type_attr, cu);
19578 }
19579
19580 /* True iff CU's producer generates GNAT Ada auxiliary information
19581    that allows to find parallel types through that information instead
19582    of having to do expensive parallel lookups by type name.  */
19583
19584 static int
19585 need_gnat_info (struct dwarf2_cu *cu)
19586 {
19587   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19588      of GNAT produces this auxiliary information, without any indication
19589      that it is produced.  Part of enhancing the FSF version of GNAT
19590      to produce that information will be to put in place an indicator
19591      that we can use in order to determine whether the descriptive type
19592      info is available or not.  One suggestion that has been made is
19593      to use a new attribute, attached to the CU die.  For now, assume
19594      that the descriptive type info is not available.  */
19595   return 0;
19596 }
19597
19598 /* Return the auxiliary type of the die in question using its
19599    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19600    attribute is not present.  */
19601
19602 static struct type *
19603 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19604 {
19605   struct attribute *type_attr;
19606
19607   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19608   if (!type_attr)
19609     return NULL;
19610
19611   return lookup_die_type (die, type_attr, cu);
19612 }
19613
19614 /* If DIE has a descriptive_type attribute, then set the TYPE's
19615    descriptive type accordingly.  */
19616
19617 static void
19618 set_descriptive_type (struct type *type, struct die_info *die,
19619                       struct dwarf2_cu *cu)
19620 {
19621   struct type *descriptive_type = die_descriptive_type (die, cu);
19622
19623   if (descriptive_type)
19624     {
19625       ALLOCATE_GNAT_AUX_TYPE (type);
19626       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19627     }
19628 }
19629
19630 /* Return the containing type of the die in question using its
19631    DW_AT_containing_type attribute.  */
19632
19633 static struct type *
19634 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19635 {
19636   struct attribute *type_attr;
19637
19638   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19639   if (!type_attr)
19640     error (_("Dwarf Error: Problem turning containing type into gdb type "
19641              "[in module %s]"), objfile_name (cu->objfile));
19642
19643   return lookup_die_type (die, type_attr, cu);
19644 }
19645
19646 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19647
19648 static struct type *
19649 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19650 {
19651   struct objfile *objfile = dwarf2_per_objfile->objfile;
19652   char *message, *saved;
19653
19654   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19655                         objfile_name (objfile),
19656                         to_underlying (cu->header.sect_off),
19657                         to_underlying (die->sect_off));
19658   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19659                                   message, strlen (message));
19660   xfree (message);
19661
19662   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19663 }
19664
19665 /* Look up the type of DIE in CU using its type attribute ATTR.
19666    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19667    DW_AT_containing_type.
19668    If there is no type substitute an error marker.  */
19669
19670 static struct type *
19671 lookup_die_type (struct die_info *die, const struct attribute *attr,
19672                  struct dwarf2_cu *cu)
19673 {
19674   struct objfile *objfile = cu->objfile;
19675   struct type *this_type;
19676
19677   gdb_assert (attr->name == DW_AT_type
19678               || attr->name == DW_AT_GNAT_descriptive_type
19679               || attr->name == DW_AT_containing_type);
19680
19681   /* First see if we have it cached.  */
19682
19683   if (attr->form == DW_FORM_GNU_ref_alt)
19684     {
19685       struct dwarf2_per_cu_data *per_cu;
19686       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19687
19688       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
19689       this_type = get_die_type_at_offset (sect_off, per_cu);
19690     }
19691   else if (attr_form_is_ref (attr))
19692     {
19693       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
19694
19695       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
19696     }
19697   else if (attr->form == DW_FORM_ref_sig8)
19698     {
19699       ULONGEST signature = DW_SIGNATURE (attr);
19700
19701       return get_signatured_type (die, signature, cu);
19702     }
19703   else
19704     {
19705       complaint (&symfile_complaints,
19706                  _("Dwarf Error: Bad type attribute %s in DIE"
19707                    " at 0x%x [in module %s]"),
19708                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
19709                  objfile_name (objfile));
19710       return build_error_marker_type (cu, die);
19711     }
19712
19713   /* If not cached we need to read it in.  */
19714
19715   if (this_type == NULL)
19716     {
19717       struct die_info *type_die = NULL;
19718       struct dwarf2_cu *type_cu = cu;
19719
19720       if (attr_form_is_ref (attr))
19721         type_die = follow_die_ref (die, attr, &type_cu);
19722       if (type_die == NULL)
19723         return build_error_marker_type (cu, die);
19724       /* If we find the type now, it's probably because the type came
19725          from an inter-CU reference and the type's CU got expanded before
19726          ours.  */
19727       this_type = read_type_die (type_die, type_cu);
19728     }
19729
19730   /* If we still don't have a type use an error marker.  */
19731
19732   if (this_type == NULL)
19733     return build_error_marker_type (cu, die);
19734
19735   return this_type;
19736 }
19737
19738 /* Return the type in DIE, CU.
19739    Returns NULL for invalid types.
19740
19741    This first does a lookup in die_type_hash,
19742    and only reads the die in if necessary.
19743
19744    NOTE: This can be called when reading in partial or full symbols.  */
19745
19746 static struct type *
19747 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
19748 {
19749   struct type *this_type;
19750
19751   this_type = get_die_type (die, cu);
19752   if (this_type)
19753     return this_type;
19754
19755   return read_type_die_1 (die, cu);
19756 }
19757
19758 /* Read the type in DIE, CU.
19759    Returns NULL for invalid types.  */
19760
19761 static struct type *
19762 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
19763 {
19764   struct type *this_type = NULL;
19765
19766   switch (die->tag)
19767     {
19768     case DW_TAG_class_type:
19769     case DW_TAG_interface_type:
19770     case DW_TAG_structure_type:
19771     case DW_TAG_union_type:
19772       this_type = read_structure_type (die, cu);
19773       break;
19774     case DW_TAG_enumeration_type:
19775       this_type = read_enumeration_type (die, cu);
19776       break;
19777     case DW_TAG_subprogram:
19778     case DW_TAG_subroutine_type:
19779     case DW_TAG_inlined_subroutine:
19780       this_type = read_subroutine_type (die, cu);
19781       break;
19782     case DW_TAG_array_type:
19783       this_type = read_array_type (die, cu);
19784       break;
19785     case DW_TAG_set_type:
19786       this_type = read_set_type (die, cu);
19787       break;
19788     case DW_TAG_pointer_type:
19789       this_type = read_tag_pointer_type (die, cu);
19790       break;
19791     case DW_TAG_ptr_to_member_type:
19792       this_type = read_tag_ptr_to_member_type (die, cu);
19793       break;
19794     case DW_TAG_reference_type:
19795       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
19796       break;
19797     case DW_TAG_rvalue_reference_type:
19798       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
19799       break;
19800     case DW_TAG_const_type:
19801       this_type = read_tag_const_type (die, cu);
19802       break;
19803     case DW_TAG_volatile_type:
19804       this_type = read_tag_volatile_type (die, cu);
19805       break;
19806     case DW_TAG_restrict_type:
19807       this_type = read_tag_restrict_type (die, cu);
19808       break;
19809     case DW_TAG_string_type:
19810       this_type = read_tag_string_type (die, cu);
19811       break;
19812     case DW_TAG_typedef:
19813       this_type = read_typedef (die, cu);
19814       break;
19815     case DW_TAG_subrange_type:
19816       this_type = read_subrange_type (die, cu);
19817       break;
19818     case DW_TAG_base_type:
19819       this_type = read_base_type (die, cu);
19820       break;
19821     case DW_TAG_unspecified_type:
19822       this_type = read_unspecified_type (die, cu);
19823       break;
19824     case DW_TAG_namespace:
19825       this_type = read_namespace_type (die, cu);
19826       break;
19827     case DW_TAG_module:
19828       this_type = read_module_type (die, cu);
19829       break;
19830     case DW_TAG_atomic_type:
19831       this_type = read_tag_atomic_type (die, cu);
19832       break;
19833     default:
19834       complaint (&symfile_complaints,
19835                  _("unexpected tag in read_type_die: '%s'"),
19836                  dwarf_tag_name (die->tag));
19837       break;
19838     }
19839
19840   return this_type;
19841 }
19842
19843 /* See if we can figure out if the class lives in a namespace.  We do
19844    this by looking for a member function; its demangled name will
19845    contain namespace info, if there is any.
19846    Return the computed name or NULL.
19847    Space for the result is allocated on the objfile's obstack.
19848    This is the full-die version of guess_partial_die_structure_name.
19849    In this case we know DIE has no useful parent.  */
19850
19851 static char *
19852 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
19853 {
19854   struct die_info *spec_die;
19855   struct dwarf2_cu *spec_cu;
19856   struct die_info *child;
19857
19858   spec_cu = cu;
19859   spec_die = die_specification (die, &spec_cu);
19860   if (spec_die != NULL)
19861     {
19862       die = spec_die;
19863       cu = spec_cu;
19864     }
19865
19866   for (child = die->child;
19867        child != NULL;
19868        child = child->sibling)
19869     {
19870       if (child->tag == DW_TAG_subprogram)
19871         {
19872           const char *linkage_name = dw2_linkage_name (child, cu);
19873
19874           if (linkage_name != NULL)
19875             {
19876               char *actual_name
19877                 = language_class_name_from_physname (cu->language_defn,
19878                                                      linkage_name);
19879               char *name = NULL;
19880
19881               if (actual_name != NULL)
19882                 {
19883                   const char *die_name = dwarf2_name (die, cu);
19884
19885                   if (die_name != NULL
19886                       && strcmp (die_name, actual_name) != 0)
19887                     {
19888                       /* Strip off the class name from the full name.
19889                          We want the prefix.  */
19890                       int die_name_len = strlen (die_name);
19891                       int actual_name_len = strlen (actual_name);
19892
19893                       /* Test for '::' as a sanity check.  */
19894                       if (actual_name_len > die_name_len + 2
19895                           && actual_name[actual_name_len
19896                                          - die_name_len - 1] == ':')
19897                         name = (char *) obstack_copy0 (
19898                           &cu->objfile->per_bfd->storage_obstack,
19899                           actual_name, actual_name_len - die_name_len - 2);
19900                     }
19901                 }
19902               xfree (actual_name);
19903               return name;
19904             }
19905         }
19906     }
19907
19908   return NULL;
19909 }
19910
19911 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
19912    prefix part in such case.  See
19913    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
19914
19915 static const char *
19916 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
19917 {
19918   struct attribute *attr;
19919   const char *base;
19920
19921   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
19922       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
19923     return NULL;
19924
19925   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
19926     return NULL;
19927
19928   attr = dw2_linkage_name_attr (die, cu);
19929   if (attr == NULL || DW_STRING (attr) == NULL)
19930     return NULL;
19931
19932   /* dwarf2_name had to be already called.  */
19933   gdb_assert (DW_STRING_IS_CANONICAL (attr));
19934
19935   /* Strip the base name, keep any leading namespaces/classes.  */
19936   base = strrchr (DW_STRING (attr), ':');
19937   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
19938     return "";
19939
19940   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
19941                                  DW_STRING (attr),
19942                                  &base[-1] - DW_STRING (attr));
19943 }
19944
19945 /* Return the name of the namespace/class that DIE is defined within,
19946    or "" if we can't tell.  The caller should not xfree the result.
19947
19948    For example, if we're within the method foo() in the following
19949    code:
19950
19951    namespace N {
19952      class C {
19953        void foo () {
19954        }
19955      };
19956    }
19957
19958    then determine_prefix on foo's die will return "N::C".  */
19959
19960 static const char *
19961 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
19962 {
19963   struct die_info *parent, *spec_die;
19964   struct dwarf2_cu *spec_cu;
19965   struct type *parent_type;
19966   const char *retval;
19967
19968   if (cu->language != language_cplus
19969       && cu->language != language_fortran && cu->language != language_d
19970       && cu->language != language_rust)
19971     return "";
19972
19973   retval = anonymous_struct_prefix (die, cu);
19974   if (retval)
19975     return retval;
19976
19977   /* We have to be careful in the presence of DW_AT_specification.
19978      For example, with GCC 3.4, given the code
19979
19980      namespace N {
19981        void foo() {
19982          // Definition of N::foo.
19983        }
19984      }
19985
19986      then we'll have a tree of DIEs like this:
19987
19988      1: DW_TAG_compile_unit
19989        2: DW_TAG_namespace        // N
19990          3: DW_TAG_subprogram     // declaration of N::foo
19991        4: DW_TAG_subprogram       // definition of N::foo
19992             DW_AT_specification   // refers to die #3
19993
19994      Thus, when processing die #4, we have to pretend that we're in
19995      the context of its DW_AT_specification, namely the contex of die
19996      #3.  */
19997   spec_cu = cu;
19998   spec_die = die_specification (die, &spec_cu);
19999   if (spec_die == NULL)
20000     parent = die->parent;
20001   else
20002     {
20003       parent = spec_die->parent;
20004       cu = spec_cu;
20005     }
20006
20007   if (parent == NULL)
20008     return "";
20009   else if (parent->building_fullname)
20010     {
20011       const char *name;
20012       const char *parent_name;
20013
20014       /* It has been seen on RealView 2.2 built binaries,
20015          DW_TAG_template_type_param types actually _defined_ as
20016          children of the parent class:
20017
20018          enum E {};
20019          template class <class Enum> Class{};
20020          Class<enum E> class_e;
20021
20022          1: DW_TAG_class_type (Class)
20023            2: DW_TAG_enumeration_type (E)
20024              3: DW_TAG_enumerator (enum1:0)
20025              3: DW_TAG_enumerator (enum2:1)
20026              ...
20027            2: DW_TAG_template_type_param
20028               DW_AT_type  DW_FORM_ref_udata (E)
20029
20030          Besides being broken debug info, it can put GDB into an
20031          infinite loop.  Consider:
20032
20033          When we're building the full name for Class<E>, we'll start
20034          at Class, and go look over its template type parameters,
20035          finding E.  We'll then try to build the full name of E, and
20036          reach here.  We're now trying to build the full name of E,
20037          and look over the parent DIE for containing scope.  In the
20038          broken case, if we followed the parent DIE of E, we'd again
20039          find Class, and once again go look at its template type
20040          arguments, etc., etc.  Simply don't consider such parent die
20041          as source-level parent of this die (it can't be, the language
20042          doesn't allow it), and break the loop here.  */
20043       name = dwarf2_name (die, cu);
20044       parent_name = dwarf2_name (parent, cu);
20045       complaint (&symfile_complaints,
20046                  _("template param type '%s' defined within parent '%s'"),
20047                  name ? name : "<unknown>",
20048                  parent_name ? parent_name : "<unknown>");
20049       return "";
20050     }
20051   else
20052     switch (parent->tag)
20053       {
20054       case DW_TAG_namespace:
20055         parent_type = read_type_die (parent, cu);
20056         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20057            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20058            Work around this problem here.  */
20059         if (cu->language == language_cplus
20060             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20061           return "";
20062         /* We give a name to even anonymous namespaces.  */
20063         return TYPE_TAG_NAME (parent_type);
20064       case DW_TAG_class_type:
20065       case DW_TAG_interface_type:
20066       case DW_TAG_structure_type:
20067       case DW_TAG_union_type:
20068       case DW_TAG_module:
20069         parent_type = read_type_die (parent, cu);
20070         if (TYPE_TAG_NAME (parent_type) != NULL)
20071           return TYPE_TAG_NAME (parent_type);
20072         else
20073           /* An anonymous structure is only allowed non-static data
20074              members; no typedefs, no member functions, et cetera.
20075              So it does not need a prefix.  */
20076           return "";
20077       case DW_TAG_compile_unit:
20078       case DW_TAG_partial_unit:
20079         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20080         if (cu->language == language_cplus
20081             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20082             && die->child != NULL
20083             && (die->tag == DW_TAG_class_type
20084                 || die->tag == DW_TAG_structure_type
20085                 || die->tag == DW_TAG_union_type))
20086           {
20087             char *name = guess_full_die_structure_name (die, cu);
20088             if (name != NULL)
20089               return name;
20090           }
20091         return "";
20092       case DW_TAG_enumeration_type:
20093         parent_type = read_type_die (parent, cu);
20094         if (TYPE_DECLARED_CLASS (parent_type))
20095           {
20096             if (TYPE_TAG_NAME (parent_type) != NULL)
20097               return TYPE_TAG_NAME (parent_type);
20098             return "";
20099           }
20100         /* Fall through.  */
20101       default:
20102         return determine_prefix (parent, cu);
20103       }
20104 }
20105
20106 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20107    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20108    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20109    an obconcat, otherwise allocate storage for the result.  The CU argument is
20110    used to determine the language and hence, the appropriate separator.  */
20111
20112 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20113
20114 static char *
20115 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20116                  int physname, struct dwarf2_cu *cu)
20117 {
20118   const char *lead = "";
20119   const char *sep;
20120
20121   if (suffix == NULL || suffix[0] == '\0'
20122       || prefix == NULL || prefix[0] == '\0')
20123     sep = "";
20124   else if (cu->language == language_d)
20125     {
20126       /* For D, the 'main' function could be defined in any module, but it
20127          should never be prefixed.  */
20128       if (strcmp (suffix, "D main") == 0)
20129         {
20130           prefix = "";
20131           sep = "";
20132         }
20133       else
20134         sep = ".";
20135     }
20136   else if (cu->language == language_fortran && physname)
20137     {
20138       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20139          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20140
20141       lead = "__";
20142       sep = "_MOD_";
20143     }
20144   else
20145     sep = "::";
20146
20147   if (prefix == NULL)
20148     prefix = "";
20149   if (suffix == NULL)
20150     suffix = "";
20151
20152   if (obs == NULL)
20153     {
20154       char *retval
20155         = ((char *)
20156            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20157
20158       strcpy (retval, lead);
20159       strcat (retval, prefix);
20160       strcat (retval, sep);
20161       strcat (retval, suffix);
20162       return retval;
20163     }
20164   else
20165     {
20166       /* We have an obstack.  */
20167       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20168     }
20169 }
20170
20171 /* Return sibling of die, NULL if no sibling.  */
20172
20173 static struct die_info *
20174 sibling_die (struct die_info *die)
20175 {
20176   return die->sibling;
20177 }
20178
20179 /* Get name of a die, return NULL if not found.  */
20180
20181 static const char *
20182 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20183                           struct obstack *obstack)
20184 {
20185   if (name && cu->language == language_cplus)
20186     {
20187       std::string canon_name = cp_canonicalize_string (name);
20188
20189       if (!canon_name.empty ())
20190         {
20191           if (canon_name != name)
20192             name = (const char *) obstack_copy0 (obstack,
20193                                                  canon_name.c_str (),
20194                                                  canon_name.length ());
20195         }
20196     }
20197
20198   return name;
20199 }
20200
20201 /* Get name of a die, return NULL if not found.
20202    Anonymous namespaces are converted to their magic string.  */
20203
20204 static const char *
20205 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20206 {
20207   struct attribute *attr;
20208
20209   attr = dwarf2_attr (die, DW_AT_name, cu);
20210   if ((!attr || !DW_STRING (attr))
20211       && die->tag != DW_TAG_namespace
20212       && die->tag != DW_TAG_class_type
20213       && die->tag != DW_TAG_interface_type
20214       && die->tag != DW_TAG_structure_type
20215       && die->tag != DW_TAG_union_type)
20216     return NULL;
20217
20218   switch (die->tag)
20219     {
20220     case DW_TAG_compile_unit:
20221     case DW_TAG_partial_unit:
20222       /* Compilation units have a DW_AT_name that is a filename, not
20223          a source language identifier.  */
20224     case DW_TAG_enumeration_type:
20225     case DW_TAG_enumerator:
20226       /* These tags always have simple identifiers already; no need
20227          to canonicalize them.  */
20228       return DW_STRING (attr);
20229
20230     case DW_TAG_namespace:
20231       if (attr != NULL && DW_STRING (attr) != NULL)
20232         return DW_STRING (attr);
20233       return CP_ANONYMOUS_NAMESPACE_STR;
20234
20235     case DW_TAG_class_type:
20236     case DW_TAG_interface_type:
20237     case DW_TAG_structure_type:
20238     case DW_TAG_union_type:
20239       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20240          structures or unions.  These were of the form "._%d" in GCC 4.1,
20241          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20242          and GCC 4.4.  We work around this problem by ignoring these.  */
20243       if (attr && DW_STRING (attr)
20244           && (startswith (DW_STRING (attr), "._")
20245               || startswith (DW_STRING (attr), "<anonymous")))
20246         return NULL;
20247
20248       /* GCC might emit a nameless typedef that has a linkage name.  See
20249          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20250       if (!attr || DW_STRING (attr) == NULL)
20251         {
20252           char *demangled = NULL;
20253
20254           attr = dw2_linkage_name_attr (die, cu);
20255           if (attr == NULL || DW_STRING (attr) == NULL)
20256             return NULL;
20257
20258           /* Avoid demangling DW_STRING (attr) the second time on a second
20259              call for the same DIE.  */
20260           if (!DW_STRING_IS_CANONICAL (attr))
20261             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20262
20263           if (demangled)
20264             {
20265               const char *base;
20266
20267               /* FIXME: we already did this for the partial symbol... */
20268               DW_STRING (attr)
20269                 = ((const char *)
20270                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20271                                   demangled, strlen (demangled)));
20272               DW_STRING_IS_CANONICAL (attr) = 1;
20273               xfree (demangled);
20274
20275               /* Strip any leading namespaces/classes, keep only the base name.
20276                  DW_AT_name for named DIEs does not contain the prefixes.  */
20277               base = strrchr (DW_STRING (attr), ':');
20278               if (base && base > DW_STRING (attr) && base[-1] == ':')
20279                 return &base[1];
20280               else
20281                 return DW_STRING (attr);
20282             }
20283         }
20284       break;
20285
20286     default:
20287       break;
20288     }
20289
20290   if (!DW_STRING_IS_CANONICAL (attr))
20291     {
20292       DW_STRING (attr)
20293         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20294                                     &cu->objfile->per_bfd->storage_obstack);
20295       DW_STRING_IS_CANONICAL (attr) = 1;
20296     }
20297   return DW_STRING (attr);
20298 }
20299
20300 /* Return the die that this die in an extension of, or NULL if there
20301    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20302    containing the return value on output.  */
20303
20304 static struct die_info *
20305 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20306 {
20307   struct attribute *attr;
20308
20309   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20310   if (attr == NULL)
20311     return NULL;
20312
20313   return follow_die_ref (die, attr, ext_cu);
20314 }
20315
20316 /* Convert a DIE tag into its string name.  */
20317
20318 static const char *
20319 dwarf_tag_name (unsigned tag)
20320 {
20321   const char *name = get_DW_TAG_name (tag);
20322
20323   if (name == NULL)
20324     return "DW_TAG_<unknown>";
20325
20326   return name;
20327 }
20328
20329 /* Convert a DWARF attribute code into its string name.  */
20330
20331 static const char *
20332 dwarf_attr_name (unsigned attr)
20333 {
20334   const char *name;
20335
20336 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20337   if (attr == DW_AT_MIPS_fde)
20338     return "DW_AT_MIPS_fde";
20339 #else
20340   if (attr == DW_AT_HP_block_index)
20341     return "DW_AT_HP_block_index";
20342 #endif
20343
20344   name = get_DW_AT_name (attr);
20345
20346   if (name == NULL)
20347     return "DW_AT_<unknown>";
20348
20349   return name;
20350 }
20351
20352 /* Convert a DWARF value form code into its string name.  */
20353
20354 static const char *
20355 dwarf_form_name (unsigned form)
20356 {
20357   const char *name = get_DW_FORM_name (form);
20358
20359   if (name == NULL)
20360     return "DW_FORM_<unknown>";
20361
20362   return name;
20363 }
20364
20365 static const char *
20366 dwarf_bool_name (unsigned mybool)
20367 {
20368   if (mybool)
20369     return "TRUE";
20370   else
20371     return "FALSE";
20372 }
20373
20374 /* Convert a DWARF type code into its string name.  */
20375
20376 static const char *
20377 dwarf_type_encoding_name (unsigned enc)
20378 {
20379   const char *name = get_DW_ATE_name (enc);
20380
20381   if (name == NULL)
20382     return "DW_ATE_<unknown>";
20383
20384   return name;
20385 }
20386
20387 static void
20388 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20389 {
20390   unsigned int i;
20391
20392   print_spaces (indent, f);
20393   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20394                       dwarf_tag_name (die->tag), die->abbrev,
20395                       to_underlying (die->sect_off));
20396
20397   if (die->parent != NULL)
20398     {
20399       print_spaces (indent, f);
20400       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20401                           to_underlying (die->parent->sect_off));
20402     }
20403
20404   print_spaces (indent, f);
20405   fprintf_unfiltered (f, "  has children: %s\n",
20406            dwarf_bool_name (die->child != NULL));
20407
20408   print_spaces (indent, f);
20409   fprintf_unfiltered (f, "  attributes:\n");
20410
20411   for (i = 0; i < die->num_attrs; ++i)
20412     {
20413       print_spaces (indent, f);
20414       fprintf_unfiltered (f, "    %s (%s) ",
20415                dwarf_attr_name (die->attrs[i].name),
20416                dwarf_form_name (die->attrs[i].form));
20417
20418       switch (die->attrs[i].form)
20419         {
20420         case DW_FORM_addr:
20421         case DW_FORM_GNU_addr_index:
20422           fprintf_unfiltered (f, "address: ");
20423           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20424           break;
20425         case DW_FORM_block2:
20426         case DW_FORM_block4:
20427         case DW_FORM_block:
20428         case DW_FORM_block1:
20429           fprintf_unfiltered (f, "block: size %s",
20430                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20431           break;
20432         case DW_FORM_exprloc:
20433           fprintf_unfiltered (f, "expression: size %s",
20434                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20435           break;
20436         case DW_FORM_data16:
20437           fprintf_unfiltered (f, "constant of 16 bytes");
20438           break;
20439         case DW_FORM_ref_addr:
20440           fprintf_unfiltered (f, "ref address: ");
20441           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20442           break;
20443         case DW_FORM_GNU_ref_alt:
20444           fprintf_unfiltered (f, "alt ref address: ");
20445           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20446           break;
20447         case DW_FORM_ref1:
20448         case DW_FORM_ref2:
20449         case DW_FORM_ref4:
20450         case DW_FORM_ref8:
20451         case DW_FORM_ref_udata:
20452           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20453                               (long) (DW_UNSND (&die->attrs[i])));
20454           break;
20455         case DW_FORM_data1:
20456         case DW_FORM_data2:
20457         case DW_FORM_data4:
20458         case DW_FORM_data8:
20459         case DW_FORM_udata:
20460         case DW_FORM_sdata:
20461           fprintf_unfiltered (f, "constant: %s",
20462                               pulongest (DW_UNSND (&die->attrs[i])));
20463           break;
20464         case DW_FORM_sec_offset:
20465           fprintf_unfiltered (f, "section offset: %s",
20466                               pulongest (DW_UNSND (&die->attrs[i])));
20467           break;
20468         case DW_FORM_ref_sig8:
20469           fprintf_unfiltered (f, "signature: %s",
20470                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20471           break;
20472         case DW_FORM_string:
20473         case DW_FORM_strp:
20474         case DW_FORM_line_strp:
20475         case DW_FORM_GNU_str_index:
20476         case DW_FORM_GNU_strp_alt:
20477           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20478                    DW_STRING (&die->attrs[i])
20479                    ? DW_STRING (&die->attrs[i]) : "",
20480                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20481           break;
20482         case DW_FORM_flag:
20483           if (DW_UNSND (&die->attrs[i]))
20484             fprintf_unfiltered (f, "flag: TRUE");
20485           else
20486             fprintf_unfiltered (f, "flag: FALSE");
20487           break;
20488         case DW_FORM_flag_present:
20489           fprintf_unfiltered (f, "flag: TRUE");
20490           break;
20491         case DW_FORM_indirect:
20492           /* The reader will have reduced the indirect form to
20493              the "base form" so this form should not occur.  */
20494           fprintf_unfiltered (f, 
20495                               "unexpected attribute form: DW_FORM_indirect");
20496           break;
20497         case DW_FORM_implicit_const:
20498           fprintf_unfiltered (f, "constant: %s",
20499                               plongest (DW_SND (&die->attrs[i])));
20500           break;
20501         default:
20502           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20503                    die->attrs[i].form);
20504           break;
20505         }
20506       fprintf_unfiltered (f, "\n");
20507     }
20508 }
20509
20510 static void
20511 dump_die_for_error (struct die_info *die)
20512 {
20513   dump_die_shallow (gdb_stderr, 0, die);
20514 }
20515
20516 static void
20517 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20518 {
20519   int indent = level * 4;
20520
20521   gdb_assert (die != NULL);
20522
20523   if (level >= max_level)
20524     return;
20525
20526   dump_die_shallow (f, indent, die);
20527
20528   if (die->child != NULL)
20529     {
20530       print_spaces (indent, f);
20531       fprintf_unfiltered (f, "  Children:");
20532       if (level + 1 < max_level)
20533         {
20534           fprintf_unfiltered (f, "\n");
20535           dump_die_1 (f, level + 1, max_level, die->child);
20536         }
20537       else
20538         {
20539           fprintf_unfiltered (f,
20540                               " [not printed, max nesting level reached]\n");
20541         }
20542     }
20543
20544   if (die->sibling != NULL && level > 0)
20545     {
20546       dump_die_1 (f, level, max_level, die->sibling);
20547     }
20548 }
20549
20550 /* This is called from the pdie macro in gdbinit.in.
20551    It's not static so gcc will keep a copy callable from gdb.  */
20552
20553 void
20554 dump_die (struct die_info *die, int max_level)
20555 {
20556   dump_die_1 (gdb_stdlog, 0, max_level, die);
20557 }
20558
20559 static void
20560 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20561 {
20562   void **slot;
20563
20564   slot = htab_find_slot_with_hash (cu->die_hash, die,
20565                                    to_underlying (die->sect_off),
20566                                    INSERT);
20567
20568   *slot = die;
20569 }
20570
20571 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20572    required kind.  */
20573
20574 static sect_offset
20575 dwarf2_get_ref_die_offset (const struct attribute *attr)
20576 {
20577   if (attr_form_is_ref (attr))
20578     return (sect_offset) DW_UNSND (attr);
20579
20580   complaint (&symfile_complaints,
20581              _("unsupported die ref attribute form: '%s'"),
20582              dwarf_form_name (attr->form));
20583   return {};
20584 }
20585
20586 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20587  * the value held by the attribute is not constant.  */
20588
20589 static LONGEST
20590 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20591 {
20592   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20593     return DW_SND (attr);
20594   else if (attr->form == DW_FORM_udata
20595            || attr->form == DW_FORM_data1
20596            || attr->form == DW_FORM_data2
20597            || attr->form == DW_FORM_data4
20598            || attr->form == DW_FORM_data8)
20599     return DW_UNSND (attr);
20600   else
20601     {
20602       /* For DW_FORM_data16 see attr_form_is_constant.  */
20603       complaint (&symfile_complaints,
20604                  _("Attribute value is not a constant (%s)"),
20605                  dwarf_form_name (attr->form));
20606       return default_value;
20607     }
20608 }
20609
20610 /* Follow reference or signature attribute ATTR of SRC_DIE.
20611    On entry *REF_CU is the CU of SRC_DIE.
20612    On exit *REF_CU is the CU of the result.  */
20613
20614 static struct die_info *
20615 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20616                        struct dwarf2_cu **ref_cu)
20617 {
20618   struct die_info *die;
20619
20620   if (attr_form_is_ref (attr))
20621     die = follow_die_ref (src_die, attr, ref_cu);
20622   else if (attr->form == DW_FORM_ref_sig8)
20623     die = follow_die_sig (src_die, attr, ref_cu);
20624   else
20625     {
20626       dump_die_for_error (src_die);
20627       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20628              objfile_name ((*ref_cu)->objfile));
20629     }
20630
20631   return die;
20632 }
20633
20634 /* Follow reference OFFSET.
20635    On entry *REF_CU is the CU of the source die referencing OFFSET.
20636    On exit *REF_CU is the CU of the result.
20637    Returns NULL if OFFSET is invalid.  */
20638
20639 static struct die_info *
20640 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20641                    struct dwarf2_cu **ref_cu)
20642 {
20643   struct die_info temp_die;
20644   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20645
20646   gdb_assert (cu->per_cu != NULL);
20647
20648   target_cu = cu;
20649
20650   if (cu->per_cu->is_debug_types)
20651     {
20652       /* .debug_types CUs cannot reference anything outside their CU.
20653          If they need to, they have to reference a signatured type via
20654          DW_FORM_ref_sig8.  */
20655       if (!offset_in_cu_p (&cu->header, sect_off))
20656         return NULL;
20657     }
20658   else if (offset_in_dwz != cu->per_cu->is_dwz
20659            || !offset_in_cu_p (&cu->header, sect_off))
20660     {
20661       struct dwarf2_per_cu_data *per_cu;
20662
20663       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20664                                                  cu->objfile);
20665
20666       /* If necessary, add it to the queue and load its DIEs.  */
20667       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20668         load_full_comp_unit (per_cu, cu->language);
20669
20670       target_cu = per_cu->cu;
20671     }
20672   else if (cu->dies == NULL)
20673     {
20674       /* We're loading full DIEs during partial symbol reading.  */
20675       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
20676       load_full_comp_unit (cu->per_cu, language_minimal);
20677     }
20678
20679   *ref_cu = target_cu;
20680   temp_die.sect_off = sect_off;
20681   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
20682                                                   &temp_die,
20683                                                   to_underlying (sect_off));
20684 }
20685
20686 /* Follow reference attribute ATTR of SRC_DIE.
20687    On entry *REF_CU is the CU of SRC_DIE.
20688    On exit *REF_CU is the CU of the result.  */
20689
20690 static struct die_info *
20691 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
20692                 struct dwarf2_cu **ref_cu)
20693 {
20694   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20695   struct dwarf2_cu *cu = *ref_cu;
20696   struct die_info *die;
20697
20698   die = follow_die_offset (sect_off,
20699                            (attr->form == DW_FORM_GNU_ref_alt
20700                             || cu->per_cu->is_dwz),
20701                            ref_cu);
20702   if (!die)
20703     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
20704            "at 0x%x [in module %s]"),
20705            to_underlying (sect_off), to_underlying (src_die->sect_off),
20706            objfile_name (cu->objfile));
20707
20708   return die;
20709 }
20710
20711 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
20712    Returned value is intended for DW_OP_call*.  Returned
20713    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
20714
20715 struct dwarf2_locexpr_baton
20716 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
20717                                struct dwarf2_per_cu_data *per_cu,
20718                                CORE_ADDR (*get_frame_pc) (void *baton),
20719                                void *baton)
20720 {
20721   struct dwarf2_cu *cu;
20722   struct die_info *die;
20723   struct attribute *attr;
20724   struct dwarf2_locexpr_baton retval;
20725
20726   dw2_setup (per_cu->objfile);
20727
20728   if (per_cu->cu == NULL)
20729     load_cu (per_cu);
20730   cu = per_cu->cu;
20731   if (cu == NULL)
20732     {
20733       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20734          Instead just throw an error, not much else we can do.  */
20735       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20736              to_underlying (sect_off), objfile_name (per_cu->objfile));
20737     }
20738
20739   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20740   if (!die)
20741     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20742            to_underlying (sect_off), objfile_name (per_cu->objfile));
20743
20744   attr = dwarf2_attr (die, DW_AT_location, cu);
20745   if (!attr)
20746     {
20747       /* DWARF: "If there is no such attribute, then there is no effect.".
20748          DATA is ignored if SIZE is 0.  */
20749
20750       retval.data = NULL;
20751       retval.size = 0;
20752     }
20753   else if (attr_form_is_section_offset (attr))
20754     {
20755       struct dwarf2_loclist_baton loclist_baton;
20756       CORE_ADDR pc = (*get_frame_pc) (baton);
20757       size_t size;
20758
20759       fill_in_loclist_baton (cu, &loclist_baton, attr);
20760
20761       retval.data = dwarf2_find_location_expression (&loclist_baton,
20762                                                      &size, pc);
20763       retval.size = size;
20764     }
20765   else
20766     {
20767       if (!attr_form_is_block (attr))
20768         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
20769                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
20770                to_underlying (sect_off), objfile_name (per_cu->objfile));
20771
20772       retval.data = DW_BLOCK (attr)->data;
20773       retval.size = DW_BLOCK (attr)->size;
20774     }
20775   retval.per_cu = cu->per_cu;
20776
20777   age_cached_comp_units ();
20778
20779   return retval;
20780 }
20781
20782 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
20783    offset.  */
20784
20785 struct dwarf2_locexpr_baton
20786 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
20787                              struct dwarf2_per_cu_data *per_cu,
20788                              CORE_ADDR (*get_frame_pc) (void *baton),
20789                              void *baton)
20790 {
20791   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
20792
20793   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
20794 }
20795
20796 /* Write a constant of a given type as target-ordered bytes into
20797    OBSTACK.  */
20798
20799 static const gdb_byte *
20800 write_constant_as_bytes (struct obstack *obstack,
20801                          enum bfd_endian byte_order,
20802                          struct type *type,
20803                          ULONGEST value,
20804                          LONGEST *len)
20805 {
20806   gdb_byte *result;
20807
20808   *len = TYPE_LENGTH (type);
20809   result = (gdb_byte *) obstack_alloc (obstack, *len);
20810   store_unsigned_integer (result, *len, byte_order, value);
20811
20812   return result;
20813 }
20814
20815 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
20816    pointer to the constant bytes and set LEN to the length of the
20817    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
20818    does not have a DW_AT_const_value, return NULL.  */
20819
20820 const gdb_byte *
20821 dwarf2_fetch_constant_bytes (sect_offset sect_off,
20822                              struct dwarf2_per_cu_data *per_cu,
20823                              struct obstack *obstack,
20824                              LONGEST *len)
20825 {
20826   struct dwarf2_cu *cu;
20827   struct die_info *die;
20828   struct attribute *attr;
20829   const gdb_byte *result = NULL;
20830   struct type *type;
20831   LONGEST value;
20832   enum bfd_endian byte_order;
20833
20834   dw2_setup (per_cu->objfile);
20835
20836   if (per_cu->cu == NULL)
20837     load_cu (per_cu);
20838   cu = per_cu->cu;
20839   if (cu == NULL)
20840     {
20841       /* We shouldn't get here for a dummy CU, but don't crash on the user.
20842          Instead just throw an error, not much else we can do.  */
20843       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
20844              to_underlying (sect_off), objfile_name (per_cu->objfile));
20845     }
20846
20847   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20848   if (!die)
20849     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
20850            to_underlying (sect_off), objfile_name (per_cu->objfile));
20851
20852
20853   attr = dwarf2_attr (die, DW_AT_const_value, cu);
20854   if (attr == NULL)
20855     return NULL;
20856
20857   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
20858                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20859
20860   switch (attr->form)
20861     {
20862     case DW_FORM_addr:
20863     case DW_FORM_GNU_addr_index:
20864       {
20865         gdb_byte *tem;
20866
20867         *len = cu->header.addr_size;
20868         tem = (gdb_byte *) obstack_alloc (obstack, *len);
20869         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
20870         result = tem;
20871       }
20872       break;
20873     case DW_FORM_string:
20874     case DW_FORM_strp:
20875     case DW_FORM_GNU_str_index:
20876     case DW_FORM_GNU_strp_alt:
20877       /* DW_STRING is already allocated on the objfile obstack, point
20878          directly to it.  */
20879       result = (const gdb_byte *) DW_STRING (attr);
20880       *len = strlen (DW_STRING (attr));
20881       break;
20882     case DW_FORM_block1:
20883     case DW_FORM_block2:
20884     case DW_FORM_block4:
20885     case DW_FORM_block:
20886     case DW_FORM_exprloc:
20887     case DW_FORM_data16:
20888       result = DW_BLOCK (attr)->data;
20889       *len = DW_BLOCK (attr)->size;
20890       break;
20891
20892       /* The DW_AT_const_value attributes are supposed to carry the
20893          symbol's value "represented as it would be on the target
20894          architecture."  By the time we get here, it's already been
20895          converted to host endianness, so we just need to sign- or
20896          zero-extend it as appropriate.  */
20897     case DW_FORM_data1:
20898       type = die_type (die, cu);
20899       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
20900       if (result == NULL)
20901         result = write_constant_as_bytes (obstack, byte_order,
20902                                           type, value, len);
20903       break;
20904     case DW_FORM_data2:
20905       type = die_type (die, cu);
20906       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
20907       if (result == NULL)
20908         result = write_constant_as_bytes (obstack, byte_order,
20909                                           type, value, len);
20910       break;
20911     case DW_FORM_data4:
20912       type = die_type (die, cu);
20913       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
20914       if (result == NULL)
20915         result = write_constant_as_bytes (obstack, byte_order,
20916                                           type, value, len);
20917       break;
20918     case DW_FORM_data8:
20919       type = die_type (die, cu);
20920       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
20921       if (result == NULL)
20922         result = write_constant_as_bytes (obstack, byte_order,
20923                                           type, value, len);
20924       break;
20925
20926     case DW_FORM_sdata:
20927     case DW_FORM_implicit_const:
20928       type = die_type (die, cu);
20929       result = write_constant_as_bytes (obstack, byte_order,
20930                                         type, DW_SND (attr), len);
20931       break;
20932
20933     case DW_FORM_udata:
20934       type = die_type (die, cu);
20935       result = write_constant_as_bytes (obstack, byte_order,
20936                                         type, DW_UNSND (attr), len);
20937       break;
20938
20939     default:
20940       complaint (&symfile_complaints,
20941                  _("unsupported const value attribute form: '%s'"),
20942                  dwarf_form_name (attr->form));
20943       break;
20944     }
20945
20946   return result;
20947 }
20948
20949 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
20950    valid type for this die is found.  */
20951
20952 struct type *
20953 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
20954                                 struct dwarf2_per_cu_data *per_cu)
20955 {
20956   struct dwarf2_cu *cu;
20957   struct die_info *die;
20958
20959   dw2_setup (per_cu->objfile);
20960
20961   if (per_cu->cu == NULL)
20962     load_cu (per_cu);
20963   cu = per_cu->cu;
20964   if (!cu)
20965     return NULL;
20966
20967   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
20968   if (!die)
20969     return NULL;
20970
20971   return die_type (die, cu);
20972 }
20973
20974 /* Return the type of the DIE at DIE_OFFSET in the CU named by
20975    PER_CU.  */
20976
20977 struct type *
20978 dwarf2_get_die_type (cu_offset die_offset,
20979                      struct dwarf2_per_cu_data *per_cu)
20980 {
20981   dw2_setup (per_cu->objfile);
20982
20983   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
20984   return get_die_type_at_offset (die_offset_sect, per_cu);
20985 }
20986
20987 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
20988    On entry *REF_CU is the CU of SRC_DIE.
20989    On exit *REF_CU is the CU of the result.
20990    Returns NULL if the referenced DIE isn't found.  */
20991
20992 static struct die_info *
20993 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
20994                   struct dwarf2_cu **ref_cu)
20995 {
20996   struct die_info temp_die;
20997   struct dwarf2_cu *sig_cu;
20998   struct die_info *die;
20999
21000   /* While it might be nice to assert sig_type->type == NULL here,
21001      we can get here for DW_AT_imported_declaration where we need
21002      the DIE not the type.  */
21003
21004   /* If necessary, add it to the queue and load its DIEs.  */
21005
21006   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21007     read_signatured_type (sig_type);
21008
21009   sig_cu = sig_type->per_cu.cu;
21010   gdb_assert (sig_cu != NULL);
21011   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21012   temp_die.sect_off = sig_type->type_offset_in_section;
21013   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21014                                                  to_underlying (temp_die.sect_off));
21015   if (die)
21016     {
21017       /* For .gdb_index version 7 keep track of included TUs.
21018          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21019       if (dwarf2_per_objfile->index_table != NULL
21020           && dwarf2_per_objfile->index_table->version <= 7)
21021         {
21022           VEC_safe_push (dwarf2_per_cu_ptr,
21023                          (*ref_cu)->per_cu->imported_symtabs,
21024                          sig_cu->per_cu);
21025         }
21026
21027       *ref_cu = sig_cu;
21028       return die;
21029     }
21030
21031   return NULL;
21032 }
21033
21034 /* Follow signatured type referenced by ATTR in SRC_DIE.
21035    On entry *REF_CU is the CU of SRC_DIE.
21036    On exit *REF_CU is the CU of the result.
21037    The result is the DIE of the type.
21038    If the referenced type cannot be found an error is thrown.  */
21039
21040 static struct die_info *
21041 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21042                 struct dwarf2_cu **ref_cu)
21043 {
21044   ULONGEST signature = DW_SIGNATURE (attr);
21045   struct signatured_type *sig_type;
21046   struct die_info *die;
21047
21048   gdb_assert (attr->form == DW_FORM_ref_sig8);
21049
21050   sig_type = lookup_signatured_type (*ref_cu, signature);
21051   /* sig_type will be NULL if the signatured type is missing from
21052      the debug info.  */
21053   if (sig_type == NULL)
21054     {
21055       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21056                " from DIE at 0x%x [in module %s]"),
21057              hex_string (signature), to_underlying (src_die->sect_off),
21058              objfile_name ((*ref_cu)->objfile));
21059     }
21060
21061   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21062   if (die == NULL)
21063     {
21064       dump_die_for_error (src_die);
21065       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21066                " from DIE at 0x%x [in module %s]"),
21067              hex_string (signature), to_underlying (src_die->sect_off),
21068              objfile_name ((*ref_cu)->objfile));
21069     }
21070
21071   return die;
21072 }
21073
21074 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21075    reading in and processing the type unit if necessary.  */
21076
21077 static struct type *
21078 get_signatured_type (struct die_info *die, ULONGEST signature,
21079                      struct dwarf2_cu *cu)
21080 {
21081   struct signatured_type *sig_type;
21082   struct dwarf2_cu *type_cu;
21083   struct die_info *type_die;
21084   struct type *type;
21085
21086   sig_type = lookup_signatured_type (cu, signature);
21087   /* sig_type will be NULL if the signatured type is missing from
21088      the debug info.  */
21089   if (sig_type == NULL)
21090     {
21091       complaint (&symfile_complaints,
21092                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21093                    " from DIE at 0x%x [in module %s]"),
21094                  hex_string (signature), to_underlying (die->sect_off),
21095                  objfile_name (dwarf2_per_objfile->objfile));
21096       return build_error_marker_type (cu, die);
21097     }
21098
21099   /* If we already know the type we're done.  */
21100   if (sig_type->type != NULL)
21101     return sig_type->type;
21102
21103   type_cu = cu;
21104   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21105   if (type_die != NULL)
21106     {
21107       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21108          is created.  This is important, for example, because for c++ classes
21109          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21110       type = read_type_die (type_die, type_cu);
21111       if (type == NULL)
21112         {
21113           complaint (&symfile_complaints,
21114                      _("Dwarf Error: Cannot build signatured type %s"
21115                        " referenced from DIE at 0x%x [in module %s]"),
21116                      hex_string (signature), to_underlying (die->sect_off),
21117                      objfile_name (dwarf2_per_objfile->objfile));
21118           type = build_error_marker_type (cu, die);
21119         }
21120     }
21121   else
21122     {
21123       complaint (&symfile_complaints,
21124                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21125                    " from DIE at 0x%x [in module %s]"),
21126                  hex_string (signature), to_underlying (die->sect_off),
21127                  objfile_name (dwarf2_per_objfile->objfile));
21128       type = build_error_marker_type (cu, die);
21129     }
21130   sig_type->type = type;
21131
21132   return type;
21133 }
21134
21135 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21136    reading in and processing the type unit if necessary.  */
21137
21138 static struct type *
21139 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21140                           struct dwarf2_cu *cu) /* ARI: editCase function */
21141 {
21142   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21143   if (attr_form_is_ref (attr))
21144     {
21145       struct dwarf2_cu *type_cu = cu;
21146       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21147
21148       return read_type_die (type_die, type_cu);
21149     }
21150   else if (attr->form == DW_FORM_ref_sig8)
21151     {
21152       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21153     }
21154   else
21155     {
21156       complaint (&symfile_complaints,
21157                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21158                    " at 0x%x [in module %s]"),
21159                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21160                  objfile_name (dwarf2_per_objfile->objfile));
21161       return build_error_marker_type (cu, die);
21162     }
21163 }
21164
21165 /* Load the DIEs associated with type unit PER_CU into memory.  */
21166
21167 static void
21168 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21169 {
21170   struct signatured_type *sig_type;
21171
21172   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21173   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21174
21175   /* We have the per_cu, but we need the signatured_type.
21176      Fortunately this is an easy translation.  */
21177   gdb_assert (per_cu->is_debug_types);
21178   sig_type = (struct signatured_type *) per_cu;
21179
21180   gdb_assert (per_cu->cu == NULL);
21181
21182   read_signatured_type (sig_type);
21183
21184   gdb_assert (per_cu->cu != NULL);
21185 }
21186
21187 /* die_reader_func for read_signatured_type.
21188    This is identical to load_full_comp_unit_reader,
21189    but is kept separate for now.  */
21190
21191 static void
21192 read_signatured_type_reader (const struct die_reader_specs *reader,
21193                              const gdb_byte *info_ptr,
21194                              struct die_info *comp_unit_die,
21195                              int has_children,
21196                              void *data)
21197 {
21198   struct dwarf2_cu *cu = reader->cu;
21199
21200   gdb_assert (cu->die_hash == NULL);
21201   cu->die_hash =
21202     htab_create_alloc_ex (cu->header.length / 12,
21203                           die_hash,
21204                           die_eq,
21205                           NULL,
21206                           &cu->comp_unit_obstack,
21207                           hashtab_obstack_allocate,
21208                           dummy_obstack_deallocate);
21209
21210   if (has_children)
21211     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21212                                                   &info_ptr, comp_unit_die);
21213   cu->dies = comp_unit_die;
21214   /* comp_unit_die is not stored in die_hash, no need.  */
21215
21216   /* We try not to read any attributes in this function, because not
21217      all CUs needed for references have been loaded yet, and symbol
21218      table processing isn't initialized.  But we have to set the CU language,
21219      or we won't be able to build types correctly.
21220      Similarly, if we do not read the producer, we can not apply
21221      producer-specific interpretation.  */
21222   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21223 }
21224
21225 /* Read in a signatured type and build its CU and DIEs.
21226    If the type is a stub for the real type in a DWO file,
21227    read in the real type from the DWO file as well.  */
21228
21229 static void
21230 read_signatured_type (struct signatured_type *sig_type)
21231 {
21232   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21233
21234   gdb_assert (per_cu->is_debug_types);
21235   gdb_assert (per_cu->cu == NULL);
21236
21237   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21238                            read_signatured_type_reader, NULL);
21239   sig_type->per_cu.tu_read = 1;
21240 }
21241
21242 /* Decode simple location descriptions.
21243    Given a pointer to a dwarf block that defines a location, compute
21244    the location and return the value.
21245
21246    NOTE drow/2003-11-18: This function is called in two situations
21247    now: for the address of static or global variables (partial symbols
21248    only) and for offsets into structures which are expected to be
21249    (more or less) constant.  The partial symbol case should go away,
21250    and only the constant case should remain.  That will let this
21251    function complain more accurately.  A few special modes are allowed
21252    without complaint for global variables (for instance, global
21253    register values and thread-local values).
21254
21255    A location description containing no operations indicates that the
21256    object is optimized out.  The return value is 0 for that case.
21257    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21258    callers will only want a very basic result and this can become a
21259    complaint.
21260
21261    Note that stack[0] is unused except as a default error return.  */
21262
21263 static CORE_ADDR
21264 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21265 {
21266   struct objfile *objfile = cu->objfile;
21267   size_t i;
21268   size_t size = blk->size;
21269   const gdb_byte *data = blk->data;
21270   CORE_ADDR stack[64];
21271   int stacki;
21272   unsigned int bytes_read, unsnd;
21273   gdb_byte op;
21274
21275   i = 0;
21276   stacki = 0;
21277   stack[stacki] = 0;
21278   stack[++stacki] = 0;
21279
21280   while (i < size)
21281     {
21282       op = data[i++];
21283       switch (op)
21284         {
21285         case DW_OP_lit0:
21286         case DW_OP_lit1:
21287         case DW_OP_lit2:
21288         case DW_OP_lit3:
21289         case DW_OP_lit4:
21290         case DW_OP_lit5:
21291         case DW_OP_lit6:
21292         case DW_OP_lit7:
21293         case DW_OP_lit8:
21294         case DW_OP_lit9:
21295         case DW_OP_lit10:
21296         case DW_OP_lit11:
21297         case DW_OP_lit12:
21298         case DW_OP_lit13:
21299         case DW_OP_lit14:
21300         case DW_OP_lit15:
21301         case DW_OP_lit16:
21302         case DW_OP_lit17:
21303         case DW_OP_lit18:
21304         case DW_OP_lit19:
21305         case DW_OP_lit20:
21306         case DW_OP_lit21:
21307         case DW_OP_lit22:
21308         case DW_OP_lit23:
21309         case DW_OP_lit24:
21310         case DW_OP_lit25:
21311         case DW_OP_lit26:
21312         case DW_OP_lit27:
21313         case DW_OP_lit28:
21314         case DW_OP_lit29:
21315         case DW_OP_lit30:
21316         case DW_OP_lit31:
21317           stack[++stacki] = op - DW_OP_lit0;
21318           break;
21319
21320         case DW_OP_reg0:
21321         case DW_OP_reg1:
21322         case DW_OP_reg2:
21323         case DW_OP_reg3:
21324         case DW_OP_reg4:
21325         case DW_OP_reg5:
21326         case DW_OP_reg6:
21327         case DW_OP_reg7:
21328         case DW_OP_reg8:
21329         case DW_OP_reg9:
21330         case DW_OP_reg10:
21331         case DW_OP_reg11:
21332         case DW_OP_reg12:
21333         case DW_OP_reg13:
21334         case DW_OP_reg14:
21335         case DW_OP_reg15:
21336         case DW_OP_reg16:
21337         case DW_OP_reg17:
21338         case DW_OP_reg18:
21339         case DW_OP_reg19:
21340         case DW_OP_reg20:
21341         case DW_OP_reg21:
21342         case DW_OP_reg22:
21343         case DW_OP_reg23:
21344         case DW_OP_reg24:
21345         case DW_OP_reg25:
21346         case DW_OP_reg26:
21347         case DW_OP_reg27:
21348         case DW_OP_reg28:
21349         case DW_OP_reg29:
21350         case DW_OP_reg30:
21351         case DW_OP_reg31:
21352           stack[++stacki] = op - DW_OP_reg0;
21353           if (i < size)
21354             dwarf2_complex_location_expr_complaint ();
21355           break;
21356
21357         case DW_OP_regx:
21358           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21359           i += bytes_read;
21360           stack[++stacki] = unsnd;
21361           if (i < size)
21362             dwarf2_complex_location_expr_complaint ();
21363           break;
21364
21365         case DW_OP_addr:
21366           stack[++stacki] = read_address (objfile->obfd, &data[i],
21367                                           cu, &bytes_read);
21368           i += bytes_read;
21369           break;
21370
21371         case DW_OP_const1u:
21372           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21373           i += 1;
21374           break;
21375
21376         case DW_OP_const1s:
21377           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21378           i += 1;
21379           break;
21380
21381         case DW_OP_const2u:
21382           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21383           i += 2;
21384           break;
21385
21386         case DW_OP_const2s:
21387           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21388           i += 2;
21389           break;
21390
21391         case DW_OP_const4u:
21392           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21393           i += 4;
21394           break;
21395
21396         case DW_OP_const4s:
21397           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21398           i += 4;
21399           break;
21400
21401         case DW_OP_const8u:
21402           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21403           i += 8;
21404           break;
21405
21406         case DW_OP_constu:
21407           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21408                                                   &bytes_read);
21409           i += bytes_read;
21410           break;
21411
21412         case DW_OP_consts:
21413           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21414           i += bytes_read;
21415           break;
21416
21417         case DW_OP_dup:
21418           stack[stacki + 1] = stack[stacki];
21419           stacki++;
21420           break;
21421
21422         case DW_OP_plus:
21423           stack[stacki - 1] += stack[stacki];
21424           stacki--;
21425           break;
21426
21427         case DW_OP_plus_uconst:
21428           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21429                                                  &bytes_read);
21430           i += bytes_read;
21431           break;
21432
21433         case DW_OP_minus:
21434           stack[stacki - 1] -= stack[stacki];
21435           stacki--;
21436           break;
21437
21438         case DW_OP_deref:
21439           /* If we're not the last op, then we definitely can't encode
21440              this using GDB's address_class enum.  This is valid for partial
21441              global symbols, although the variable's address will be bogus
21442              in the psymtab.  */
21443           if (i < size)
21444             dwarf2_complex_location_expr_complaint ();
21445           break;
21446
21447         case DW_OP_GNU_push_tls_address:
21448         case DW_OP_form_tls_address:
21449           /* The top of the stack has the offset from the beginning
21450              of the thread control block at which the variable is located.  */
21451           /* Nothing should follow this operator, so the top of stack would
21452              be returned.  */
21453           /* This is valid for partial global symbols, but the variable's
21454              address will be bogus in the psymtab.  Make it always at least
21455              non-zero to not look as a variable garbage collected by linker
21456              which have DW_OP_addr 0.  */
21457           if (i < size)
21458             dwarf2_complex_location_expr_complaint ();
21459           stack[stacki]++;
21460           break;
21461
21462         case DW_OP_GNU_uninit:
21463           break;
21464
21465         case DW_OP_GNU_addr_index:
21466         case DW_OP_GNU_const_index:
21467           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21468                                                          &bytes_read);
21469           i += bytes_read;
21470           break;
21471
21472         default:
21473           {
21474             const char *name = get_DW_OP_name (op);
21475
21476             if (name)
21477               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21478                          name);
21479             else
21480               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21481                          op);
21482           }
21483
21484           return (stack[stacki]);
21485         }
21486
21487       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21488          outside of the allocated space.  Also enforce minimum>0.  */
21489       if (stacki >= ARRAY_SIZE (stack) - 1)
21490         {
21491           complaint (&symfile_complaints,
21492                      _("location description stack overflow"));
21493           return 0;
21494         }
21495
21496       if (stacki <= 0)
21497         {
21498           complaint (&symfile_complaints,
21499                      _("location description stack underflow"));
21500           return 0;
21501         }
21502     }
21503   return (stack[stacki]);
21504 }
21505
21506 /* memory allocation interface */
21507
21508 static struct dwarf_block *
21509 dwarf_alloc_block (struct dwarf2_cu *cu)
21510 {
21511   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21512 }
21513
21514 static struct die_info *
21515 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21516 {
21517   struct die_info *die;
21518   size_t size = sizeof (struct die_info);
21519
21520   if (num_attrs > 1)
21521     size += (num_attrs - 1) * sizeof (struct attribute);
21522
21523   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21524   memset (die, 0, sizeof (struct die_info));
21525   return (die);
21526 }
21527
21528 \f
21529 /* Macro support.  */
21530
21531 /* Return file name relative to the compilation directory of file number I in
21532    *LH's file name table.  The result is allocated using xmalloc; the caller is
21533    responsible for freeing it.  */
21534
21535 static char *
21536 file_file_name (int file, struct line_header *lh)
21537 {
21538   /* Is the file number a valid index into the line header's file name
21539      table?  Remember that file numbers start with one, not zero.  */
21540   if (1 <= file && file <= lh->file_names.size ())
21541     {
21542       const file_entry &fe = lh->file_names[file - 1];
21543
21544       if (!IS_ABSOLUTE_PATH (fe.name))
21545         {
21546           const char *dir = fe.include_dir (lh);
21547           if (dir != NULL)
21548             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21549         }
21550       return xstrdup (fe.name);
21551     }
21552   else
21553     {
21554       /* The compiler produced a bogus file number.  We can at least
21555          record the macro definitions made in the file, even if we
21556          won't be able to find the file by name.  */
21557       char fake_name[80];
21558
21559       xsnprintf (fake_name, sizeof (fake_name),
21560                  "<bad macro file number %d>", file);
21561
21562       complaint (&symfile_complaints,
21563                  _("bad file number in macro information (%d)"),
21564                  file);
21565
21566       return xstrdup (fake_name);
21567     }
21568 }
21569
21570 /* Return the full name of file number I in *LH's file name table.
21571    Use COMP_DIR as the name of the current directory of the
21572    compilation.  The result is allocated using xmalloc; the caller is
21573    responsible for freeing it.  */
21574 static char *
21575 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21576 {
21577   /* Is the file number a valid index into the line header's file name
21578      table?  Remember that file numbers start with one, not zero.  */
21579   if (1 <= file && file <= lh->file_names.size ())
21580     {
21581       char *relative = file_file_name (file, lh);
21582
21583       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21584         return relative;
21585       return reconcat (relative, comp_dir, SLASH_STRING,
21586                        relative, (char *) NULL);
21587     }
21588   else
21589     return file_file_name (file, lh);
21590 }
21591
21592
21593 static struct macro_source_file *
21594 macro_start_file (int file, int line,
21595                   struct macro_source_file *current_file,
21596                   struct line_header *lh)
21597 {
21598   /* File name relative to the compilation directory of this source file.  */
21599   char *file_name = file_file_name (file, lh);
21600
21601   if (! current_file)
21602     {
21603       /* Note: We don't create a macro table for this compilation unit
21604          at all until we actually get a filename.  */
21605       struct macro_table *macro_table = get_macro_table ();
21606
21607       /* If we have no current file, then this must be the start_file
21608          directive for the compilation unit's main source file.  */
21609       current_file = macro_set_main (macro_table, file_name);
21610       macro_define_special (macro_table);
21611     }
21612   else
21613     current_file = macro_include (current_file, line, file_name);
21614
21615   xfree (file_name);
21616
21617   return current_file;
21618 }
21619
21620 static const char *
21621 consume_improper_spaces (const char *p, const char *body)
21622 {
21623   if (*p == ' ')
21624     {
21625       complaint (&symfile_complaints,
21626                  _("macro definition contains spaces "
21627                    "in formal argument list:\n`%s'"),
21628                  body);
21629
21630       while (*p == ' ')
21631         p++;
21632     }
21633
21634   return p;
21635 }
21636
21637
21638 static void
21639 parse_macro_definition (struct macro_source_file *file, int line,
21640                         const char *body)
21641 {
21642   const char *p;
21643
21644   /* The body string takes one of two forms.  For object-like macro
21645      definitions, it should be:
21646
21647         <macro name> " " <definition>
21648
21649      For function-like macro definitions, it should be:
21650
21651         <macro name> "() " <definition>
21652      or
21653         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21654
21655      Spaces may appear only where explicitly indicated, and in the
21656      <definition>.
21657
21658      The Dwarf 2 spec says that an object-like macro's name is always
21659      followed by a space, but versions of GCC around March 2002 omit
21660      the space when the macro's definition is the empty string.
21661
21662      The Dwarf 2 spec says that there should be no spaces between the
21663      formal arguments in a function-like macro's formal argument list,
21664      but versions of GCC around March 2002 include spaces after the
21665      commas.  */
21666
21667
21668   /* Find the extent of the macro name.  The macro name is terminated
21669      by either a space or null character (for an object-like macro) or
21670      an opening paren (for a function-like macro).  */
21671   for (p = body; *p; p++)
21672     if (*p == ' ' || *p == '(')
21673       break;
21674
21675   if (*p == ' ' || *p == '\0')
21676     {
21677       /* It's an object-like macro.  */
21678       int name_len = p - body;
21679       char *name = savestring (body, name_len);
21680       const char *replacement;
21681
21682       if (*p == ' ')
21683         replacement = body + name_len + 1;
21684       else
21685         {
21686           dwarf2_macro_malformed_definition_complaint (body);
21687           replacement = body + name_len;
21688         }
21689
21690       macro_define_object (file, line, name, replacement);
21691
21692       xfree (name);
21693     }
21694   else if (*p == '(')
21695     {
21696       /* It's a function-like macro.  */
21697       char *name = savestring (body, p - body);
21698       int argc = 0;
21699       int argv_size = 1;
21700       char **argv = XNEWVEC (char *, argv_size);
21701
21702       p++;
21703
21704       p = consume_improper_spaces (p, body);
21705
21706       /* Parse the formal argument list.  */
21707       while (*p && *p != ')')
21708         {
21709           /* Find the extent of the current argument name.  */
21710           const char *arg_start = p;
21711
21712           while (*p && *p != ',' && *p != ')' && *p != ' ')
21713             p++;
21714
21715           if (! *p || p == arg_start)
21716             dwarf2_macro_malformed_definition_complaint (body);
21717           else
21718             {
21719               /* Make sure argv has room for the new argument.  */
21720               if (argc >= argv_size)
21721                 {
21722                   argv_size *= 2;
21723                   argv = XRESIZEVEC (char *, argv, argv_size);
21724                 }
21725
21726               argv[argc++] = savestring (arg_start, p - arg_start);
21727             }
21728
21729           p = consume_improper_spaces (p, body);
21730
21731           /* Consume the comma, if present.  */
21732           if (*p == ',')
21733             {
21734               p++;
21735
21736               p = consume_improper_spaces (p, body);
21737             }
21738         }
21739
21740       if (*p == ')')
21741         {
21742           p++;
21743
21744           if (*p == ' ')
21745             /* Perfectly formed definition, no complaints.  */
21746             macro_define_function (file, line, name,
21747                                    argc, (const char **) argv,
21748                                    p + 1);
21749           else if (*p == '\0')
21750             {
21751               /* Complain, but do define it.  */
21752               dwarf2_macro_malformed_definition_complaint (body);
21753               macro_define_function (file, line, name,
21754                                      argc, (const char **) argv,
21755                                      p);
21756             }
21757           else
21758             /* Just complain.  */
21759             dwarf2_macro_malformed_definition_complaint (body);
21760         }
21761       else
21762         /* Just complain.  */
21763         dwarf2_macro_malformed_definition_complaint (body);
21764
21765       xfree (name);
21766       {
21767         int i;
21768
21769         for (i = 0; i < argc; i++)
21770           xfree (argv[i]);
21771       }
21772       xfree (argv);
21773     }
21774   else
21775     dwarf2_macro_malformed_definition_complaint (body);
21776 }
21777
21778 /* Skip some bytes from BYTES according to the form given in FORM.
21779    Returns the new pointer.  */
21780
21781 static const gdb_byte *
21782 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
21783                  enum dwarf_form form,
21784                  unsigned int offset_size,
21785                  struct dwarf2_section_info *section)
21786 {
21787   unsigned int bytes_read;
21788
21789   switch (form)
21790     {
21791     case DW_FORM_data1:
21792     case DW_FORM_flag:
21793       ++bytes;
21794       break;
21795
21796     case DW_FORM_data2:
21797       bytes += 2;
21798       break;
21799
21800     case DW_FORM_data4:
21801       bytes += 4;
21802       break;
21803
21804     case DW_FORM_data8:
21805       bytes += 8;
21806       break;
21807
21808     case DW_FORM_data16:
21809       bytes += 16;
21810       break;
21811
21812     case DW_FORM_string:
21813       read_direct_string (abfd, bytes, &bytes_read);
21814       bytes += bytes_read;
21815       break;
21816
21817     case DW_FORM_sec_offset:
21818     case DW_FORM_strp:
21819     case DW_FORM_GNU_strp_alt:
21820       bytes += offset_size;
21821       break;
21822
21823     case DW_FORM_block:
21824       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
21825       bytes += bytes_read;
21826       break;
21827
21828     case DW_FORM_block1:
21829       bytes += 1 + read_1_byte (abfd, bytes);
21830       break;
21831     case DW_FORM_block2:
21832       bytes += 2 + read_2_bytes (abfd, bytes);
21833       break;
21834     case DW_FORM_block4:
21835       bytes += 4 + read_4_bytes (abfd, bytes);
21836       break;
21837
21838     case DW_FORM_sdata:
21839     case DW_FORM_udata:
21840     case DW_FORM_GNU_addr_index:
21841     case DW_FORM_GNU_str_index:
21842       bytes = gdb_skip_leb128 (bytes, buffer_end);
21843       if (bytes == NULL)
21844         {
21845           dwarf2_section_buffer_overflow_complaint (section);
21846           return NULL;
21847         }
21848       break;
21849
21850     case DW_FORM_implicit_const:
21851       break;
21852
21853     default:
21854       {
21855       complain:
21856         complaint (&symfile_complaints,
21857                    _("invalid form 0x%x in `%s'"),
21858                    form, get_section_name (section));
21859         return NULL;
21860       }
21861     }
21862
21863   return bytes;
21864 }
21865
21866 /* A helper for dwarf_decode_macros that handles skipping an unknown
21867    opcode.  Returns an updated pointer to the macro data buffer; or,
21868    on error, issues a complaint and returns NULL.  */
21869
21870 static const gdb_byte *
21871 skip_unknown_opcode (unsigned int opcode,
21872                      const gdb_byte **opcode_definitions,
21873                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21874                      bfd *abfd,
21875                      unsigned int offset_size,
21876                      struct dwarf2_section_info *section)
21877 {
21878   unsigned int bytes_read, i;
21879   unsigned long arg;
21880   const gdb_byte *defn;
21881
21882   if (opcode_definitions[opcode] == NULL)
21883     {
21884       complaint (&symfile_complaints,
21885                  _("unrecognized DW_MACFINO opcode 0x%x"),
21886                  opcode);
21887       return NULL;
21888     }
21889
21890   defn = opcode_definitions[opcode];
21891   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
21892   defn += bytes_read;
21893
21894   for (i = 0; i < arg; ++i)
21895     {
21896       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
21897                                  (enum dwarf_form) defn[i], offset_size,
21898                                  section);
21899       if (mac_ptr == NULL)
21900         {
21901           /* skip_form_bytes already issued the complaint.  */
21902           return NULL;
21903         }
21904     }
21905
21906   return mac_ptr;
21907 }
21908
21909 /* A helper function which parses the header of a macro section.
21910    If the macro section is the extended (for now called "GNU") type,
21911    then this updates *OFFSET_SIZE.  Returns a pointer to just after
21912    the header, or issues a complaint and returns NULL on error.  */
21913
21914 static const gdb_byte *
21915 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
21916                           bfd *abfd,
21917                           const gdb_byte *mac_ptr,
21918                           unsigned int *offset_size,
21919                           int section_is_gnu)
21920 {
21921   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
21922
21923   if (section_is_gnu)
21924     {
21925       unsigned int version, flags;
21926
21927       version = read_2_bytes (abfd, mac_ptr);
21928       if (version != 4 && version != 5)
21929         {
21930           complaint (&symfile_complaints,
21931                      _("unrecognized version `%d' in .debug_macro section"),
21932                      version);
21933           return NULL;
21934         }
21935       mac_ptr += 2;
21936
21937       flags = read_1_byte (abfd, mac_ptr);
21938       ++mac_ptr;
21939       *offset_size = (flags & 1) ? 8 : 4;
21940
21941       if ((flags & 2) != 0)
21942         /* We don't need the line table offset.  */
21943         mac_ptr += *offset_size;
21944
21945       /* Vendor opcode descriptions.  */
21946       if ((flags & 4) != 0)
21947         {
21948           unsigned int i, count;
21949
21950           count = read_1_byte (abfd, mac_ptr);
21951           ++mac_ptr;
21952           for (i = 0; i < count; ++i)
21953             {
21954               unsigned int opcode, bytes_read;
21955               unsigned long arg;
21956
21957               opcode = read_1_byte (abfd, mac_ptr);
21958               ++mac_ptr;
21959               opcode_definitions[opcode] = mac_ptr;
21960               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
21961               mac_ptr += bytes_read;
21962               mac_ptr += arg;
21963             }
21964         }
21965     }
21966
21967   return mac_ptr;
21968 }
21969
21970 /* A helper for dwarf_decode_macros that handles the GNU extensions,
21971    including DW_MACRO_import.  */
21972
21973 static void
21974 dwarf_decode_macro_bytes (bfd *abfd,
21975                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
21976                           struct macro_source_file *current_file,
21977                           struct line_header *lh,
21978                           struct dwarf2_section_info *section,
21979                           int section_is_gnu, int section_is_dwz,
21980                           unsigned int offset_size,
21981                           htab_t include_hash)
21982 {
21983   struct objfile *objfile = dwarf2_per_objfile->objfile;
21984   enum dwarf_macro_record_type macinfo_type;
21985   int at_commandline;
21986   const gdb_byte *opcode_definitions[256];
21987
21988   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
21989                                       &offset_size, section_is_gnu);
21990   if (mac_ptr == NULL)
21991     {
21992       /* We already issued a complaint.  */
21993       return;
21994     }
21995
21996   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
21997      GDB is still reading the definitions from command line.  First
21998      DW_MACINFO_start_file will need to be ignored as it was already executed
21999      to create CURRENT_FILE for the main source holding also the command line
22000      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22001      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22002
22003   at_commandline = 1;
22004
22005   do
22006     {
22007       /* Do we at least have room for a macinfo type byte?  */
22008       if (mac_ptr >= mac_end)
22009         {
22010           dwarf2_section_buffer_overflow_complaint (section);
22011           break;
22012         }
22013
22014       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22015       mac_ptr++;
22016
22017       /* Note that we rely on the fact that the corresponding GNU and
22018          DWARF constants are the same.  */
22019       switch (macinfo_type)
22020         {
22021           /* A zero macinfo type indicates the end of the macro
22022              information.  */
22023         case 0:
22024           break;
22025
22026         case DW_MACRO_define:
22027         case DW_MACRO_undef:
22028         case DW_MACRO_define_strp:
22029         case DW_MACRO_undef_strp:
22030         case DW_MACRO_define_sup:
22031         case DW_MACRO_undef_sup:
22032           {
22033             unsigned int bytes_read;
22034             int line;
22035             const char *body;
22036             int is_define;
22037
22038             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22039             mac_ptr += bytes_read;
22040
22041             if (macinfo_type == DW_MACRO_define
22042                 || macinfo_type == DW_MACRO_undef)
22043               {
22044                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22045                 mac_ptr += bytes_read;
22046               }
22047             else
22048               {
22049                 LONGEST str_offset;
22050
22051                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22052                 mac_ptr += offset_size;
22053
22054                 if (macinfo_type == DW_MACRO_define_sup
22055                     || macinfo_type == DW_MACRO_undef_sup
22056                     || section_is_dwz)
22057                   {
22058                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22059
22060                     body = read_indirect_string_from_dwz (dwz, str_offset);
22061                   }
22062                 else
22063                   body = read_indirect_string_at_offset (abfd, str_offset);
22064               }
22065
22066             is_define = (macinfo_type == DW_MACRO_define
22067                          || macinfo_type == DW_MACRO_define_strp
22068                          || macinfo_type == DW_MACRO_define_sup);
22069             if (! current_file)
22070               {
22071                 /* DWARF violation as no main source is present.  */
22072                 complaint (&symfile_complaints,
22073                            _("debug info with no main source gives macro %s "
22074                              "on line %d: %s"),
22075                            is_define ? _("definition") : _("undefinition"),
22076                            line, body);
22077                 break;
22078               }
22079             if ((line == 0 && !at_commandline)
22080                 || (line != 0 && at_commandline))
22081               complaint (&symfile_complaints,
22082                          _("debug info gives %s macro %s with %s line %d: %s"),
22083                          at_commandline ? _("command-line") : _("in-file"),
22084                          is_define ? _("definition") : _("undefinition"),
22085                          line == 0 ? _("zero") : _("non-zero"), line, body);
22086
22087             if (is_define)
22088               parse_macro_definition (current_file, line, body);
22089             else
22090               {
22091                 gdb_assert (macinfo_type == DW_MACRO_undef
22092                             || macinfo_type == DW_MACRO_undef_strp
22093                             || macinfo_type == DW_MACRO_undef_sup);
22094                 macro_undef (current_file, line, body);
22095               }
22096           }
22097           break;
22098
22099         case DW_MACRO_start_file:
22100           {
22101             unsigned int bytes_read;
22102             int line, file;
22103
22104             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22105             mac_ptr += bytes_read;
22106             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22107             mac_ptr += bytes_read;
22108
22109             if ((line == 0 && !at_commandline)
22110                 || (line != 0 && at_commandline))
22111               complaint (&symfile_complaints,
22112                          _("debug info gives source %d included "
22113                            "from %s at %s line %d"),
22114                          file, at_commandline ? _("command-line") : _("file"),
22115                          line == 0 ? _("zero") : _("non-zero"), line);
22116
22117             if (at_commandline)
22118               {
22119                 /* This DW_MACRO_start_file was executed in the
22120                    pass one.  */
22121                 at_commandline = 0;
22122               }
22123             else
22124               current_file = macro_start_file (file, line, current_file, lh);
22125           }
22126           break;
22127
22128         case DW_MACRO_end_file:
22129           if (! current_file)
22130             complaint (&symfile_complaints,
22131                        _("macro debug info has an unmatched "
22132                          "`close_file' directive"));
22133           else
22134             {
22135               current_file = current_file->included_by;
22136               if (! current_file)
22137                 {
22138                   enum dwarf_macro_record_type next_type;
22139
22140                   /* GCC circa March 2002 doesn't produce the zero
22141                      type byte marking the end of the compilation
22142                      unit.  Complain if it's not there, but exit no
22143                      matter what.  */
22144
22145                   /* Do we at least have room for a macinfo type byte?  */
22146                   if (mac_ptr >= mac_end)
22147                     {
22148                       dwarf2_section_buffer_overflow_complaint (section);
22149                       return;
22150                     }
22151
22152                   /* We don't increment mac_ptr here, so this is just
22153                      a look-ahead.  */
22154                   next_type
22155                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22156                                                                   mac_ptr);
22157                   if (next_type != 0)
22158                     complaint (&symfile_complaints,
22159                                _("no terminating 0-type entry for "
22160                                  "macros in `.debug_macinfo' section"));
22161
22162                   return;
22163                 }
22164             }
22165           break;
22166
22167         case DW_MACRO_import:
22168         case DW_MACRO_import_sup:
22169           {
22170             LONGEST offset;
22171             void **slot;
22172             bfd *include_bfd = abfd;
22173             struct dwarf2_section_info *include_section = section;
22174             const gdb_byte *include_mac_end = mac_end;
22175             int is_dwz = section_is_dwz;
22176             const gdb_byte *new_mac_ptr;
22177
22178             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22179             mac_ptr += offset_size;
22180
22181             if (macinfo_type == DW_MACRO_import_sup)
22182               {
22183                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22184
22185                 dwarf2_read_section (objfile, &dwz->macro);
22186
22187                 include_section = &dwz->macro;
22188                 include_bfd = get_section_bfd_owner (include_section);
22189                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22190                 is_dwz = 1;
22191               }
22192
22193             new_mac_ptr = include_section->buffer + offset;
22194             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22195
22196             if (*slot != NULL)
22197               {
22198                 /* This has actually happened; see
22199                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22200                 complaint (&symfile_complaints,
22201                            _("recursive DW_MACRO_import in "
22202                              ".debug_macro section"));
22203               }
22204             else
22205               {
22206                 *slot = (void *) new_mac_ptr;
22207
22208                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22209                                           include_mac_end, current_file, lh,
22210                                           section, section_is_gnu, is_dwz,
22211                                           offset_size, include_hash);
22212
22213                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22214               }
22215           }
22216           break;
22217
22218         case DW_MACINFO_vendor_ext:
22219           if (!section_is_gnu)
22220             {
22221               unsigned int bytes_read;
22222
22223               /* This reads the constant, but since we don't recognize
22224                  any vendor extensions, we ignore it.  */
22225               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22226               mac_ptr += bytes_read;
22227               read_direct_string (abfd, mac_ptr, &bytes_read);
22228               mac_ptr += bytes_read;
22229
22230               /* We don't recognize any vendor extensions.  */
22231               break;
22232             }
22233           /* FALLTHROUGH */
22234
22235         default:
22236           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22237                                          mac_ptr, mac_end, abfd, offset_size,
22238                                          section);
22239           if (mac_ptr == NULL)
22240             return;
22241           break;
22242         }
22243     } while (macinfo_type != 0);
22244 }
22245
22246 static void
22247 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22248                      int section_is_gnu)
22249 {
22250   struct objfile *objfile = dwarf2_per_objfile->objfile;
22251   struct line_header *lh = cu->line_header;
22252   bfd *abfd;
22253   const gdb_byte *mac_ptr, *mac_end;
22254   struct macro_source_file *current_file = 0;
22255   enum dwarf_macro_record_type macinfo_type;
22256   unsigned int offset_size = cu->header.offset_size;
22257   const gdb_byte *opcode_definitions[256];
22258   void **slot;
22259   struct dwarf2_section_info *section;
22260   const char *section_name;
22261
22262   if (cu->dwo_unit != NULL)
22263     {
22264       if (section_is_gnu)
22265         {
22266           section = &cu->dwo_unit->dwo_file->sections.macro;
22267           section_name = ".debug_macro.dwo";
22268         }
22269       else
22270         {
22271           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22272           section_name = ".debug_macinfo.dwo";
22273         }
22274     }
22275   else
22276     {
22277       if (section_is_gnu)
22278         {
22279           section = &dwarf2_per_objfile->macro;
22280           section_name = ".debug_macro";
22281         }
22282       else
22283         {
22284           section = &dwarf2_per_objfile->macinfo;
22285           section_name = ".debug_macinfo";
22286         }
22287     }
22288
22289   dwarf2_read_section (objfile, section);
22290   if (section->buffer == NULL)
22291     {
22292       complaint (&symfile_complaints, _("missing %s section"), section_name);
22293       return;
22294     }
22295   abfd = get_section_bfd_owner (section);
22296
22297   /* First pass: Find the name of the base filename.
22298      This filename is needed in order to process all macros whose definition
22299      (or undefinition) comes from the command line.  These macros are defined
22300      before the first DW_MACINFO_start_file entry, and yet still need to be
22301      associated to the base file.
22302
22303      To determine the base file name, we scan the macro definitions until we
22304      reach the first DW_MACINFO_start_file entry.  We then initialize
22305      CURRENT_FILE accordingly so that any macro definition found before the
22306      first DW_MACINFO_start_file can still be associated to the base file.  */
22307
22308   mac_ptr = section->buffer + offset;
22309   mac_end = section->buffer + section->size;
22310
22311   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22312                                       &offset_size, section_is_gnu);
22313   if (mac_ptr == NULL)
22314     {
22315       /* We already issued a complaint.  */
22316       return;
22317     }
22318
22319   do
22320     {
22321       /* Do we at least have room for a macinfo type byte?  */
22322       if (mac_ptr >= mac_end)
22323         {
22324           /* Complaint is printed during the second pass as GDB will probably
22325              stop the first pass earlier upon finding
22326              DW_MACINFO_start_file.  */
22327           break;
22328         }
22329
22330       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22331       mac_ptr++;
22332
22333       /* Note that we rely on the fact that the corresponding GNU and
22334          DWARF constants are the same.  */
22335       switch (macinfo_type)
22336         {
22337           /* A zero macinfo type indicates the end of the macro
22338              information.  */
22339         case 0:
22340           break;
22341
22342         case DW_MACRO_define:
22343         case DW_MACRO_undef:
22344           /* Only skip the data by MAC_PTR.  */
22345           {
22346             unsigned int bytes_read;
22347
22348             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22349             mac_ptr += bytes_read;
22350             read_direct_string (abfd, mac_ptr, &bytes_read);
22351             mac_ptr += bytes_read;
22352           }
22353           break;
22354
22355         case DW_MACRO_start_file:
22356           {
22357             unsigned int bytes_read;
22358             int line, file;
22359
22360             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22361             mac_ptr += bytes_read;
22362             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22363             mac_ptr += bytes_read;
22364
22365             current_file = macro_start_file (file, line, current_file, lh);
22366           }
22367           break;
22368
22369         case DW_MACRO_end_file:
22370           /* No data to skip by MAC_PTR.  */
22371           break;
22372
22373         case DW_MACRO_define_strp:
22374         case DW_MACRO_undef_strp:
22375         case DW_MACRO_define_sup:
22376         case DW_MACRO_undef_sup:
22377           {
22378             unsigned int bytes_read;
22379
22380             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22381             mac_ptr += bytes_read;
22382             mac_ptr += offset_size;
22383           }
22384           break;
22385
22386         case DW_MACRO_import:
22387         case DW_MACRO_import_sup:
22388           /* Note that, according to the spec, a transparent include
22389              chain cannot call DW_MACRO_start_file.  So, we can just
22390              skip this opcode.  */
22391           mac_ptr += offset_size;
22392           break;
22393
22394         case DW_MACINFO_vendor_ext:
22395           /* Only skip the data by MAC_PTR.  */
22396           if (!section_is_gnu)
22397             {
22398               unsigned int bytes_read;
22399
22400               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22401               mac_ptr += bytes_read;
22402               read_direct_string (abfd, mac_ptr, &bytes_read);
22403               mac_ptr += bytes_read;
22404             }
22405           /* FALLTHROUGH */
22406
22407         default:
22408           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22409                                          mac_ptr, mac_end, abfd, offset_size,
22410                                          section);
22411           if (mac_ptr == NULL)
22412             return;
22413           break;
22414         }
22415     } while (macinfo_type != 0 && current_file == NULL);
22416
22417   /* Second pass: Process all entries.
22418
22419      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22420      command-line macro definitions/undefinitions.  This flag is unset when we
22421      reach the first DW_MACINFO_start_file entry.  */
22422
22423   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22424                                            htab_eq_pointer,
22425                                            NULL, xcalloc, xfree));
22426   mac_ptr = section->buffer + offset;
22427   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22428   *slot = (void *) mac_ptr;
22429   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22430                             current_file, lh, section,
22431                             section_is_gnu, 0, offset_size,
22432                             include_hash.get ());
22433 }
22434
22435 /* Check if the attribute's form is a DW_FORM_block*
22436    if so return true else false.  */
22437
22438 static int
22439 attr_form_is_block (const struct attribute *attr)
22440 {
22441   return (attr == NULL ? 0 :
22442       attr->form == DW_FORM_block1
22443       || attr->form == DW_FORM_block2
22444       || attr->form == DW_FORM_block4
22445       || attr->form == DW_FORM_block
22446       || attr->form == DW_FORM_exprloc);
22447 }
22448
22449 /* Return non-zero if ATTR's value is a section offset --- classes
22450    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22451    You may use DW_UNSND (attr) to retrieve such offsets.
22452
22453    Section 7.5.4, "Attribute Encodings", explains that no attribute
22454    may have a value that belongs to more than one of these classes; it
22455    would be ambiguous if we did, because we use the same forms for all
22456    of them.  */
22457
22458 static int
22459 attr_form_is_section_offset (const struct attribute *attr)
22460 {
22461   return (attr->form == DW_FORM_data4
22462           || attr->form == DW_FORM_data8
22463           || attr->form == DW_FORM_sec_offset);
22464 }
22465
22466 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22467    zero otherwise.  When this function returns true, you can apply
22468    dwarf2_get_attr_constant_value to it.
22469
22470    However, note that for some attributes you must check
22471    attr_form_is_section_offset before using this test.  DW_FORM_data4
22472    and DW_FORM_data8 are members of both the constant class, and of
22473    the classes that contain offsets into other debug sections
22474    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22475    that, if an attribute's can be either a constant or one of the
22476    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22477    taken as section offsets, not constants.
22478
22479    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22480    cannot handle that.  */
22481
22482 static int
22483 attr_form_is_constant (const struct attribute *attr)
22484 {
22485   switch (attr->form)
22486     {
22487     case DW_FORM_sdata:
22488     case DW_FORM_udata:
22489     case DW_FORM_data1:
22490     case DW_FORM_data2:
22491     case DW_FORM_data4:
22492     case DW_FORM_data8:
22493     case DW_FORM_implicit_const:
22494       return 1;
22495     default:
22496       return 0;
22497     }
22498 }
22499
22500
22501 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22502    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22503
22504 static int
22505 attr_form_is_ref (const struct attribute *attr)
22506 {
22507   switch (attr->form)
22508     {
22509     case DW_FORM_ref_addr:
22510     case DW_FORM_ref1:
22511     case DW_FORM_ref2:
22512     case DW_FORM_ref4:
22513     case DW_FORM_ref8:
22514     case DW_FORM_ref_udata:
22515     case DW_FORM_GNU_ref_alt:
22516       return 1;
22517     default:
22518       return 0;
22519     }
22520 }
22521
22522 /* Return the .debug_loc section to use for CU.
22523    For DWO files use .debug_loc.dwo.  */
22524
22525 static struct dwarf2_section_info *
22526 cu_debug_loc_section (struct dwarf2_cu *cu)
22527 {
22528   if (cu->dwo_unit)
22529     {
22530       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22531       
22532       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22533     }
22534   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22535                                   : &dwarf2_per_objfile->loc);
22536 }
22537
22538 /* A helper function that fills in a dwarf2_loclist_baton.  */
22539
22540 static void
22541 fill_in_loclist_baton (struct dwarf2_cu *cu,
22542                        struct dwarf2_loclist_baton *baton,
22543                        const struct attribute *attr)
22544 {
22545   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22546
22547   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22548
22549   baton->per_cu = cu->per_cu;
22550   gdb_assert (baton->per_cu);
22551   /* We don't know how long the location list is, but make sure we
22552      don't run off the edge of the section.  */
22553   baton->size = section->size - DW_UNSND (attr);
22554   baton->data = section->buffer + DW_UNSND (attr);
22555   baton->base_address = cu->base_address;
22556   baton->from_dwo = cu->dwo_unit != NULL;
22557 }
22558
22559 static void
22560 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22561                              struct dwarf2_cu *cu, int is_block)
22562 {
22563   struct objfile *objfile = dwarf2_per_objfile->objfile;
22564   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22565
22566   if (attr_form_is_section_offset (attr)
22567       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22568          the section.  If so, fall through to the complaint in the
22569          other branch.  */
22570       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22571     {
22572       struct dwarf2_loclist_baton *baton;
22573
22574       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22575
22576       fill_in_loclist_baton (cu, baton, attr);
22577
22578       if (cu->base_known == 0)
22579         complaint (&symfile_complaints,
22580                    _("Location list used without "
22581                      "specifying the CU base address."));
22582
22583       SYMBOL_ACLASS_INDEX (sym) = (is_block
22584                                    ? dwarf2_loclist_block_index
22585                                    : dwarf2_loclist_index);
22586       SYMBOL_LOCATION_BATON (sym) = baton;
22587     }
22588   else
22589     {
22590       struct dwarf2_locexpr_baton *baton;
22591
22592       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22593       baton->per_cu = cu->per_cu;
22594       gdb_assert (baton->per_cu);
22595
22596       if (attr_form_is_block (attr))
22597         {
22598           /* Note that we're just copying the block's data pointer
22599              here, not the actual data.  We're still pointing into the
22600              info_buffer for SYM's objfile; right now we never release
22601              that buffer, but when we do clean up properly this may
22602              need to change.  */
22603           baton->size = DW_BLOCK (attr)->size;
22604           baton->data = DW_BLOCK (attr)->data;
22605         }
22606       else
22607         {
22608           dwarf2_invalid_attrib_class_complaint ("location description",
22609                                                  SYMBOL_NATURAL_NAME (sym));
22610           baton->size = 0;
22611         }
22612
22613       SYMBOL_ACLASS_INDEX (sym) = (is_block
22614                                    ? dwarf2_locexpr_block_index
22615                                    : dwarf2_locexpr_index);
22616       SYMBOL_LOCATION_BATON (sym) = baton;
22617     }
22618 }
22619
22620 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22621    came from a separate debuginfo file, then the master objfile is
22622    returned.  */
22623
22624 struct objfile *
22625 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22626 {
22627   struct objfile *objfile = per_cu->objfile;
22628
22629   /* Return the master objfile, so that we can report and look up the
22630      correct file containing this variable.  */
22631   if (objfile->separate_debug_objfile_backlink)
22632     objfile = objfile->separate_debug_objfile_backlink;
22633
22634   return objfile;
22635 }
22636
22637 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22638    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22639    CU_HEADERP first.  */
22640
22641 static const struct comp_unit_head *
22642 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22643                        struct dwarf2_per_cu_data *per_cu)
22644 {
22645   const gdb_byte *info_ptr;
22646
22647   if (per_cu->cu)
22648     return &per_cu->cu->header;
22649
22650   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22651
22652   memset (cu_headerp, 0, sizeof (*cu_headerp));
22653   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22654                        rcuh_kind::COMPILE);
22655
22656   return cu_headerp;
22657 }
22658
22659 /* Return the address size given in the compilation unit header for CU.  */
22660
22661 int
22662 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22663 {
22664   struct comp_unit_head cu_header_local;
22665   const struct comp_unit_head *cu_headerp;
22666
22667   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22668
22669   return cu_headerp->addr_size;
22670 }
22671
22672 /* Return the offset size given in the compilation unit header for CU.  */
22673
22674 int
22675 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
22676 {
22677   struct comp_unit_head cu_header_local;
22678   const struct comp_unit_head *cu_headerp;
22679
22680   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22681
22682   return cu_headerp->offset_size;
22683 }
22684
22685 /* See its dwarf2loc.h declaration.  */
22686
22687 int
22688 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
22689 {
22690   struct comp_unit_head cu_header_local;
22691   const struct comp_unit_head *cu_headerp;
22692
22693   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22694
22695   if (cu_headerp->version == 2)
22696     return cu_headerp->addr_size;
22697   else
22698     return cu_headerp->offset_size;
22699 }
22700
22701 /* Return the text offset of the CU.  The returned offset comes from
22702    this CU's objfile.  If this objfile came from a separate debuginfo
22703    file, then the offset may be different from the corresponding
22704    offset in the parent objfile.  */
22705
22706 CORE_ADDR
22707 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
22708 {
22709   struct objfile *objfile = per_cu->objfile;
22710
22711   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
22712 }
22713
22714 /* Return DWARF version number of PER_CU.  */
22715
22716 short
22717 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
22718 {
22719   return per_cu->dwarf_version;
22720 }
22721
22722 /* Locate the .debug_info compilation unit from CU's objfile which contains
22723    the DIE at OFFSET.  Raises an error on failure.  */
22724
22725 static struct dwarf2_per_cu_data *
22726 dwarf2_find_containing_comp_unit (sect_offset sect_off,
22727                                   unsigned int offset_in_dwz,
22728                                   struct objfile *objfile)
22729 {
22730   struct dwarf2_per_cu_data *this_cu;
22731   int low, high;
22732   const sect_offset *cu_off;
22733
22734   low = 0;
22735   high = dwarf2_per_objfile->n_comp_units - 1;
22736   while (high > low)
22737     {
22738       struct dwarf2_per_cu_data *mid_cu;
22739       int mid = low + (high - low) / 2;
22740
22741       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
22742       cu_off = &mid_cu->sect_off;
22743       if (mid_cu->is_dwz > offset_in_dwz
22744           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
22745         high = mid;
22746       else
22747         low = mid + 1;
22748     }
22749   gdb_assert (low == high);
22750   this_cu = dwarf2_per_objfile->all_comp_units[low];
22751   cu_off = &this_cu->sect_off;
22752   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
22753     {
22754       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
22755         error (_("Dwarf Error: could not find partial DIE containing "
22756                "offset 0x%x [in module %s]"),
22757                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
22758
22759       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
22760                   <= sect_off);
22761       return dwarf2_per_objfile->all_comp_units[low-1];
22762     }
22763   else
22764     {
22765       this_cu = dwarf2_per_objfile->all_comp_units[low];
22766       if (low == dwarf2_per_objfile->n_comp_units - 1
22767           && sect_off >= this_cu->sect_off + this_cu->length)
22768         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
22769       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
22770       return this_cu;
22771     }
22772 }
22773
22774 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
22775
22776 static void
22777 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
22778 {
22779   memset (cu, 0, sizeof (*cu));
22780   per_cu->cu = cu;
22781   cu->per_cu = per_cu;
22782   cu->objfile = per_cu->objfile;
22783   obstack_init (&cu->comp_unit_obstack);
22784 }
22785
22786 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
22787
22788 static void
22789 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
22790                        enum language pretend_language)
22791 {
22792   struct attribute *attr;
22793
22794   /* Set the language we're debugging.  */
22795   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
22796   if (attr)
22797     set_cu_language (DW_UNSND (attr), cu);
22798   else
22799     {
22800       cu->language = pretend_language;
22801       cu->language_defn = language_def (cu->language);
22802     }
22803
22804   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
22805 }
22806
22807 /* Release one cached compilation unit, CU.  We unlink it from the tree
22808    of compilation units, but we don't remove it from the read_in_chain;
22809    the caller is responsible for that.
22810    NOTE: DATA is a void * because this function is also used as a
22811    cleanup routine.  */
22812
22813 static void
22814 free_heap_comp_unit (void *data)
22815 {
22816   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22817
22818   gdb_assert (cu->per_cu != NULL);
22819   cu->per_cu->cu = NULL;
22820   cu->per_cu = NULL;
22821
22822   obstack_free (&cu->comp_unit_obstack, NULL);
22823
22824   xfree (cu);
22825 }
22826
22827 /* This cleanup function is passed the address of a dwarf2_cu on the stack
22828    when we're finished with it.  We can't free the pointer itself, but be
22829    sure to unlink it from the cache.  Also release any associated storage.  */
22830
22831 static void
22832 free_stack_comp_unit (void *data)
22833 {
22834   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
22835
22836   gdb_assert (cu->per_cu != NULL);
22837   cu->per_cu->cu = NULL;
22838   cu->per_cu = NULL;
22839
22840   obstack_free (&cu->comp_unit_obstack, NULL);
22841   cu->partial_dies = NULL;
22842 }
22843
22844 /* Free all cached compilation units.  */
22845
22846 static void
22847 free_cached_comp_units (void *data)
22848 {
22849   dwarf2_per_objfile->free_cached_comp_units ();
22850 }
22851
22852 /* Increase the age counter on each cached compilation unit, and free
22853    any that are too old.  */
22854
22855 static void
22856 age_cached_comp_units (void)
22857 {
22858   struct dwarf2_per_cu_data *per_cu, **last_chain;
22859
22860   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
22861   per_cu = dwarf2_per_objfile->read_in_chain;
22862   while (per_cu != NULL)
22863     {
22864       per_cu->cu->last_used ++;
22865       if (per_cu->cu->last_used <= dwarf_max_cache_age)
22866         dwarf2_mark (per_cu->cu);
22867       per_cu = per_cu->cu->read_in_chain;
22868     }
22869
22870   per_cu = dwarf2_per_objfile->read_in_chain;
22871   last_chain = &dwarf2_per_objfile->read_in_chain;
22872   while (per_cu != NULL)
22873     {
22874       struct dwarf2_per_cu_data *next_cu;
22875
22876       next_cu = per_cu->cu->read_in_chain;
22877
22878       if (!per_cu->cu->mark)
22879         {
22880           free_heap_comp_unit (per_cu->cu);
22881           *last_chain = next_cu;
22882         }
22883       else
22884         last_chain = &per_cu->cu->read_in_chain;
22885
22886       per_cu = next_cu;
22887     }
22888 }
22889
22890 /* Remove a single compilation unit from the cache.  */
22891
22892 static void
22893 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
22894 {
22895   struct dwarf2_per_cu_data *per_cu, **last_chain;
22896
22897   per_cu = dwarf2_per_objfile->read_in_chain;
22898   last_chain = &dwarf2_per_objfile->read_in_chain;
22899   while (per_cu != NULL)
22900     {
22901       struct dwarf2_per_cu_data *next_cu;
22902
22903       next_cu = per_cu->cu->read_in_chain;
22904
22905       if (per_cu == target_per_cu)
22906         {
22907           free_heap_comp_unit (per_cu->cu);
22908           per_cu->cu = NULL;
22909           *last_chain = next_cu;
22910           break;
22911         }
22912       else
22913         last_chain = &per_cu->cu->read_in_chain;
22914
22915       per_cu = next_cu;
22916     }
22917 }
22918
22919 /* Release all extra memory associated with OBJFILE.  */
22920
22921 void
22922 dwarf2_free_objfile (struct objfile *objfile)
22923 {
22924   dwarf2_per_objfile
22925     = (struct dwarf2_per_objfile *) objfile_data (objfile,
22926                                                   dwarf2_objfile_data_key);
22927
22928   if (dwarf2_per_objfile == NULL)
22929     return;
22930
22931   dwarf2_per_objfile->~dwarf2_per_objfile ();
22932 }
22933
22934 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
22935    We store these in a hash table separate from the DIEs, and preserve them
22936    when the DIEs are flushed out of cache.
22937
22938    The CU "per_cu" pointer is needed because offset alone is not enough to
22939    uniquely identify the type.  A file may have multiple .debug_types sections,
22940    or the type may come from a DWO file.  Furthermore, while it's more logical
22941    to use per_cu->section+offset, with Fission the section with the data is in
22942    the DWO file but we don't know that section at the point we need it.
22943    We have to use something in dwarf2_per_cu_data (or the pointer to it)
22944    because we can enter the lookup routine, get_die_type_at_offset, from
22945    outside this file, and thus won't necessarily have PER_CU->cu.
22946    Fortunately, PER_CU is stable for the life of the objfile.  */
22947
22948 struct dwarf2_per_cu_offset_and_type
22949 {
22950   const struct dwarf2_per_cu_data *per_cu;
22951   sect_offset sect_off;
22952   struct type *type;
22953 };
22954
22955 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
22956
22957 static hashval_t
22958 per_cu_offset_and_type_hash (const void *item)
22959 {
22960   const struct dwarf2_per_cu_offset_and_type *ofs
22961     = (const struct dwarf2_per_cu_offset_and_type *) item;
22962
22963   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
22964 }
22965
22966 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
22967
22968 static int
22969 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
22970 {
22971   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
22972     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
22973   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
22974     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
22975
22976   return (ofs_lhs->per_cu == ofs_rhs->per_cu
22977           && ofs_lhs->sect_off == ofs_rhs->sect_off);
22978 }
22979
22980 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
22981    table if necessary.  For convenience, return TYPE.
22982
22983    The DIEs reading must have careful ordering to:
22984     * Not cause infite loops trying to read in DIEs as a prerequisite for
22985       reading current DIE.
22986     * Not trying to dereference contents of still incompletely read in types
22987       while reading in other DIEs.
22988     * Enable referencing still incompletely read in types just by a pointer to
22989       the type without accessing its fields.
22990
22991    Therefore caller should follow these rules:
22992      * Try to fetch any prerequisite types we may need to build this DIE type
22993        before building the type and calling set_die_type.
22994      * After building type call set_die_type for current DIE as soon as
22995        possible before fetching more types to complete the current type.
22996      * Make the type as complete as possible before fetching more types.  */
22997
22998 static struct type *
22999 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23000 {
23001   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23002   struct objfile *objfile = cu->objfile;
23003   struct attribute *attr;
23004   struct dynamic_prop prop;
23005
23006   /* For Ada types, make sure that the gnat-specific data is always
23007      initialized (if not already set).  There are a few types where
23008      we should not be doing so, because the type-specific area is
23009      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23010      where the type-specific area is used to store the floatformat).
23011      But this is not a problem, because the gnat-specific information
23012      is actually not needed for these types.  */
23013   if (need_gnat_info (cu)
23014       && TYPE_CODE (type) != TYPE_CODE_FUNC
23015       && TYPE_CODE (type) != TYPE_CODE_FLT
23016       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23017       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23018       && TYPE_CODE (type) != TYPE_CODE_METHOD
23019       && !HAVE_GNAT_AUX_INFO (type))
23020     INIT_GNAT_SPECIFIC (type);
23021
23022   /* Read DW_AT_allocated and set in type.  */
23023   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23024   if (attr_form_is_block (attr))
23025     {
23026       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23027         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23028     }
23029   else if (attr != NULL)
23030     {
23031       complaint (&symfile_complaints,
23032                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23033                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23034                  to_underlying (die->sect_off));
23035     }
23036
23037   /* Read DW_AT_associated and set in type.  */
23038   attr = dwarf2_attr (die, DW_AT_associated, cu);
23039   if (attr_form_is_block (attr))
23040     {
23041       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23042         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23043     }
23044   else if (attr != NULL)
23045     {
23046       complaint (&symfile_complaints,
23047                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23048                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23049                  to_underlying (die->sect_off));
23050     }
23051
23052   /* Read DW_AT_data_location and set in type.  */
23053   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23054   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23055     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23056
23057   if (dwarf2_per_objfile->die_type_hash == NULL)
23058     {
23059       dwarf2_per_objfile->die_type_hash =
23060         htab_create_alloc_ex (127,
23061                               per_cu_offset_and_type_hash,
23062                               per_cu_offset_and_type_eq,
23063                               NULL,
23064                               &objfile->objfile_obstack,
23065                               hashtab_obstack_allocate,
23066                               dummy_obstack_deallocate);
23067     }
23068
23069   ofs.per_cu = cu->per_cu;
23070   ofs.sect_off = die->sect_off;
23071   ofs.type = type;
23072   slot = (struct dwarf2_per_cu_offset_and_type **)
23073     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23074   if (*slot)
23075     complaint (&symfile_complaints,
23076                _("A problem internal to GDB: DIE 0x%x has type already set"),
23077                to_underlying (die->sect_off));
23078   *slot = XOBNEW (&objfile->objfile_obstack,
23079                   struct dwarf2_per_cu_offset_and_type);
23080   **slot = ofs;
23081   return type;
23082 }
23083
23084 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23085    or return NULL if the die does not have a saved type.  */
23086
23087 static struct type *
23088 get_die_type_at_offset (sect_offset sect_off,
23089                         struct dwarf2_per_cu_data *per_cu)
23090 {
23091   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23092
23093   if (dwarf2_per_objfile->die_type_hash == NULL)
23094     return NULL;
23095
23096   ofs.per_cu = per_cu;
23097   ofs.sect_off = sect_off;
23098   slot = ((struct dwarf2_per_cu_offset_and_type *)
23099           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23100   if (slot)
23101     return slot->type;
23102   else
23103     return NULL;
23104 }
23105
23106 /* Look up the type for DIE in CU in die_type_hash,
23107    or return NULL if DIE does not have a saved type.  */
23108
23109 static struct type *
23110 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23111 {
23112   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23113 }
23114
23115 /* Add a dependence relationship from CU to REF_PER_CU.  */
23116
23117 static void
23118 dwarf2_add_dependence (struct dwarf2_cu *cu,
23119                        struct dwarf2_per_cu_data *ref_per_cu)
23120 {
23121   void **slot;
23122
23123   if (cu->dependencies == NULL)
23124     cu->dependencies
23125       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23126                               NULL, &cu->comp_unit_obstack,
23127                               hashtab_obstack_allocate,
23128                               dummy_obstack_deallocate);
23129
23130   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23131   if (*slot == NULL)
23132     *slot = ref_per_cu;
23133 }
23134
23135 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23136    Set the mark field in every compilation unit in the
23137    cache that we must keep because we are keeping CU.  */
23138
23139 static int
23140 dwarf2_mark_helper (void **slot, void *data)
23141 {
23142   struct dwarf2_per_cu_data *per_cu;
23143
23144   per_cu = (struct dwarf2_per_cu_data *) *slot;
23145
23146   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23147      reading of the chain.  As such dependencies remain valid it is not much
23148      useful to track and undo them during QUIT cleanups.  */
23149   if (per_cu->cu == NULL)
23150     return 1;
23151
23152   if (per_cu->cu->mark)
23153     return 1;
23154   per_cu->cu->mark = 1;
23155
23156   if (per_cu->cu->dependencies != NULL)
23157     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23158
23159   return 1;
23160 }
23161
23162 /* Set the mark field in CU and in every other compilation unit in the
23163    cache that we must keep because we are keeping CU.  */
23164
23165 static void
23166 dwarf2_mark (struct dwarf2_cu *cu)
23167 {
23168   if (cu->mark)
23169     return;
23170   cu->mark = 1;
23171   if (cu->dependencies != NULL)
23172     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23173 }
23174
23175 static void
23176 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23177 {
23178   while (per_cu)
23179     {
23180       per_cu->cu->mark = 0;
23181       per_cu = per_cu->cu->read_in_chain;
23182     }
23183 }
23184
23185 /* Trivial hash function for partial_die_info: the hash value of a DIE
23186    is its offset in .debug_info for this objfile.  */
23187
23188 static hashval_t
23189 partial_die_hash (const void *item)
23190 {
23191   const struct partial_die_info *part_die
23192     = (const struct partial_die_info *) item;
23193
23194   return to_underlying (part_die->sect_off);
23195 }
23196
23197 /* Trivial comparison function for partial_die_info structures: two DIEs
23198    are equal if they have the same offset.  */
23199
23200 static int
23201 partial_die_eq (const void *item_lhs, const void *item_rhs)
23202 {
23203   const struct partial_die_info *part_die_lhs
23204     = (const struct partial_die_info *) item_lhs;
23205   const struct partial_die_info *part_die_rhs
23206     = (const struct partial_die_info *) item_rhs;
23207
23208   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23209 }
23210
23211 static struct cmd_list_element *set_dwarf_cmdlist;
23212 static struct cmd_list_element *show_dwarf_cmdlist;
23213
23214 static void
23215 set_dwarf_cmd (const char *args, int from_tty)
23216 {
23217   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23218              gdb_stdout);
23219 }
23220
23221 static void
23222 show_dwarf_cmd (const char *args, int from_tty)
23223 {
23224   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23225 }
23226
23227 /* Free data associated with OBJFILE, if necessary.  */
23228
23229 static void
23230 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23231 {
23232   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23233   int ix;
23234
23235   /* Make sure we don't accidentally use dwarf2_per_objfile while
23236      cleaning up.  */
23237   dwarf2_per_objfile = NULL;
23238
23239   for (ix = 0; ix < data->n_comp_units; ++ix)
23240    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23241
23242   for (ix = 0; ix < data->n_type_units; ++ix)
23243     VEC_free (dwarf2_per_cu_ptr,
23244               data->all_type_units[ix]->per_cu.imported_symtabs);
23245   xfree (data->all_type_units);
23246
23247   VEC_free (dwarf2_section_info_def, data->types);
23248
23249   if (data->dwo_files)
23250     free_dwo_files (data->dwo_files, objfile);
23251   if (data->dwp_file)
23252     gdb_bfd_unref (data->dwp_file->dbfd);
23253
23254   if (data->dwz_file && data->dwz_file->dwz_bfd)
23255     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23256 }
23257
23258 \f
23259 /* The "save gdb-index" command.  */
23260
23261 /* In-memory buffer to prepare data to be written later to a file.  */
23262 class data_buf
23263 {
23264 public:
23265   /* Copy DATA to the end of the buffer.  */
23266   template<typename T>
23267   void append_data (const T &data)
23268   {
23269     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23270                reinterpret_cast<const gdb_byte *> (&data + 1),
23271                grow (sizeof (data)));
23272   }
23273
23274   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23275      terminating zero is appended too.  */
23276   void append_cstr0 (const char *cstr)
23277   {
23278     const size_t size = strlen (cstr) + 1;
23279     std::copy (cstr, cstr + size, grow (size));
23280   }
23281
23282   /* Accept a host-format integer in VAL and append it to the buffer
23283      as a target-format integer which is LEN bytes long.  */
23284   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23285   {
23286     ::store_unsigned_integer (grow (len), len, byte_order, val);
23287   }
23288
23289   /* Return the size of the buffer.  */
23290   size_t size () const
23291   {
23292     return m_vec.size ();
23293   }
23294
23295   /* Write the buffer to FILE.  */
23296   void file_write (FILE *file) const
23297   {
23298     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23299       error (_("couldn't write data to file"));
23300   }
23301
23302 private:
23303   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23304      the start of the new block.  */
23305   gdb_byte *grow (size_t size)
23306   {
23307     m_vec.resize (m_vec.size () + size);
23308     return &*m_vec.end () - size;
23309   }
23310
23311   gdb::byte_vector m_vec;
23312 };
23313
23314 /* An entry in the symbol table.  */
23315 struct symtab_index_entry
23316 {
23317   /* The name of the symbol.  */
23318   const char *name;
23319   /* The offset of the name in the constant pool.  */
23320   offset_type index_offset;
23321   /* A sorted vector of the indices of all the CUs that hold an object
23322      of this name.  */
23323   std::vector<offset_type> cu_indices;
23324 };
23325
23326 /* The symbol table.  This is a power-of-2-sized hash table.  */
23327 struct mapped_symtab
23328 {
23329   mapped_symtab ()
23330   {
23331     data.resize (1024);
23332   }
23333
23334   offset_type n_elements = 0;
23335   std::vector<symtab_index_entry> data;
23336 };
23337
23338 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23339    the slot.
23340    
23341    Function is used only during write_hash_table so no index format backward
23342    compatibility is needed.  */
23343
23344 static symtab_index_entry &
23345 find_slot (struct mapped_symtab *symtab, const char *name)
23346 {
23347   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23348
23349   index = hash & (symtab->data.size () - 1);
23350   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23351
23352   for (;;)
23353     {
23354       if (symtab->data[index].name == NULL
23355           || strcmp (name, symtab->data[index].name) == 0)
23356         return symtab->data[index];
23357       index = (index + step) & (symtab->data.size () - 1);
23358     }
23359 }
23360
23361 /* Expand SYMTAB's hash table.  */
23362
23363 static void
23364 hash_expand (struct mapped_symtab *symtab)
23365 {
23366   auto old_entries = std::move (symtab->data);
23367
23368   symtab->data.clear ();
23369   symtab->data.resize (old_entries.size () * 2);
23370
23371   for (auto &it : old_entries)
23372     if (it.name != NULL)
23373       {
23374         auto &ref = find_slot (symtab, it.name);
23375         ref = std::move (it);
23376       }
23377 }
23378
23379 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23380    CU_INDEX is the index of the CU in which the symbol appears.
23381    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23382
23383 static void
23384 add_index_entry (struct mapped_symtab *symtab, const char *name,
23385                  int is_static, gdb_index_symbol_kind kind,
23386                  offset_type cu_index)
23387 {
23388   offset_type cu_index_and_attrs;
23389
23390   ++symtab->n_elements;
23391   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23392     hash_expand (symtab);
23393
23394   symtab_index_entry &slot = find_slot (symtab, name);
23395   if (slot.name == NULL)
23396     {
23397       slot.name = name;
23398       /* index_offset is set later.  */
23399     }
23400
23401   cu_index_and_attrs = 0;
23402   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23403   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23404   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23405
23406   /* We don't want to record an index value twice as we want to avoid the
23407      duplication.
23408      We process all global symbols and then all static symbols
23409      (which would allow us to avoid the duplication by only having to check
23410      the last entry pushed), but a symbol could have multiple kinds in one CU.
23411      To keep things simple we don't worry about the duplication here and
23412      sort and uniqufy the list after we've processed all symbols.  */
23413   slot.cu_indices.push_back (cu_index_and_attrs);
23414 }
23415
23416 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23417
23418 static void
23419 uniquify_cu_indices (struct mapped_symtab *symtab)
23420 {
23421   for (auto &entry : symtab->data)
23422     {
23423       if (entry.name != NULL && !entry.cu_indices.empty ())
23424         {
23425           auto &cu_indices = entry.cu_indices;
23426           std::sort (cu_indices.begin (), cu_indices.end ());
23427           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23428           cu_indices.erase (from, cu_indices.end ());
23429         }
23430     }
23431 }
23432
23433 /* A form of 'const char *' suitable for container keys.  Only the
23434    pointer is stored.  The strings themselves are compared, not the
23435    pointers.  */
23436 class c_str_view
23437 {
23438 public:
23439   c_str_view (const char *cstr)
23440     : m_cstr (cstr)
23441   {}
23442
23443   bool operator== (const c_str_view &other) const
23444   {
23445     return strcmp (m_cstr, other.m_cstr) == 0;
23446   }
23447
23448 private:
23449   friend class c_str_view_hasher;
23450   const char *const m_cstr;
23451 };
23452
23453 /* A std::unordered_map::hasher for c_str_view that uses the right
23454    hash function for strings in a mapped index.  */
23455 class c_str_view_hasher
23456 {
23457 public:
23458   size_t operator () (const c_str_view &x) const
23459   {
23460     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23461   }
23462 };
23463
23464 /* A std::unordered_map::hasher for std::vector<>.  */
23465 template<typename T>
23466 class vector_hasher
23467 {
23468 public:
23469   size_t operator () (const std::vector<T> &key) const
23470   {
23471     return iterative_hash (key.data (),
23472                            sizeof (key.front ()) * key.size (), 0);
23473   }
23474 };
23475
23476 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23477    constant pool entries going into the data buffer CPOOL.  */
23478
23479 static void
23480 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23481 {
23482   {
23483     /* Elements are sorted vectors of the indices of all the CUs that
23484        hold an object of this name.  */
23485     std::unordered_map<std::vector<offset_type>, offset_type,
23486                        vector_hasher<offset_type>>
23487       symbol_hash_table;
23488
23489     /* We add all the index vectors to the constant pool first, to
23490        ensure alignment is ok.  */
23491     for (symtab_index_entry &entry : symtab->data)
23492       {
23493         if (entry.name == NULL)
23494           continue;
23495         gdb_assert (entry.index_offset == 0);
23496
23497         /* Finding before inserting is faster than always trying to
23498            insert, because inserting always allocates a node, does the
23499            lookup, and then destroys the new node if another node
23500            already had the same key.  C++17 try_emplace will avoid
23501            this.  */
23502         const auto found
23503           = symbol_hash_table.find (entry.cu_indices);
23504         if (found != symbol_hash_table.end ())
23505           {
23506             entry.index_offset = found->second;
23507             continue;
23508           }
23509
23510         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23511         entry.index_offset = cpool.size ();
23512         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23513         for (const auto index : entry.cu_indices)
23514           cpool.append_data (MAYBE_SWAP (index));
23515       }
23516   }
23517
23518   /* Now write out the hash table.  */
23519   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23520   for (const auto &entry : symtab->data)
23521     {
23522       offset_type str_off, vec_off;
23523
23524       if (entry.name != NULL)
23525         {
23526           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23527           if (insertpair.second)
23528             cpool.append_cstr0 (entry.name);
23529           str_off = insertpair.first->second;
23530           vec_off = entry.index_offset;
23531         }
23532       else
23533         {
23534           /* While 0 is a valid constant pool index, it is not valid
23535              to have 0 for both offsets.  */
23536           str_off = 0;
23537           vec_off = 0;
23538         }
23539
23540       output.append_data (MAYBE_SWAP (str_off));
23541       output.append_data (MAYBE_SWAP (vec_off));
23542     }
23543 }
23544
23545 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23546
23547 /* Helper struct for building the address table.  */
23548 struct addrmap_index_data
23549 {
23550   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23551     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23552   {}
23553
23554   struct objfile *objfile;
23555   data_buf &addr_vec;
23556   psym_index_map &cu_index_htab;
23557
23558   /* Non-zero if the previous_* fields are valid.
23559      We can't write an entry until we see the next entry (since it is only then
23560      that we know the end of the entry).  */
23561   int previous_valid;
23562   /* Index of the CU in the table of all CUs in the index file.  */
23563   unsigned int previous_cu_index;
23564   /* Start address of the CU.  */
23565   CORE_ADDR previous_cu_start;
23566 };
23567
23568 /* Write an address entry to ADDR_VEC.  */
23569
23570 static void
23571 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23572                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23573 {
23574   CORE_ADDR baseaddr;
23575
23576   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23577
23578   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23579   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23580   addr_vec.append_data (MAYBE_SWAP (cu_index));
23581 }
23582
23583 /* Worker function for traversing an addrmap to build the address table.  */
23584
23585 static int
23586 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23587 {
23588   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23589   struct partial_symtab *pst = (struct partial_symtab *) obj;
23590
23591   if (data->previous_valid)
23592     add_address_entry (data->objfile, data->addr_vec,
23593                        data->previous_cu_start, start_addr,
23594                        data->previous_cu_index);
23595
23596   data->previous_cu_start = start_addr;
23597   if (pst != NULL)
23598     {
23599       const auto it = data->cu_index_htab.find (pst);
23600       gdb_assert (it != data->cu_index_htab.cend ());
23601       data->previous_cu_index = it->second;
23602       data->previous_valid = 1;
23603     }
23604   else
23605     data->previous_valid = 0;
23606
23607   return 0;
23608 }
23609
23610 /* Write OBJFILE's address map to ADDR_VEC.
23611    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23612    in the index file.  */
23613
23614 static void
23615 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23616                    psym_index_map &cu_index_htab)
23617 {
23618   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23619
23620   /* When writing the address table, we have to cope with the fact that
23621      the addrmap iterator only provides the start of a region; we have to
23622      wait until the next invocation to get the start of the next region.  */
23623
23624   addrmap_index_data.objfile = objfile;
23625   addrmap_index_data.previous_valid = 0;
23626
23627   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23628                    &addrmap_index_data);
23629
23630   /* It's highly unlikely the last entry (end address = 0xff...ff)
23631      is valid, but we should still handle it.
23632      The end address is recorded as the start of the next region, but that
23633      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23634      anyway.  */
23635   if (addrmap_index_data.previous_valid)
23636     add_address_entry (objfile, addr_vec,
23637                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23638                        addrmap_index_data.previous_cu_index);
23639 }
23640
23641 /* Return the symbol kind of PSYM.  */
23642
23643 static gdb_index_symbol_kind
23644 symbol_kind (struct partial_symbol *psym)
23645 {
23646   domain_enum domain = PSYMBOL_DOMAIN (psym);
23647   enum address_class aclass = PSYMBOL_CLASS (psym);
23648
23649   switch (domain)
23650     {
23651     case VAR_DOMAIN:
23652       switch (aclass)
23653         {
23654         case LOC_BLOCK:
23655           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23656         case LOC_TYPEDEF:
23657           return GDB_INDEX_SYMBOL_KIND_TYPE;
23658         case LOC_COMPUTED:
23659         case LOC_CONST_BYTES:
23660         case LOC_OPTIMIZED_OUT:
23661         case LOC_STATIC:
23662           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23663         case LOC_CONST:
23664           /* Note: It's currently impossible to recognize psyms as enum values
23665              short of reading the type info.  For now punt.  */
23666           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23667         default:
23668           /* There are other LOC_FOO values that one might want to classify
23669              as variables, but dwarf2read.c doesn't currently use them.  */
23670           return GDB_INDEX_SYMBOL_KIND_OTHER;
23671         }
23672     case STRUCT_DOMAIN:
23673       return GDB_INDEX_SYMBOL_KIND_TYPE;
23674     default:
23675       return GDB_INDEX_SYMBOL_KIND_OTHER;
23676     }
23677 }
23678
23679 /* Add a list of partial symbols to SYMTAB.  */
23680
23681 static void
23682 write_psymbols (struct mapped_symtab *symtab,
23683                 std::unordered_set<partial_symbol *> &psyms_seen,
23684                 struct partial_symbol **psymp,
23685                 int count,
23686                 offset_type cu_index,
23687                 int is_static)
23688 {
23689   for (; count-- > 0; ++psymp)
23690     {
23691       struct partial_symbol *psym = *psymp;
23692
23693       if (SYMBOL_LANGUAGE (psym) == language_ada)
23694         error (_("Ada is not currently supported by the index"));
23695
23696       /* Only add a given psymbol once.  */
23697       if (psyms_seen.insert (psym).second)
23698         {
23699           gdb_index_symbol_kind kind = symbol_kind (psym);
23700
23701           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
23702                            is_static, kind, cu_index);
23703         }
23704     }
23705 }
23706
23707 /* A helper struct used when iterating over debug_types.  */
23708 struct signatured_type_index_data
23709 {
23710   signatured_type_index_data (data_buf &types_list_,
23711                               std::unordered_set<partial_symbol *> &psyms_seen_)
23712     : types_list (types_list_), psyms_seen (psyms_seen_)
23713   {}
23714
23715   struct objfile *objfile;
23716   struct mapped_symtab *symtab;
23717   data_buf &types_list;
23718   std::unordered_set<partial_symbol *> &psyms_seen;
23719   int cu_index;
23720 };
23721
23722 /* A helper function that writes a single signatured_type to an
23723    obstack.  */
23724
23725 static int
23726 write_one_signatured_type (void **slot, void *d)
23727 {
23728   struct signatured_type_index_data *info
23729     = (struct signatured_type_index_data *) d;
23730   struct signatured_type *entry = (struct signatured_type *) *slot;
23731   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
23732
23733   write_psymbols (info->symtab,
23734                   info->psyms_seen,
23735                   info->objfile->global_psymbols.list
23736                   + psymtab->globals_offset,
23737                   psymtab->n_global_syms, info->cu_index,
23738                   0);
23739   write_psymbols (info->symtab,
23740                   info->psyms_seen,
23741                   info->objfile->static_psymbols.list
23742                   + psymtab->statics_offset,
23743                   psymtab->n_static_syms, info->cu_index,
23744                   1);
23745
23746   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23747                                 to_underlying (entry->per_cu.sect_off));
23748   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
23749                                 to_underlying (entry->type_offset_in_tu));
23750   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
23751
23752   ++info->cu_index;
23753
23754   return 1;
23755 }
23756
23757 /* Recurse into all "included" dependencies and count their symbols as
23758    if they appeared in this psymtab.  */
23759
23760 static void
23761 recursively_count_psymbols (struct partial_symtab *psymtab,
23762                             size_t &psyms_seen)
23763 {
23764   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
23765     if (psymtab->dependencies[i]->user != NULL)
23766       recursively_count_psymbols (psymtab->dependencies[i],
23767                                   psyms_seen);
23768
23769   psyms_seen += psymtab->n_global_syms;
23770   psyms_seen += psymtab->n_static_syms;
23771 }
23772
23773 /* Recurse into all "included" dependencies and write their symbols as
23774    if they appeared in this psymtab.  */
23775
23776 static void
23777 recursively_write_psymbols (struct objfile *objfile,
23778                             struct partial_symtab *psymtab,
23779                             struct mapped_symtab *symtab,
23780                             std::unordered_set<partial_symbol *> &psyms_seen,
23781                             offset_type cu_index)
23782 {
23783   int i;
23784
23785   for (i = 0; i < psymtab->number_of_dependencies; ++i)
23786     if (psymtab->dependencies[i]->user != NULL)
23787       recursively_write_psymbols (objfile, psymtab->dependencies[i],
23788                                   symtab, psyms_seen, cu_index);
23789
23790   write_psymbols (symtab,
23791                   psyms_seen,
23792                   objfile->global_psymbols.list + psymtab->globals_offset,
23793                   psymtab->n_global_syms, cu_index,
23794                   0);
23795   write_psymbols (symtab,
23796                   psyms_seen,
23797                   objfile->static_psymbols.list + psymtab->statics_offset,
23798                   psymtab->n_static_syms, cu_index,
23799                   1);
23800 }
23801
23802 /* Create an index file for OBJFILE in the directory DIR.  */
23803
23804 static void
23805 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
23806 {
23807   if (dwarf2_per_objfile->using_index)
23808     error (_("Cannot use an index to create the index"));
23809
23810   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
23811     error (_("Cannot make an index when the file has multiple .debug_types sections"));
23812
23813   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
23814     return;
23815
23816   struct stat st;
23817   if (stat (objfile_name (objfile), &st) < 0)
23818     perror_with_name (objfile_name (objfile));
23819
23820   std::string filename (std::string (dir) + SLASH_STRING
23821                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
23822
23823   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
23824   if (!out_file)
23825     error (_("Can't open `%s' for writing"), filename.c_str ());
23826
23827   /* Order matters here; we want FILE to be closed before FILENAME is
23828      unlinked, because on MS-Windows one cannot delete a file that is
23829      still open.  (Don't call anything here that might throw until
23830      file_closer is created.)  */
23831   gdb::unlinker unlink_file (filename.c_str ());
23832   gdb_file_up close_out_file (out_file);
23833
23834   mapped_symtab symtab;
23835   data_buf cu_list;
23836
23837   /* While we're scanning CU's create a table that maps a psymtab pointer
23838      (which is what addrmap records) to its index (which is what is recorded
23839      in the index file).  This will later be needed to write the address
23840      table.  */
23841   psym_index_map cu_index_htab;
23842   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
23843
23844   /* The CU list is already sorted, so we don't need to do additional
23845      work here.  Also, the debug_types entries do not appear in
23846      all_comp_units, but only in their own hash table.  */
23847
23848   /* The psyms_seen set is potentially going to be largish (~40k
23849      elements when indexing a -g3 build of GDB itself).  Estimate the
23850      number of elements in order to avoid too many rehashes, which
23851      require rebuilding buckets and thus many trips to
23852      malloc/free.  */
23853   size_t psyms_count = 0;
23854   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23855     {
23856       struct dwarf2_per_cu_data *per_cu
23857         = dwarf2_per_objfile->all_comp_units[i];
23858       struct partial_symtab *psymtab = per_cu->v.psymtab;
23859
23860       if (psymtab != NULL && psymtab->user == NULL)
23861         recursively_count_psymbols (psymtab, psyms_count);
23862     }
23863   /* Generating an index for gdb itself shows a ratio of
23864      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
23865   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
23866   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
23867     {
23868       struct dwarf2_per_cu_data *per_cu
23869         = dwarf2_per_objfile->all_comp_units[i];
23870       struct partial_symtab *psymtab = per_cu->v.psymtab;
23871
23872       /* CU of a shared file from 'dwz -m' may be unused by this main file.
23873          It may be referenced from a local scope but in such case it does not
23874          need to be present in .gdb_index.  */
23875       if (psymtab == NULL)
23876         continue;
23877
23878       if (psymtab->user == NULL)
23879         recursively_write_psymbols (objfile, psymtab, &symtab,
23880                                     psyms_seen, i);
23881
23882       const auto insertpair = cu_index_htab.emplace (psymtab, i);
23883       gdb_assert (insertpair.second);
23884
23885       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
23886                            to_underlying (per_cu->sect_off));
23887       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
23888     }
23889
23890   /* Dump the address map.  */
23891   data_buf addr_vec;
23892   write_address_map (objfile, addr_vec, cu_index_htab);
23893
23894   /* Write out the .debug_type entries, if any.  */
23895   data_buf types_cu_list;
23896   if (dwarf2_per_objfile->signatured_types)
23897     {
23898       signatured_type_index_data sig_data (types_cu_list,
23899                                            psyms_seen);
23900
23901       sig_data.objfile = objfile;
23902       sig_data.symtab = &symtab;
23903       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
23904       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
23905                               write_one_signatured_type, &sig_data);
23906     }
23907
23908   /* Now that we've processed all symbols we can shrink their cu_indices
23909      lists.  */
23910   uniquify_cu_indices (&symtab);
23911
23912   data_buf symtab_vec, constant_pool;
23913   write_hash_table (&symtab, symtab_vec, constant_pool);
23914
23915   data_buf contents;
23916   const offset_type size_of_contents = 6 * sizeof (offset_type);
23917   offset_type total_len = size_of_contents;
23918
23919   /* The version number.  */
23920   contents.append_data (MAYBE_SWAP (8));
23921
23922   /* The offset of the CU list from the start of the file.  */
23923   contents.append_data (MAYBE_SWAP (total_len));
23924   total_len += cu_list.size ();
23925
23926   /* The offset of the types CU list from the start of the file.  */
23927   contents.append_data (MAYBE_SWAP (total_len));
23928   total_len += types_cu_list.size ();
23929
23930   /* The offset of the address table from the start of the file.  */
23931   contents.append_data (MAYBE_SWAP (total_len));
23932   total_len += addr_vec.size ();
23933
23934   /* The offset of the symbol table from the start of the file.  */
23935   contents.append_data (MAYBE_SWAP (total_len));
23936   total_len += symtab_vec.size ();
23937
23938   /* The offset of the constant pool from the start of the file.  */
23939   contents.append_data (MAYBE_SWAP (total_len));
23940   total_len += constant_pool.size ();
23941
23942   gdb_assert (contents.size () == size_of_contents);
23943
23944   contents.file_write (out_file);
23945   cu_list.file_write (out_file);
23946   types_cu_list.file_write (out_file);
23947   addr_vec.file_write (out_file);
23948   symtab_vec.file_write (out_file);
23949   constant_pool.file_write (out_file);
23950
23951   /* We want to keep the file.  */
23952   unlink_file.keep ();
23953 }
23954
23955 /* Implementation of the `save gdb-index' command.
23956    
23957    Note that the file format used by this command is documented in the
23958    GDB manual.  Any changes here must be documented there.  */
23959
23960 static void
23961 save_gdb_index_command (const char *arg, int from_tty)
23962 {
23963   struct objfile *objfile;
23964
23965   if (!arg || !*arg)
23966     error (_("usage: save gdb-index DIRECTORY"));
23967
23968   ALL_OBJFILES (objfile)
23969   {
23970     struct stat st;
23971
23972     /* If the objfile does not correspond to an actual file, skip it.  */
23973     if (stat (objfile_name (objfile), &st) < 0)
23974       continue;
23975
23976     dwarf2_per_objfile
23977       = (struct dwarf2_per_objfile *) objfile_data (objfile,
23978                                                     dwarf2_objfile_data_key);
23979     if (dwarf2_per_objfile)
23980       {
23981
23982         TRY
23983           {
23984             write_psymtabs_to_index (objfile, arg);
23985           }
23986         CATCH (except, RETURN_MASK_ERROR)
23987           {
23988             exception_fprintf (gdb_stderr, except,
23989                                _("Error while writing index for `%s': "),
23990                                objfile_name (objfile));
23991           }
23992         END_CATCH
23993       }
23994   }
23995 }
23996
23997 \f
23998
23999 int dwarf_always_disassemble;
24000
24001 static void
24002 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24003                                struct cmd_list_element *c, const char *value)
24004 {
24005   fprintf_filtered (file,
24006                     _("Whether to always disassemble "
24007                       "DWARF expressions is %s.\n"),
24008                     value);
24009 }
24010
24011 static void
24012 show_check_physname (struct ui_file *file, int from_tty,
24013                      struct cmd_list_element *c, const char *value)
24014 {
24015   fprintf_filtered (file,
24016                     _("Whether to check \"physname\" is %s.\n"),
24017                     value);
24018 }
24019
24020 void
24021 _initialize_dwarf2_read (void)
24022 {
24023   struct cmd_list_element *c;
24024
24025   dwarf2_objfile_data_key
24026     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24027
24028   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24029 Set DWARF specific variables.\n\
24030 Configure DWARF variables such as the cache size"),
24031                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24032                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24033
24034   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24035 Show DWARF specific variables\n\
24036 Show DWARF variables such as the cache size"),
24037                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24038                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24039
24040   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24041                             &dwarf_max_cache_age, _("\
24042 Set the upper bound on the age of cached DWARF compilation units."), _("\
24043 Show the upper bound on the age of cached DWARF compilation units."), _("\
24044 A higher limit means that cached compilation units will be stored\n\
24045 in memory longer, and more total memory will be used.  Zero disables\n\
24046 caching, which can slow down startup."),
24047                             NULL,
24048                             show_dwarf_max_cache_age,
24049                             &set_dwarf_cmdlist,
24050                             &show_dwarf_cmdlist);
24051
24052   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24053                            &dwarf_always_disassemble, _("\
24054 Set whether `info address' always disassembles DWARF expressions."), _("\
24055 Show whether `info address' always disassembles DWARF expressions."), _("\
24056 When enabled, DWARF expressions are always printed in an assembly-like\n\
24057 syntax.  When disabled, expressions will be printed in a more\n\
24058 conversational style, when possible."),
24059                            NULL,
24060                            show_dwarf_always_disassemble,
24061                            &set_dwarf_cmdlist,
24062                            &show_dwarf_cmdlist);
24063
24064   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24065 Set debugging of the DWARF reader."), _("\
24066 Show debugging of the DWARF reader."), _("\
24067 When enabled (non-zero), debugging messages are printed during DWARF\n\
24068 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24069 information.  A value greater than 1 provides more verbose information."),
24070                             NULL,
24071                             NULL,
24072                             &setdebuglist, &showdebuglist);
24073
24074   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24075 Set debugging of the DWARF DIE reader."), _("\
24076 Show debugging of the DWARF DIE reader."), _("\
24077 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24078 The value is the maximum depth to print."),
24079                              NULL,
24080                              NULL,
24081                              &setdebuglist, &showdebuglist);
24082
24083   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24084 Set debugging of the dwarf line reader."), _("\
24085 Show debugging of the dwarf line reader."), _("\
24086 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24087 A value of 1 (one) provides basic information.\n\
24088 A value greater than 1 provides more verbose information."),
24089                              NULL,
24090                              NULL,
24091                              &setdebuglist, &showdebuglist);
24092
24093   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24094 Set cross-checking of \"physname\" code against demangler."), _("\
24095 Show cross-checking of \"physname\" code against demangler."), _("\
24096 When enabled, GDB's internal \"physname\" code is checked against\n\
24097 the demangler."),
24098                            NULL, show_check_physname,
24099                            &setdebuglist, &showdebuglist);
24100
24101   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24102                            no_class, &use_deprecated_index_sections, _("\
24103 Set whether to use deprecated gdb_index sections."), _("\
24104 Show whether to use deprecated gdb_index sections."), _("\
24105 When enabled, deprecated .gdb_index sections are used anyway.\n\
24106 Normally they are ignored either because of a missing feature or\n\
24107 performance issue.\n\
24108 Warning: This option must be enabled before gdb reads the file."),
24109                            NULL,
24110                            NULL,
24111                            &setlist, &showlist);
24112
24113   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24114                _("\
24115 Save a gdb-index file.\n\
24116 Usage: save gdb-index DIRECTORY"),
24117                &save_cmdlist);
24118   set_cmd_completer (c, filename_completer);
24119
24120   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24121                                                         &dwarf2_locexpr_funcs);
24122   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24123                                                         &dwarf2_loclist_funcs);
24124
24125   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24126                                         &dwarf2_block_frame_base_locexpr_funcs);
24127   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24128                                         &dwarf2_block_frame_base_loclist_funcs);
24129 }