Optimize .gdb_index symbol name searching
[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 #if WORDS_BIGENDIAN
186
187 /* Convert VALUE between big- and little-endian.  */
188
189 static offset_type
190 byte_swap (offset_type value)
191 {
192   offset_type result;
193
194   result = (value & 0xff) << 24;
195   result |= (value & 0xff00) << 8;
196   result |= (value & 0xff0000) >> 8;
197   result |= (value & 0xff000000) >> 24;
198   return result;
199 }
200
201 #define MAYBE_SWAP(V)  byte_swap (V)
202
203 #else
204 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
205 #endif /* WORDS_BIGENDIAN */
206
207 /* An index into a (C++) symbol name component in a symbol name as
208    recorded in the mapped_index's symbol table.  For each C++ symbol
209    in the symbol table, we record one entry for the start of each
210    component in the symbol in a table of name components, and then
211    sort the table, in order to be able to binary search symbol names,
212    ignoring leading namespaces, both completion and regular look up.
213    For example, for symbol "A::B::C", we'll have an entry that points
214    to "A::B::C", another that points to "B::C", and another for "C".
215    Note that function symbols in GDB index have no parameter
216    information, just the function/method names.  You can convert a
217    name_component to a "const char *" using the
218    'mapped_index::symbol_name_at(offset_type)' method.  */
219
220 struct name_component
221 {
222   /* Offset in the symbol name where the component starts.  Stored as
223      a (32-bit) offset instead of a pointer to save memory and improve
224      locality on 64-bit architectures.  */
225   offset_type name_offset;
226
227   /* The symbol's index in the symbol and constant pool tables of a
228      mapped_index.  */
229   offset_type idx;
230 };
231
232 /* A description of the mapped index.  The file format is described in
233    a comment by the code that writes the index.  */
234 struct mapped_index
235 {
236   /* Index data format version.  */
237   int version;
238
239   /* The total length of the buffer.  */
240   off_t total_size;
241
242   /* A pointer to the address table data.  */
243   const gdb_byte *address_table;
244
245   /* Size of the address table data in bytes.  */
246   offset_type address_table_size;
247
248   /* The symbol table, implemented as a hash table.  */
249   const offset_type *symbol_table;
250
251   /* Size in slots, each slot is 2 offset_types.  */
252   offset_type symbol_table_slots;
253
254   /* A pointer to the constant pool.  */
255   const char *constant_pool;
256
257   /* The name_component table (a sorted vector).  See name_component's
258      description above.  */
259   std::vector<name_component> name_components;
260
261   /* Convenience method to get at the name of the symbol at IDX in the
262      symbol table.  */
263   const char *symbol_name_at (offset_type idx) const
264   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
265 };
266
267 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
268 DEF_VEC_P (dwarf2_per_cu_ptr);
269
270 struct tu_stats
271 {
272   int nr_uniq_abbrev_tables;
273   int nr_symtabs;
274   int nr_symtab_sharers;
275   int nr_stmt_less_type_units;
276   int nr_all_type_units_reallocs;
277 };
278
279 /* Collection of data recorded per objfile.
280    This hangs off of dwarf2_objfile_data_key.  */
281
282 struct dwarf2_per_objfile
283 {
284   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
285      dwarf2 section names, or is NULL if the standard ELF names are
286      used.  */
287   dwarf2_per_objfile (struct objfile *objfile,
288                       const dwarf2_debug_sections *names);
289
290   ~dwarf2_per_objfile ();
291
292   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
293
294   /* Free all cached compilation units.  */
295   void free_cached_comp_units ();
296 private:
297   /* This function is mapped across the sections and remembers the
298      offset and size of each of the debugging sections we are
299      interested in.  */
300   void locate_sections (bfd *abfd, asection *sectp,
301                         const dwarf2_debug_sections &names);
302
303 public:
304   dwarf2_section_info info {};
305   dwarf2_section_info abbrev {};
306   dwarf2_section_info line {};
307   dwarf2_section_info loc {};
308   dwarf2_section_info loclists {};
309   dwarf2_section_info macinfo {};
310   dwarf2_section_info macro {};
311   dwarf2_section_info str {};
312   dwarf2_section_info line_str {};
313   dwarf2_section_info ranges {};
314   dwarf2_section_info rnglists {};
315   dwarf2_section_info addr {};
316   dwarf2_section_info frame {};
317   dwarf2_section_info eh_frame {};
318   dwarf2_section_info gdb_index {};
319
320   VEC (dwarf2_section_info_def) *types = NULL;
321
322   /* Back link.  */
323   struct objfile *objfile = NULL;
324
325   /* Table of all the compilation units.  This is used to locate
326      the target compilation unit of a particular reference.  */
327   struct dwarf2_per_cu_data **all_comp_units = NULL;
328
329   /* The number of compilation units in ALL_COMP_UNITS.  */
330   int n_comp_units = 0;
331
332   /* The number of .debug_types-related CUs.  */
333   int n_type_units = 0;
334
335   /* The number of elements allocated in all_type_units.
336      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
337   int n_allocated_type_units = 0;
338
339   /* The .debug_types-related CUs (TUs).
340      This is stored in malloc space because we may realloc it.  */
341   struct signatured_type **all_type_units = NULL;
342
343   /* Table of struct type_unit_group objects.
344      The hash key is the DW_AT_stmt_list value.  */
345   htab_t type_unit_groups {};
346
347   /* A table mapping .debug_types signatures to its signatured_type entry.
348      This is NULL if the .debug_types section hasn't been read in yet.  */
349   htab_t signatured_types {};
350
351   /* Type unit statistics, to see how well the scaling improvements
352      are doing.  */
353   struct tu_stats tu_stats {};
354
355   /* A chain of compilation units that are currently read in, so that
356      they can be freed later.  */
357   dwarf2_per_cu_data *read_in_chain = NULL;
358
359   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
360      This is NULL if the table hasn't been allocated yet.  */
361   htab_t dwo_files {};
362
363   /* True if we've checked for whether there is a DWP file.  */
364   bool dwp_checked = false;
365
366   /* The DWP file if there is one, or NULL.  */
367   struct dwp_file *dwp_file = NULL;
368
369   /* The shared '.dwz' file, if one exists.  This is used when the
370      original data was compressed using 'dwz -m'.  */
371   struct dwz_file *dwz_file = NULL;
372
373   /* A flag indicating whether this objfile has a section loaded at a
374      VMA of 0.  */
375   bool has_section_at_zero = false;
376
377   /* True if we are using the mapped index,
378      or we are faking it for OBJF_READNOW's sake.  */
379   bool using_index = false;
380
381   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
382   mapped_index *index_table = NULL;
383
384   /* When using index_table, this keeps track of all quick_file_names entries.
385      TUs typically share line table entries with a CU, so we maintain a
386      separate table of all line table entries to support the sharing.
387      Note that while there can be way more TUs than CUs, we've already
388      sorted all the TUs into "type unit groups", grouped by their
389      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
390      CU and its associated TU group if there is one.  */
391   htab_t quick_file_names_table {};
392
393   /* Set during partial symbol reading, to prevent queueing of full
394      symbols.  */
395   bool reading_partial_symbols = false;
396
397   /* Table mapping type DIEs to their struct type *.
398      This is NULL if not allocated yet.
399      The mapping is done via (CU/TU + DIE offset) -> type.  */
400   htab_t die_type_hash {};
401
402   /* The CUs we recently read.  */
403   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
404
405   /* Table containing line_header indexed by offset and offset_in_dwz.  */
406   htab_t line_header_hash {};
407
408   /* Table containing all filenames.  This is an optional because the
409      table is lazily constructed on first access.  */
410   gdb::optional<filename_seen_cache> filenames_cache;
411 };
412
413 static struct dwarf2_per_objfile *dwarf2_per_objfile;
414
415 /* Default names of the debugging sections.  */
416
417 /* Note that if the debugging section has been compressed, it might
418    have a name like .zdebug_info.  */
419
420 static const struct dwarf2_debug_sections dwarf2_elf_names =
421 {
422   { ".debug_info", ".zdebug_info" },
423   { ".debug_abbrev", ".zdebug_abbrev" },
424   { ".debug_line", ".zdebug_line" },
425   { ".debug_loc", ".zdebug_loc" },
426   { ".debug_loclists", ".zdebug_loclists" },
427   { ".debug_macinfo", ".zdebug_macinfo" },
428   { ".debug_macro", ".zdebug_macro" },
429   { ".debug_str", ".zdebug_str" },
430   { ".debug_line_str", ".zdebug_line_str" },
431   { ".debug_ranges", ".zdebug_ranges" },
432   { ".debug_rnglists", ".zdebug_rnglists" },
433   { ".debug_types", ".zdebug_types" },
434   { ".debug_addr", ".zdebug_addr" },
435   { ".debug_frame", ".zdebug_frame" },
436   { ".eh_frame", NULL },
437   { ".gdb_index", ".zgdb_index" },
438   23
439 };
440
441 /* List of DWO/DWP sections.  */
442
443 static const struct dwop_section_names
444 {
445   struct dwarf2_section_names abbrev_dwo;
446   struct dwarf2_section_names info_dwo;
447   struct dwarf2_section_names line_dwo;
448   struct dwarf2_section_names loc_dwo;
449   struct dwarf2_section_names loclists_dwo;
450   struct dwarf2_section_names macinfo_dwo;
451   struct dwarf2_section_names macro_dwo;
452   struct dwarf2_section_names str_dwo;
453   struct dwarf2_section_names str_offsets_dwo;
454   struct dwarf2_section_names types_dwo;
455   struct dwarf2_section_names cu_index;
456   struct dwarf2_section_names tu_index;
457 }
458 dwop_section_names =
459 {
460   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
461   { ".debug_info.dwo", ".zdebug_info.dwo" },
462   { ".debug_line.dwo", ".zdebug_line.dwo" },
463   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
464   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
465   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
466   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
467   { ".debug_str.dwo", ".zdebug_str.dwo" },
468   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
469   { ".debug_types.dwo", ".zdebug_types.dwo" },
470   { ".debug_cu_index", ".zdebug_cu_index" },
471   { ".debug_tu_index", ".zdebug_tu_index" },
472 };
473
474 /* local data types */
475
476 /* The data in a compilation unit header, after target2host
477    translation, looks like this.  */
478 struct comp_unit_head
479 {
480   unsigned int length;
481   short version;
482   unsigned char addr_size;
483   unsigned char signed_addr_p;
484   sect_offset abbrev_sect_off;
485
486   /* Size of file offsets; either 4 or 8.  */
487   unsigned int offset_size;
488
489   /* Size of the length field; either 4 or 12.  */
490   unsigned int initial_length_size;
491
492   enum dwarf_unit_type unit_type;
493
494   /* Offset to the first byte of this compilation unit header in the
495      .debug_info section, for resolving relative reference dies.  */
496   sect_offset sect_off;
497
498   /* Offset to first die in this cu from the start of the cu.
499      This will be the first byte following the compilation unit header.  */
500   cu_offset first_die_cu_offset;
501
502   /* 64-bit signature of this type unit - it is valid only for
503      UNIT_TYPE DW_UT_type.  */
504   ULONGEST signature;
505
506   /* For types, offset in the type's DIE of the type defined by this TU.  */
507   cu_offset type_cu_offset_in_tu;
508 };
509
510 /* Type used for delaying computation of method physnames.
511    See comments for compute_delayed_physnames.  */
512 struct delayed_method_info
513 {
514   /* The type to which the method is attached, i.e., its parent class.  */
515   struct type *type;
516
517   /* The index of the method in the type's function fieldlists.  */
518   int fnfield_index;
519
520   /* The index of the method in the fieldlist.  */
521   int index;
522
523   /* The name of the DIE.  */
524   const char *name;
525
526   /*  The DIE associated with this method.  */
527   struct die_info *die;
528 };
529
530 typedef struct delayed_method_info delayed_method_info;
531 DEF_VEC_O (delayed_method_info);
532
533 /* Internal state when decoding a particular compilation unit.  */
534 struct dwarf2_cu
535 {
536   /* The objfile containing this compilation unit.  */
537   struct objfile *objfile;
538
539   /* The header of the compilation unit.  */
540   struct comp_unit_head header;
541
542   /* Base address of this compilation unit.  */
543   CORE_ADDR base_address;
544
545   /* Non-zero if base_address has been set.  */
546   int base_known;
547
548   /* The language we are debugging.  */
549   enum language language;
550   const struct language_defn *language_defn;
551
552   const char *producer;
553
554   /* The generic symbol table building routines have separate lists for
555      file scope symbols and all all other scopes (local scopes).  So
556      we need to select the right one to pass to add_symbol_to_list().
557      We do it by keeping a pointer to the correct list in list_in_scope.
558
559      FIXME: The original dwarf code just treated the file scope as the
560      first local scope, and all other local scopes as nested local
561      scopes, and worked fine.  Check to see if we really need to
562      distinguish these in buildsym.c.  */
563   struct pending **list_in_scope;
564
565   /* The abbrev table for this CU.
566      Normally this points to the abbrev table in the objfile.
567      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
568   struct abbrev_table *abbrev_table;
569
570   /* Hash table holding all the loaded partial DIEs
571      with partial_die->offset.SECT_OFF as hash.  */
572   htab_t partial_dies;
573
574   /* Storage for things with the same lifetime as this read-in compilation
575      unit, including partial DIEs.  */
576   struct obstack comp_unit_obstack;
577
578   /* When multiple dwarf2_cu structures are living in memory, this field
579      chains them all together, so that they can be released efficiently.
580      We will probably also want a generation counter so that most-recently-used
581      compilation units are cached...  */
582   struct dwarf2_per_cu_data *read_in_chain;
583
584   /* Backlink to our per_cu entry.  */
585   struct dwarf2_per_cu_data *per_cu;
586
587   /* How many compilation units ago was this CU last referenced?  */
588   int last_used;
589
590   /* A hash table of DIE cu_offset for following references with
591      die_info->offset.sect_off as hash.  */
592   htab_t die_hash;
593
594   /* Full DIEs if read in.  */
595   struct die_info *dies;
596
597   /* A set of pointers to dwarf2_per_cu_data objects for compilation
598      units referenced by this one.  Only set during full symbol processing;
599      partial symbol tables do not have dependencies.  */
600   htab_t dependencies;
601
602   /* Header data from the line table, during full symbol processing.  */
603   struct line_header *line_header;
604   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
605      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
606      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
607      to the line header as long as this DIE is being processed.  See
608      process_die_scope.  */
609   die_info *line_header_die_owner;
610
611   /* A list of methods which need to have physnames computed
612      after all type information has been read.  */
613   VEC (delayed_method_info) *method_list;
614
615   /* To be copied to symtab->call_site_htab.  */
616   htab_t call_site_htab;
617
618   /* Non-NULL if this CU came from a DWO file.
619      There is an invariant here that is important to remember:
620      Except for attributes copied from the top level DIE in the "main"
621      (or "stub") file in preparation for reading the DWO file
622      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
623      Either there isn't a DWO file (in which case this is NULL and the point
624      is moot), or there is and either we're not going to read it (in which
625      case this is NULL) or there is and we are reading it (in which case this
626      is non-NULL).  */
627   struct dwo_unit *dwo_unit;
628
629   /* The DW_AT_addr_base attribute if present, zero otherwise
630      (zero is a valid value though).
631      Note this value comes from the Fission stub CU/TU's DIE.  */
632   ULONGEST addr_base;
633
634   /* The DW_AT_ranges_base attribute if present, zero otherwise
635      (zero is a valid value though).
636      Note this value comes from the Fission stub CU/TU's DIE.
637      Also note that the value is zero in the non-DWO case so this value can
638      be used without needing to know whether DWO files are in use or not.
639      N.B. This does not apply to DW_AT_ranges appearing in
640      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
641      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
642      DW_AT_ranges_base *would* have to be applied, and we'd have to care
643      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
644   ULONGEST ranges_base;
645
646   /* Mark used when releasing cached dies.  */
647   unsigned int mark : 1;
648
649   /* This CU references .debug_loc.  See the symtab->locations_valid field.
650      This test is imperfect as there may exist optimized debug code not using
651      any location list and still facing inlining issues if handled as
652      unoptimized code.  For a future better test see GCC PR other/32998.  */
653   unsigned int has_loclist : 1;
654
655   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
656      if all the producer_is_* fields are valid.  This information is cached
657      because profiling CU expansion showed excessive time spent in
658      producer_is_gxx_lt_4_6.  */
659   unsigned int checked_producer : 1;
660   unsigned int producer_is_gxx_lt_4_6 : 1;
661   unsigned int producer_is_gcc_lt_4_3 : 1;
662   unsigned int producer_is_icc_lt_14 : 1;
663
664   /* When set, the file that we're processing is known to have
665      debugging info for C++ namespaces.  GCC 3.3.x did not produce
666      this information, but later versions do.  */
667
668   unsigned int processing_has_namespace_info : 1;
669 };
670
671 /* Persistent data held for a compilation unit, even when not
672    processing it.  We put a pointer to this structure in the
673    read_symtab_private field of the psymtab.  */
674
675 struct dwarf2_per_cu_data
676 {
677   /* The start offset and length of this compilation unit.
678      NOTE: Unlike comp_unit_head.length, this length includes
679      initial_length_size.
680      If the DIE refers to a DWO file, this is always of the original die,
681      not the DWO file.  */
682   sect_offset sect_off;
683   unsigned int length;
684
685   /* DWARF standard version this data has been read from (such as 4 or 5).  */
686   short dwarf_version;
687
688   /* Flag indicating this compilation unit will be read in before
689      any of the current compilation units are processed.  */
690   unsigned int queued : 1;
691
692   /* This flag will be set when reading partial DIEs if we need to load
693      absolutely all DIEs for this compilation unit, instead of just the ones
694      we think are interesting.  It gets set if we look for a DIE in the
695      hash table and don't find it.  */
696   unsigned int load_all_dies : 1;
697
698   /* Non-zero if this CU is from .debug_types.
699      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
700      this is non-zero.  */
701   unsigned int is_debug_types : 1;
702
703   /* Non-zero if this CU is from the .dwz file.  */
704   unsigned int is_dwz : 1;
705
706   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
707      This flag is only valid if is_debug_types is true.
708      We can't read a CU directly from a DWO file: There are required
709      attributes in the stub.  */
710   unsigned int reading_dwo_directly : 1;
711
712   /* Non-zero if the TU has been read.
713      This is used to assist the "Stay in DWO Optimization" for Fission:
714      When reading a DWO, it's faster to read TUs from the DWO instead of
715      fetching them from random other DWOs (due to comdat folding).
716      If the TU has already been read, the optimization is unnecessary
717      (and unwise - we don't want to change where gdb thinks the TU lives
718      "midflight").
719      This flag is only valid if is_debug_types is true.  */
720   unsigned int tu_read : 1;
721
722   /* The section this CU/TU lives in.
723      If the DIE refers to a DWO file, this is always the original die,
724      not the DWO file.  */
725   struct dwarf2_section_info *section;
726
727   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
728      of the CU cache it gets reset to NULL again.  This is left as NULL for
729      dummy CUs (a CU header, but nothing else).  */
730   struct dwarf2_cu *cu;
731
732   /* The corresponding objfile.
733      Normally we can get the objfile from dwarf2_per_objfile.
734      However we can enter this file with just a "per_cu" handle.  */
735   struct objfile *objfile;
736
737   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
738      is active.  Otherwise, the 'psymtab' field is active.  */
739   union
740   {
741     /* The partial symbol table associated with this compilation unit,
742        or NULL for unread partial units.  */
743     struct partial_symtab *psymtab;
744
745     /* Data needed by the "quick" functions.  */
746     struct dwarf2_per_cu_quick_data *quick;
747   } v;
748
749   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
750      while reading psymtabs, used to compute the psymtab dependencies,
751      and then cleared.  Then it is filled in again while reading full
752      symbols, and only deleted when the objfile is destroyed.
753
754      This is also used to work around a difference between the way gold
755      generates .gdb_index version <=7 and the way gdb does.  Arguably this
756      is a gold bug.  For symbols coming from TUs, gold records in the index
757      the CU that includes the TU instead of the TU itself.  This breaks
758      dw2_lookup_symbol: It assumes that if the index says symbol X lives
759      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
760      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
761      we need to look in TU Z to find X.  Fortunately, this is akin to
762      DW_TAG_imported_unit, so we just use the same mechanism: For
763      .gdb_index version <=7 this also records the TUs that the CU referred
764      to.  Concurrently with this change gdb was modified to emit version 8
765      indices so we only pay a price for gold generated indices.
766      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
767   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
768 };
769
770 /* Entry in the signatured_types hash table.  */
771
772 struct signatured_type
773 {
774   /* The "per_cu" object of this type.
775      This struct is used iff per_cu.is_debug_types.
776      N.B.: This is the first member so that it's easy to convert pointers
777      between them.  */
778   struct dwarf2_per_cu_data per_cu;
779
780   /* The type's signature.  */
781   ULONGEST signature;
782
783   /* Offset in the TU of the type's DIE, as read from the TU header.
784      If this TU is a DWO stub and the definition lives in a DWO file
785      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
786   cu_offset type_offset_in_tu;
787
788   /* Offset in the section of the type's DIE.
789      If the definition lives in a DWO file, this is the offset in the
790      .debug_types.dwo section.
791      The value is zero until the actual value is known.
792      Zero is otherwise not a valid section offset.  */
793   sect_offset type_offset_in_section;
794
795   /* Type units are grouped by their DW_AT_stmt_list entry so that they
796      can share them.  This points to the containing symtab.  */
797   struct type_unit_group *type_unit_group;
798
799   /* The type.
800      The first time we encounter this type we fully read it in and install it
801      in the symbol tables.  Subsequent times we only need the type.  */
802   struct type *type;
803
804   /* Containing DWO unit.
805      This field is valid iff per_cu.reading_dwo_directly.  */
806   struct dwo_unit *dwo_unit;
807 };
808
809 typedef struct signatured_type *sig_type_ptr;
810 DEF_VEC_P (sig_type_ptr);
811
812 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
813    This includes type_unit_group and quick_file_names.  */
814
815 struct stmt_list_hash
816 {
817   /* The DWO unit this table is from or NULL if there is none.  */
818   struct dwo_unit *dwo_unit;
819
820   /* Offset in .debug_line or .debug_line.dwo.  */
821   sect_offset line_sect_off;
822 };
823
824 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
825    an object of this type.  */
826
827 struct type_unit_group
828 {
829   /* dwarf2read.c's main "handle" on a TU symtab.
830      To simplify things we create an artificial CU that "includes" all the
831      type units using this stmt_list so that the rest of the code still has
832      a "per_cu" handle on the symtab.
833      This PER_CU is recognized by having no section.  */
834 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
835   struct dwarf2_per_cu_data per_cu;
836
837   /* The TUs that share this DW_AT_stmt_list entry.
838      This is added to while parsing type units to build partial symtabs,
839      and is deleted afterwards and not used again.  */
840   VEC (sig_type_ptr) *tus;
841
842   /* The compunit symtab.
843      Type units in a group needn't all be defined in the same source file,
844      so we create an essentially anonymous symtab as the compunit symtab.  */
845   struct compunit_symtab *compunit_symtab;
846
847   /* The data used to construct the hash key.  */
848   struct stmt_list_hash hash;
849
850   /* The number of symtabs from the line header.
851      The value here must match line_header.num_file_names.  */
852   unsigned int num_symtabs;
853
854   /* The symbol tables for this TU (obtained from the files listed in
855      DW_AT_stmt_list).
856      WARNING: The order of entries here must match the order of entries
857      in the line header.  After the first TU using this type_unit_group, the
858      line header for the subsequent TUs is recreated from this.  This is done
859      because we need to use the same symtabs for each TU using the same
860      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
861      there's no guarantee the line header doesn't have duplicate entries.  */
862   struct symtab **symtabs;
863 };
864
865 /* These sections are what may appear in a (real or virtual) DWO file.  */
866
867 struct dwo_sections
868 {
869   struct dwarf2_section_info abbrev;
870   struct dwarf2_section_info line;
871   struct dwarf2_section_info loc;
872   struct dwarf2_section_info loclists;
873   struct dwarf2_section_info macinfo;
874   struct dwarf2_section_info macro;
875   struct dwarf2_section_info str;
876   struct dwarf2_section_info str_offsets;
877   /* In the case of a virtual DWO file, these two are unused.  */
878   struct dwarf2_section_info info;
879   VEC (dwarf2_section_info_def) *types;
880 };
881
882 /* CUs/TUs in DWP/DWO files.  */
883
884 struct dwo_unit
885 {
886   /* Backlink to the containing struct dwo_file.  */
887   struct dwo_file *dwo_file;
888
889   /* The "id" that distinguishes this CU/TU.
890      .debug_info calls this "dwo_id", .debug_types calls this "signature".
891      Since signatures came first, we stick with it for consistency.  */
892   ULONGEST signature;
893
894   /* The section this CU/TU lives in, in the DWO file.  */
895   struct dwarf2_section_info *section;
896
897   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
898   sect_offset sect_off;
899   unsigned int length;
900
901   /* For types, offset in the type's DIE of the type defined by this TU.  */
902   cu_offset type_offset_in_tu;
903 };
904
905 /* include/dwarf2.h defines the DWP section codes.
906    It defines a max value but it doesn't define a min value, which we
907    use for error checking, so provide one.  */
908
909 enum dwp_v2_section_ids
910 {
911   DW_SECT_MIN = 1
912 };
913
914 /* Data for one DWO file.
915
916    This includes virtual DWO files (a virtual DWO file is a DWO file as it
917    appears in a DWP file).  DWP files don't really have DWO files per se -
918    comdat folding of types "loses" the DWO file they came from, and from
919    a high level view DWP files appear to contain a mass of random types.
920    However, to maintain consistency with the non-DWP case we pretend DWP
921    files contain virtual DWO files, and we assign each TU with one virtual
922    DWO file (generally based on the line and abbrev section offsets -
923    a heuristic that seems to work in practice).  */
924
925 struct dwo_file
926 {
927   /* The DW_AT_GNU_dwo_name attribute.
928      For virtual DWO files the name is constructed from the section offsets
929      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
930      from related CU+TUs.  */
931   const char *dwo_name;
932
933   /* The DW_AT_comp_dir attribute.  */
934   const char *comp_dir;
935
936   /* The bfd, when the file is open.  Otherwise this is NULL.
937      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
938   bfd *dbfd;
939
940   /* The sections that make up this DWO file.
941      Remember that for virtual DWO files in DWP V2, these are virtual
942      sections (for lack of a better name).  */
943   struct dwo_sections sections;
944
945   /* The CUs in the file.
946      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
947      an extension to handle LLVM's Link Time Optimization output (where
948      multiple source files may be compiled into a single object/dwo pair). */
949   htab_t cus;
950
951   /* Table of TUs in the file.
952      Each element is a struct dwo_unit.  */
953   htab_t tus;
954 };
955
956 /* These sections are what may appear in a DWP file.  */
957
958 struct dwp_sections
959 {
960   /* These are used by both DWP version 1 and 2.  */
961   struct dwarf2_section_info str;
962   struct dwarf2_section_info cu_index;
963   struct dwarf2_section_info tu_index;
964
965   /* These are only used by DWP version 2 files.
966      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
967      sections are referenced by section number, and are not recorded here.
968      In DWP version 2 there is at most one copy of all these sections, each
969      section being (effectively) comprised of the concatenation of all of the
970      individual sections that exist in the version 1 format.
971      To keep the code simple we treat each of these concatenated pieces as a
972      section itself (a virtual section?).  */
973   struct dwarf2_section_info abbrev;
974   struct dwarf2_section_info info;
975   struct dwarf2_section_info line;
976   struct dwarf2_section_info loc;
977   struct dwarf2_section_info macinfo;
978   struct dwarf2_section_info macro;
979   struct dwarf2_section_info str_offsets;
980   struct dwarf2_section_info types;
981 };
982
983 /* These sections are what may appear in a virtual DWO file in DWP version 1.
984    A virtual DWO file is a DWO file as it appears in a DWP file.  */
985
986 struct virtual_v1_dwo_sections
987 {
988   struct dwarf2_section_info abbrev;
989   struct dwarf2_section_info line;
990   struct dwarf2_section_info loc;
991   struct dwarf2_section_info macinfo;
992   struct dwarf2_section_info macro;
993   struct dwarf2_section_info str_offsets;
994   /* Each DWP hash table entry records one CU or one TU.
995      That is recorded here, and copied to dwo_unit.section.  */
996   struct dwarf2_section_info info_or_types;
997 };
998
999 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1000    In version 2, the sections of the DWO files are concatenated together
1001    and stored in one section of that name.  Thus each ELF section contains
1002    several "virtual" sections.  */
1003
1004 struct virtual_v2_dwo_sections
1005 {
1006   bfd_size_type abbrev_offset;
1007   bfd_size_type abbrev_size;
1008
1009   bfd_size_type line_offset;
1010   bfd_size_type line_size;
1011
1012   bfd_size_type loc_offset;
1013   bfd_size_type loc_size;
1014
1015   bfd_size_type macinfo_offset;
1016   bfd_size_type macinfo_size;
1017
1018   bfd_size_type macro_offset;
1019   bfd_size_type macro_size;
1020
1021   bfd_size_type str_offsets_offset;
1022   bfd_size_type str_offsets_size;
1023
1024   /* Each DWP hash table entry records one CU or one TU.
1025      That is recorded here, and copied to dwo_unit.section.  */
1026   bfd_size_type info_or_types_offset;
1027   bfd_size_type info_or_types_size;
1028 };
1029
1030 /* Contents of DWP hash tables.  */
1031
1032 struct dwp_hash_table
1033 {
1034   uint32_t version, nr_columns;
1035   uint32_t nr_units, nr_slots;
1036   const gdb_byte *hash_table, *unit_table;
1037   union
1038   {
1039     struct
1040     {
1041       const gdb_byte *indices;
1042     } v1;
1043     struct
1044     {
1045       /* This is indexed by column number and gives the id of the section
1046          in that column.  */
1047 #define MAX_NR_V2_DWO_SECTIONS \
1048   (1 /* .debug_info or .debug_types */ \
1049    + 1 /* .debug_abbrev */ \
1050    + 1 /* .debug_line */ \
1051    + 1 /* .debug_loc */ \
1052    + 1 /* .debug_str_offsets */ \
1053    + 1 /* .debug_macro or .debug_macinfo */)
1054       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1055       const gdb_byte *offsets;
1056       const gdb_byte *sizes;
1057     } v2;
1058   } section_pool;
1059 };
1060
1061 /* Data for one DWP file.  */
1062
1063 struct dwp_file
1064 {
1065   /* Name of the file.  */
1066   const char *name;
1067
1068   /* File format version.  */
1069   int version;
1070
1071   /* The bfd.  */
1072   bfd *dbfd;
1073
1074   /* Section info for this file.  */
1075   struct dwp_sections sections;
1076
1077   /* Table of CUs in the file.  */
1078   const struct dwp_hash_table *cus;
1079
1080   /* Table of TUs in the file.  */
1081   const struct dwp_hash_table *tus;
1082
1083   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1084   htab_t loaded_cus;
1085   htab_t loaded_tus;
1086
1087   /* Table to map ELF section numbers to their sections.
1088      This is only needed for the DWP V1 file format.  */
1089   unsigned int num_sections;
1090   asection **elf_sections;
1091 };
1092
1093 /* This represents a '.dwz' file.  */
1094
1095 struct dwz_file
1096 {
1097   /* A dwz file can only contain a few sections.  */
1098   struct dwarf2_section_info abbrev;
1099   struct dwarf2_section_info info;
1100   struct dwarf2_section_info str;
1101   struct dwarf2_section_info line;
1102   struct dwarf2_section_info macro;
1103   struct dwarf2_section_info gdb_index;
1104
1105   /* The dwz's BFD.  */
1106   bfd *dwz_bfd;
1107 };
1108
1109 /* Struct used to pass misc. parameters to read_die_and_children, et
1110    al.  which are used for both .debug_info and .debug_types dies.
1111    All parameters here are unchanging for the life of the call.  This
1112    struct exists to abstract away the constant parameters of die reading.  */
1113
1114 struct die_reader_specs
1115 {
1116   /* The bfd of die_section.  */
1117   bfd* abfd;
1118
1119   /* The CU of the DIE we are parsing.  */
1120   struct dwarf2_cu *cu;
1121
1122   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1123   struct dwo_file *dwo_file;
1124
1125   /* The section the die comes from.
1126      This is either .debug_info or .debug_types, or the .dwo variants.  */
1127   struct dwarf2_section_info *die_section;
1128
1129   /* die_section->buffer.  */
1130   const gdb_byte *buffer;
1131
1132   /* The end of the buffer.  */
1133   const gdb_byte *buffer_end;
1134
1135   /* The value of the DW_AT_comp_dir attribute.  */
1136   const char *comp_dir;
1137 };
1138
1139 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1140 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1141                                       const gdb_byte *info_ptr,
1142                                       struct die_info *comp_unit_die,
1143                                       int has_children,
1144                                       void *data);
1145
1146 /* A 1-based directory index.  This is a strong typedef to prevent
1147    accidentally using a directory index as a 0-based index into an
1148    array/vector.  */
1149 enum class dir_index : unsigned int {};
1150
1151 /* Likewise, a 1-based file name index.  */
1152 enum class file_name_index : unsigned int {};
1153
1154 struct file_entry
1155 {
1156   file_entry () = default;
1157
1158   file_entry (const char *name_, dir_index d_index_,
1159               unsigned int mod_time_, unsigned int length_)
1160     : name (name_),
1161       d_index (d_index_),
1162       mod_time (mod_time_),
1163       length (length_)
1164   {}
1165
1166   /* Return the include directory at D_INDEX stored in LH.  Returns
1167      NULL if D_INDEX is out of bounds.  */
1168   const char *include_dir (const line_header *lh) const;
1169
1170   /* The file name.  Note this is an observing pointer.  The memory is
1171      owned by debug_line_buffer.  */
1172   const char *name {};
1173
1174   /* The directory index (1-based).  */
1175   dir_index d_index {};
1176
1177   unsigned int mod_time {};
1178
1179   unsigned int length {};
1180
1181   /* True if referenced by the Line Number Program.  */
1182   bool included_p {};
1183
1184   /* The associated symbol table, if any.  */
1185   struct symtab *symtab {};
1186 };
1187
1188 /* The line number information for a compilation unit (found in the
1189    .debug_line section) begins with a "statement program header",
1190    which contains the following information.  */
1191 struct line_header
1192 {
1193   line_header ()
1194     : offset_in_dwz {}
1195   {}
1196
1197   /* Add an entry to the include directory table.  */
1198   void add_include_dir (const char *include_dir);
1199
1200   /* Add an entry to the file name table.  */
1201   void add_file_name (const char *name, dir_index d_index,
1202                       unsigned int mod_time, unsigned int length);
1203
1204   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1205      is out of bounds.  */
1206   const char *include_dir_at (dir_index index) const
1207   {
1208     /* Convert directory index number (1-based) to vector index
1209        (0-based).  */
1210     size_t vec_index = to_underlying (index) - 1;
1211
1212     if (vec_index >= include_dirs.size ())
1213       return NULL;
1214     return include_dirs[vec_index];
1215   }
1216
1217   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1218      is out of bounds.  */
1219   file_entry *file_name_at (file_name_index index)
1220   {
1221     /* Convert file name index number (1-based) to vector index
1222        (0-based).  */
1223     size_t vec_index = to_underlying (index) - 1;
1224
1225     if (vec_index >= file_names.size ())
1226       return NULL;
1227     return &file_names[vec_index];
1228   }
1229
1230   /* Const version of the above.  */
1231   const file_entry *file_name_at (unsigned int index) const
1232   {
1233     if (index >= file_names.size ())
1234       return NULL;
1235     return &file_names[index];
1236   }
1237
1238   /* Offset of line number information in .debug_line section.  */
1239   sect_offset sect_off {};
1240
1241   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1242   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1243
1244   unsigned int total_length {};
1245   unsigned short version {};
1246   unsigned int header_length {};
1247   unsigned char minimum_instruction_length {};
1248   unsigned char maximum_ops_per_instruction {};
1249   unsigned char default_is_stmt {};
1250   int line_base {};
1251   unsigned char line_range {};
1252   unsigned char opcode_base {};
1253
1254   /* standard_opcode_lengths[i] is the number of operands for the
1255      standard opcode whose value is i.  This means that
1256      standard_opcode_lengths[0] is unused, and the last meaningful
1257      element is standard_opcode_lengths[opcode_base - 1].  */
1258   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1259
1260   /* The include_directories table.  Note these are observing
1261      pointers.  The memory is owned by debug_line_buffer.  */
1262   std::vector<const char *> include_dirs;
1263
1264   /* The file_names table.  */
1265   std::vector<file_entry> file_names;
1266
1267   /* The start and end of the statement program following this
1268      header.  These point into dwarf2_per_objfile->line_buffer.  */
1269   const gdb_byte *statement_program_start {}, *statement_program_end {};
1270 };
1271
1272 typedef std::unique_ptr<line_header> line_header_up;
1273
1274 const char *
1275 file_entry::include_dir (const line_header *lh) const
1276 {
1277   return lh->include_dir_at (d_index);
1278 }
1279
1280 /* When we construct a partial symbol table entry we only
1281    need this much information.  */
1282 struct partial_die_info
1283   {
1284     /* Offset of this DIE.  */
1285     sect_offset sect_off;
1286
1287     /* DWARF-2 tag for this DIE.  */
1288     ENUM_BITFIELD(dwarf_tag) tag : 16;
1289
1290     /* Assorted flags describing the data found in this DIE.  */
1291     unsigned int has_children : 1;
1292     unsigned int is_external : 1;
1293     unsigned int is_declaration : 1;
1294     unsigned int has_type : 1;
1295     unsigned int has_specification : 1;
1296     unsigned int has_pc_info : 1;
1297     unsigned int may_be_inlined : 1;
1298
1299     /* This DIE has been marked DW_AT_main_subprogram.  */
1300     unsigned int main_subprogram : 1;
1301
1302     /* Flag set if the SCOPE field of this structure has been
1303        computed.  */
1304     unsigned int scope_set : 1;
1305
1306     /* Flag set if the DIE has a byte_size attribute.  */
1307     unsigned int has_byte_size : 1;
1308
1309     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1310     unsigned int has_const_value : 1;
1311
1312     /* Flag set if any of the DIE's children are template arguments.  */
1313     unsigned int has_template_arguments : 1;
1314
1315     /* Flag set if fixup_partial_die has been called on this die.  */
1316     unsigned int fixup_called : 1;
1317
1318     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1319     unsigned int is_dwz : 1;
1320
1321     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1322     unsigned int spec_is_dwz : 1;
1323
1324     /* The name of this DIE.  Normally the value of DW_AT_name, but
1325        sometimes a default name for unnamed DIEs.  */
1326     const char *name;
1327
1328     /* The linkage name, if present.  */
1329     const char *linkage_name;
1330
1331     /* The scope to prepend to our children.  This is generally
1332        allocated on the comp_unit_obstack, so will disappear
1333        when this compilation unit leaves the cache.  */
1334     const char *scope;
1335
1336     /* Some data associated with the partial DIE.  The tag determines
1337        which field is live.  */
1338     union
1339     {
1340       /* The location description associated with this DIE, if any.  */
1341       struct dwarf_block *locdesc;
1342       /* The offset of an import, for DW_TAG_imported_unit.  */
1343       sect_offset sect_off;
1344     } d;
1345
1346     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1347     CORE_ADDR lowpc;
1348     CORE_ADDR highpc;
1349
1350     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1351        DW_AT_sibling, if any.  */
1352     /* NOTE: This member isn't strictly necessary, read_partial_die could
1353        return DW_AT_sibling values to its caller load_partial_dies.  */
1354     const gdb_byte *sibling;
1355
1356     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1357        DW_AT_specification (or DW_AT_abstract_origin or
1358        DW_AT_extension).  */
1359     sect_offset spec_offset;
1360
1361     /* Pointers to this DIE's parent, first child, and next sibling,
1362        if any.  */
1363     struct partial_die_info *die_parent, *die_child, *die_sibling;
1364   };
1365
1366 /* This data structure holds the information of an abbrev.  */
1367 struct abbrev_info
1368   {
1369     unsigned int number;        /* number identifying abbrev */
1370     enum dwarf_tag tag;         /* dwarf tag */
1371     unsigned short has_children;                /* boolean */
1372     unsigned short num_attrs;   /* number of attributes */
1373     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1374     struct abbrev_info *next;   /* next in chain */
1375   };
1376
1377 struct attr_abbrev
1378   {
1379     ENUM_BITFIELD(dwarf_attribute) name : 16;
1380     ENUM_BITFIELD(dwarf_form) form : 16;
1381
1382     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1383     LONGEST implicit_const;
1384   };
1385
1386 /* Size of abbrev_table.abbrev_hash_table.  */
1387 #define ABBREV_HASH_SIZE 121
1388
1389 /* Top level data structure to contain an abbreviation table.  */
1390
1391 struct abbrev_table
1392 {
1393   /* Where the abbrev table came from.
1394      This is used as a sanity check when the table is used.  */
1395   sect_offset sect_off;
1396
1397   /* Storage for the abbrev table.  */
1398   struct obstack abbrev_obstack;
1399
1400   /* Hash table of abbrevs.
1401      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1402      It could be statically allocated, but the previous code didn't so we
1403      don't either.  */
1404   struct abbrev_info **abbrevs;
1405 };
1406
1407 /* Attributes have a name and a value.  */
1408 struct attribute
1409   {
1410     ENUM_BITFIELD(dwarf_attribute) name : 16;
1411     ENUM_BITFIELD(dwarf_form) form : 15;
1412
1413     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1414        field should be in u.str (existing only for DW_STRING) but it is kept
1415        here for better struct attribute alignment.  */
1416     unsigned int string_is_canonical : 1;
1417
1418     union
1419       {
1420         const char *str;
1421         struct dwarf_block *blk;
1422         ULONGEST unsnd;
1423         LONGEST snd;
1424         CORE_ADDR addr;
1425         ULONGEST signature;
1426       }
1427     u;
1428   };
1429
1430 /* This data structure holds a complete die structure.  */
1431 struct die_info
1432   {
1433     /* DWARF-2 tag for this DIE.  */
1434     ENUM_BITFIELD(dwarf_tag) tag : 16;
1435
1436     /* Number of attributes */
1437     unsigned char num_attrs;
1438
1439     /* True if we're presently building the full type name for the
1440        type derived from this DIE.  */
1441     unsigned char building_fullname : 1;
1442
1443     /* True if this die is in process.  PR 16581.  */
1444     unsigned char in_process : 1;
1445
1446     /* Abbrev number */
1447     unsigned int abbrev;
1448
1449     /* Offset in .debug_info or .debug_types section.  */
1450     sect_offset sect_off;
1451
1452     /* The dies in a compilation unit form an n-ary tree.  PARENT
1453        points to this die's parent; CHILD points to the first child of
1454        this node; and all the children of a given node are chained
1455        together via their SIBLING fields.  */
1456     struct die_info *child;     /* Its first child, if any.  */
1457     struct die_info *sibling;   /* Its next sibling, if any.  */
1458     struct die_info *parent;    /* Its parent, if any.  */
1459
1460     /* An array of attributes, with NUM_ATTRS elements.  There may be
1461        zero, but it's not common and zero-sized arrays are not
1462        sufficiently portable C.  */
1463     struct attribute attrs[1];
1464   };
1465
1466 /* Get at parts of an attribute structure.  */
1467
1468 #define DW_STRING(attr)    ((attr)->u.str)
1469 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1470 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1471 #define DW_BLOCK(attr)     ((attr)->u.blk)
1472 #define DW_SND(attr)       ((attr)->u.snd)
1473 #define DW_ADDR(attr)      ((attr)->u.addr)
1474 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1475
1476 /* Blocks are a bunch of untyped bytes.  */
1477 struct dwarf_block
1478   {
1479     size_t size;
1480
1481     /* Valid only if SIZE is not zero.  */
1482     const gdb_byte *data;
1483   };
1484
1485 #ifndef ATTR_ALLOC_CHUNK
1486 #define ATTR_ALLOC_CHUNK 4
1487 #endif
1488
1489 /* Allocate fields for structs, unions and enums in this size.  */
1490 #ifndef DW_FIELD_ALLOC_CHUNK
1491 #define DW_FIELD_ALLOC_CHUNK 4
1492 #endif
1493
1494 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1495    but this would require a corresponding change in unpack_field_as_long
1496    and friends.  */
1497 static int bits_per_byte = 8;
1498
1499 struct nextfield
1500 {
1501   struct nextfield *next;
1502   int accessibility;
1503   int virtuality;
1504   struct field field;
1505 };
1506
1507 struct nextfnfield
1508 {
1509   struct nextfnfield *next;
1510   struct fn_field fnfield;
1511 };
1512
1513 struct fnfieldlist
1514 {
1515   const char *name;
1516   int length;
1517   struct nextfnfield *head;
1518 };
1519
1520 struct typedef_field_list
1521 {
1522   struct typedef_field field;
1523   struct typedef_field_list *next;
1524 };
1525
1526 /* The routines that read and process dies for a C struct or C++ class
1527    pass lists of data member fields and lists of member function fields
1528    in an instance of a field_info structure, as defined below.  */
1529 struct field_info
1530   {
1531     /* List of data member and baseclasses fields.  */
1532     struct nextfield *fields, *baseclasses;
1533
1534     /* Number of fields (including baseclasses).  */
1535     int nfields;
1536
1537     /* Number of baseclasses.  */
1538     int nbaseclasses;
1539
1540     /* Set if the accesibility of one of the fields is not public.  */
1541     int non_public_fields;
1542
1543     /* Member function fieldlist array, contains name of possibly overloaded
1544        member function, number of overloaded member functions and a pointer
1545        to the head of the member function field chain.  */
1546     struct fnfieldlist *fnfieldlists;
1547
1548     /* Number of entries in the fnfieldlists array.  */
1549     int nfnfields;
1550
1551     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1552        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1553     struct typedef_field_list *typedef_field_list;
1554     unsigned typedef_field_list_count;
1555   };
1556
1557 /* One item on the queue of compilation units to read in full symbols
1558    for.  */
1559 struct dwarf2_queue_item
1560 {
1561   struct dwarf2_per_cu_data *per_cu;
1562   enum language pretend_language;
1563   struct dwarf2_queue_item *next;
1564 };
1565
1566 /* The current queue.  */
1567 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1568
1569 /* Loaded secondary compilation units are kept in memory until they
1570    have not been referenced for the processing of this many
1571    compilation units.  Set this to zero to disable caching.  Cache
1572    sizes of up to at least twenty will improve startup time for
1573    typical inter-CU-reference binaries, at an obvious memory cost.  */
1574 static int dwarf_max_cache_age = 5;
1575 static void
1576 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1577                           struct cmd_list_element *c, const char *value)
1578 {
1579   fprintf_filtered (file, _("The upper bound on the age of cached "
1580                             "DWARF compilation units is %s.\n"),
1581                     value);
1582 }
1583 \f
1584 /* local function prototypes */
1585
1586 static const char *get_section_name (const struct dwarf2_section_info *);
1587
1588 static const char *get_section_file_name (const struct dwarf2_section_info *);
1589
1590 static void dwarf2_find_base_address (struct die_info *die,
1591                                       struct dwarf2_cu *cu);
1592
1593 static struct partial_symtab *create_partial_symtab
1594   (struct dwarf2_per_cu_data *per_cu, const char *name);
1595
1596 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1597                                         const gdb_byte *info_ptr,
1598                                         struct die_info *type_unit_die,
1599                                         int has_children, void *data);
1600
1601 static void dwarf2_build_psymtabs_hard (struct objfile *);
1602
1603 static void scan_partial_symbols (struct partial_die_info *,
1604                                   CORE_ADDR *, CORE_ADDR *,
1605                                   int, struct dwarf2_cu *);
1606
1607 static void add_partial_symbol (struct partial_die_info *,
1608                                 struct dwarf2_cu *);
1609
1610 static void add_partial_namespace (struct partial_die_info *pdi,
1611                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1612                                    int set_addrmap, struct dwarf2_cu *cu);
1613
1614 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1615                                 CORE_ADDR *highpc, int set_addrmap,
1616                                 struct dwarf2_cu *cu);
1617
1618 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1619                                      struct dwarf2_cu *cu);
1620
1621 static void add_partial_subprogram (struct partial_die_info *pdi,
1622                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1623                                     int need_pc, struct dwarf2_cu *cu);
1624
1625 static void dwarf2_read_symtab (struct partial_symtab *,
1626                                 struct objfile *);
1627
1628 static void psymtab_to_symtab_1 (struct partial_symtab *);
1629
1630 static struct abbrev_info *abbrev_table_lookup_abbrev
1631   (const struct abbrev_table *, unsigned int);
1632
1633 static struct abbrev_table *abbrev_table_read_table
1634   (struct dwarf2_section_info *, sect_offset);
1635
1636 static void abbrev_table_free (struct abbrev_table *);
1637
1638 static void abbrev_table_free_cleanup (void *);
1639
1640 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1641                                  struct dwarf2_section_info *);
1642
1643 static void dwarf2_free_abbrev_table (void *);
1644
1645 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1646
1647 static struct partial_die_info *load_partial_dies
1648   (const struct die_reader_specs *, const gdb_byte *, int);
1649
1650 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1651                                          struct partial_die_info *,
1652                                          struct abbrev_info *,
1653                                          unsigned int,
1654                                          const gdb_byte *);
1655
1656 static struct partial_die_info *find_partial_die (sect_offset, int,
1657                                                   struct dwarf2_cu *);
1658
1659 static void fixup_partial_die (struct partial_die_info *,
1660                                struct dwarf2_cu *);
1661
1662 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1663                                        struct attribute *, struct attr_abbrev *,
1664                                        const gdb_byte *);
1665
1666 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1667
1668 static int read_1_signed_byte (bfd *, const gdb_byte *);
1669
1670 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1671
1672 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1673
1674 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1675
1676 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1677                                unsigned int *);
1678
1679 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1680
1681 static LONGEST read_checked_initial_length_and_offset
1682   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1683    unsigned int *, unsigned int *);
1684
1685 static LONGEST read_offset (bfd *, const gdb_byte *,
1686                             const struct comp_unit_head *,
1687                             unsigned int *);
1688
1689 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1690
1691 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1692                                        sect_offset);
1693
1694 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1695
1696 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1697
1698 static const char *read_indirect_string (bfd *, const gdb_byte *,
1699                                          const struct comp_unit_head *,
1700                                          unsigned int *);
1701
1702 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1703                                               const struct comp_unit_head *,
1704                                               unsigned int *);
1705
1706 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1707
1708 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1709
1710 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1711                                               const gdb_byte *,
1712                                               unsigned int *);
1713
1714 static const char *read_str_index (const struct die_reader_specs *reader,
1715                                    ULONGEST str_index);
1716
1717 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1718
1719 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1720                                       struct dwarf2_cu *);
1721
1722 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1723                                                 unsigned int);
1724
1725 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1726                                        struct dwarf2_cu *cu);
1727
1728 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1729                                struct dwarf2_cu *cu);
1730
1731 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1732
1733 static struct die_info *die_specification (struct die_info *die,
1734                                            struct dwarf2_cu **);
1735
1736 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1737                                                 struct dwarf2_cu *cu);
1738
1739 static void dwarf_decode_lines (struct line_header *, const char *,
1740                                 struct dwarf2_cu *, struct partial_symtab *,
1741                                 CORE_ADDR, int decode_mapping);
1742
1743 static void dwarf2_start_subfile (const char *, const char *);
1744
1745 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1746                                                     const char *, const char *,
1747                                                     CORE_ADDR);
1748
1749 static struct symbol *new_symbol (struct die_info *, struct type *,
1750                                   struct dwarf2_cu *);
1751
1752 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1753                                        struct dwarf2_cu *, struct symbol *);
1754
1755 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1756                                 struct dwarf2_cu *);
1757
1758 static void dwarf2_const_value_attr (const struct attribute *attr,
1759                                      struct type *type,
1760                                      const char *name,
1761                                      struct obstack *obstack,
1762                                      struct dwarf2_cu *cu, LONGEST *value,
1763                                      const gdb_byte **bytes,
1764                                      struct dwarf2_locexpr_baton **baton);
1765
1766 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1767
1768 static int need_gnat_info (struct dwarf2_cu *);
1769
1770 static struct type *die_descriptive_type (struct die_info *,
1771                                           struct dwarf2_cu *);
1772
1773 static void set_descriptive_type (struct type *, struct die_info *,
1774                                   struct dwarf2_cu *);
1775
1776 static struct type *die_containing_type (struct die_info *,
1777                                          struct dwarf2_cu *);
1778
1779 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1780                                      struct dwarf2_cu *);
1781
1782 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1783
1784 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1785
1786 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1787
1788 static char *typename_concat (struct obstack *obs, const char *prefix,
1789                               const char *suffix, int physname,
1790                               struct dwarf2_cu *cu);
1791
1792 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1793
1794 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1795
1796 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1797
1798 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1799
1800 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1801
1802 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1803                                struct dwarf2_cu *, struct partial_symtab *);
1804
1805 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1806    values.  Keep the items ordered with increasing constraints compliance.  */
1807 enum pc_bounds_kind
1808 {
1809   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1810   PC_BOUNDS_NOT_PRESENT,
1811
1812   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1813      were present but they do not form a valid range of PC addresses.  */
1814   PC_BOUNDS_INVALID,
1815
1816   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1817   PC_BOUNDS_RANGES,
1818
1819   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1820   PC_BOUNDS_HIGH_LOW,
1821 };
1822
1823 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1824                                                  CORE_ADDR *, CORE_ADDR *,
1825                                                  struct dwarf2_cu *,
1826                                                  struct partial_symtab *);
1827
1828 static void get_scope_pc_bounds (struct die_info *,
1829                                  CORE_ADDR *, CORE_ADDR *,
1830                                  struct dwarf2_cu *);
1831
1832 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1833                                         CORE_ADDR, struct dwarf2_cu *);
1834
1835 static void dwarf2_add_field (struct field_info *, struct die_info *,
1836                               struct dwarf2_cu *);
1837
1838 static void dwarf2_attach_fields_to_type (struct field_info *,
1839                                           struct type *, struct dwarf2_cu *);
1840
1841 static void dwarf2_add_member_fn (struct field_info *,
1842                                   struct die_info *, struct type *,
1843                                   struct dwarf2_cu *);
1844
1845 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1846                                              struct type *,
1847                                              struct dwarf2_cu *);
1848
1849 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1850
1851 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1852
1853 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1854
1855 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1856
1857 static struct using_direct **using_directives (enum language);
1858
1859 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1860
1861 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1862
1863 static struct type *read_module_type (struct die_info *die,
1864                                       struct dwarf2_cu *cu);
1865
1866 static const char *namespace_name (struct die_info *die,
1867                                    int *is_anonymous, struct dwarf2_cu *);
1868
1869 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1870
1871 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1872
1873 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1874                                                        struct dwarf2_cu *);
1875
1876 static struct die_info *read_die_and_siblings_1
1877   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1878    struct die_info *);
1879
1880 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1881                                                const gdb_byte *info_ptr,
1882                                                const gdb_byte **new_info_ptr,
1883                                                struct die_info *parent);
1884
1885 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1886                                         struct die_info **, const gdb_byte *,
1887                                         int *, int);
1888
1889 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1890                                       struct die_info **, const gdb_byte *,
1891                                       int *);
1892
1893 static void process_die (struct die_info *, struct dwarf2_cu *);
1894
1895 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1896                                              struct obstack *);
1897
1898 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1899
1900 static const char *dwarf2_full_name (const char *name,
1901                                      struct die_info *die,
1902                                      struct dwarf2_cu *cu);
1903
1904 static const char *dwarf2_physname (const char *name, struct die_info *die,
1905                                     struct dwarf2_cu *cu);
1906
1907 static struct die_info *dwarf2_extension (struct die_info *die,
1908                                           struct dwarf2_cu **);
1909
1910 static const char *dwarf_tag_name (unsigned int);
1911
1912 static const char *dwarf_attr_name (unsigned int);
1913
1914 static const char *dwarf_form_name (unsigned int);
1915
1916 static const char *dwarf_bool_name (unsigned int);
1917
1918 static const char *dwarf_type_encoding_name (unsigned int);
1919
1920 static struct die_info *sibling_die (struct die_info *);
1921
1922 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1923
1924 static void dump_die_for_error (struct die_info *);
1925
1926 static void dump_die_1 (struct ui_file *, int level, int max_level,
1927                         struct die_info *);
1928
1929 /*static*/ void dump_die (struct die_info *, int max_level);
1930
1931 static void store_in_ref_table (struct die_info *,
1932                                 struct dwarf2_cu *);
1933
1934 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1935
1936 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1937
1938 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1939                                                const struct attribute *,
1940                                                struct dwarf2_cu **);
1941
1942 static struct die_info *follow_die_ref (struct die_info *,
1943                                         const struct attribute *,
1944                                         struct dwarf2_cu **);
1945
1946 static struct die_info *follow_die_sig (struct die_info *,
1947                                         const struct attribute *,
1948                                         struct dwarf2_cu **);
1949
1950 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1951                                          struct dwarf2_cu *);
1952
1953 static struct type *get_DW_AT_signature_type (struct die_info *,
1954                                               const struct attribute *,
1955                                               struct dwarf2_cu *);
1956
1957 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1958
1959 static void read_signatured_type (struct signatured_type *);
1960
1961 static int attr_to_dynamic_prop (const struct attribute *attr,
1962                                  struct die_info *die, struct dwarf2_cu *cu,
1963                                  struct dynamic_prop *prop);
1964
1965 /* memory allocation interface */
1966
1967 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1968
1969 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1970
1971 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1972
1973 static int attr_form_is_block (const struct attribute *);
1974
1975 static int attr_form_is_section_offset (const struct attribute *);
1976
1977 static int attr_form_is_constant (const struct attribute *);
1978
1979 static int attr_form_is_ref (const struct attribute *);
1980
1981 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1982                                    struct dwarf2_loclist_baton *baton,
1983                                    const struct attribute *attr);
1984
1985 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1986                                          struct symbol *sym,
1987                                          struct dwarf2_cu *cu,
1988                                          int is_block);
1989
1990 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1991                                      const gdb_byte *info_ptr,
1992                                      struct abbrev_info *abbrev);
1993
1994 static void free_stack_comp_unit (void *);
1995
1996 static hashval_t partial_die_hash (const void *item);
1997
1998 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1999
2000 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2001   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2002
2003 static void init_one_comp_unit (struct dwarf2_cu *cu,
2004                                 struct dwarf2_per_cu_data *per_cu);
2005
2006 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2007                                    struct die_info *comp_unit_die,
2008                                    enum language pretend_language);
2009
2010 static void free_heap_comp_unit (void *);
2011
2012 static void free_cached_comp_units (void *);
2013
2014 static void age_cached_comp_units (void);
2015
2016 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2017
2018 static struct type *set_die_type (struct die_info *, struct type *,
2019                                   struct dwarf2_cu *);
2020
2021 static void create_all_comp_units (struct objfile *);
2022
2023 static int create_all_type_units (struct objfile *);
2024
2025 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2026                                  enum language);
2027
2028 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2029                                     enum language);
2030
2031 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2032                                     enum language);
2033
2034 static void dwarf2_add_dependence (struct dwarf2_cu *,
2035                                    struct dwarf2_per_cu_data *);
2036
2037 static void dwarf2_mark (struct dwarf2_cu *);
2038
2039 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2040
2041 static struct type *get_die_type_at_offset (sect_offset,
2042                                             struct dwarf2_per_cu_data *);
2043
2044 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2045
2046 static void dwarf2_release_queue (void *dummy);
2047
2048 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2049                              enum language pretend_language);
2050
2051 static void process_queue (void);
2052
2053 /* The return type of find_file_and_directory.  Note, the enclosed
2054    string pointers are only valid while this object is valid.  */
2055
2056 struct file_and_directory
2057 {
2058   /* The filename.  This is never NULL.  */
2059   const char *name;
2060
2061   /* The compilation directory.  NULL if not known.  If we needed to
2062      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2063      points directly to the DW_AT_comp_dir string attribute owned by
2064      the obstack that owns the DIE.  */
2065   const char *comp_dir;
2066
2067   /* If we needed to build a new string for comp_dir, this is what
2068      owns the storage.  */
2069   std::string comp_dir_storage;
2070 };
2071
2072 static file_and_directory find_file_and_directory (struct die_info *die,
2073                                                    struct dwarf2_cu *cu);
2074
2075 static char *file_full_name (int file, struct line_header *lh,
2076                              const char *comp_dir);
2077
2078 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2079 enum class rcuh_kind { COMPILE, TYPE };
2080
2081 static const gdb_byte *read_and_check_comp_unit_head
2082   (struct comp_unit_head *header,
2083    struct dwarf2_section_info *section,
2084    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2085    rcuh_kind section_kind);
2086
2087 static void init_cutu_and_read_dies
2088   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2089    int use_existing_cu, int keep,
2090    die_reader_func_ftype *die_reader_func, void *data);
2091
2092 static void init_cutu_and_read_dies_simple
2093   (struct dwarf2_per_cu_data *this_cu,
2094    die_reader_func_ftype *die_reader_func, void *data);
2095
2096 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2097
2098 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2099
2100 static struct dwo_unit *lookup_dwo_unit_in_dwp
2101   (struct dwp_file *dwp_file, const char *comp_dir,
2102    ULONGEST signature, int is_debug_types);
2103
2104 static struct dwp_file *get_dwp_file (void);
2105
2106 static struct dwo_unit *lookup_dwo_comp_unit
2107   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2108
2109 static struct dwo_unit *lookup_dwo_type_unit
2110   (struct signatured_type *, const char *, const char *);
2111
2112 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2113
2114 static void free_dwo_file_cleanup (void *);
2115
2116 static void process_cu_includes (void);
2117
2118 static void check_producer (struct dwarf2_cu *cu);
2119
2120 static void free_line_header_voidp (void *arg);
2121 \f
2122 /* Various complaints about symbol reading that don't abort the process.  */
2123
2124 static void
2125 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2126 {
2127   complaint (&symfile_complaints,
2128              _("statement list doesn't fit in .debug_line section"));
2129 }
2130
2131 static void
2132 dwarf2_debug_line_missing_file_complaint (void)
2133 {
2134   complaint (&symfile_complaints,
2135              _(".debug_line section has line data without a file"));
2136 }
2137
2138 static void
2139 dwarf2_debug_line_missing_end_sequence_complaint (void)
2140 {
2141   complaint (&symfile_complaints,
2142              _(".debug_line section has line "
2143                "program sequence without an end"));
2144 }
2145
2146 static void
2147 dwarf2_complex_location_expr_complaint (void)
2148 {
2149   complaint (&symfile_complaints, _("location expression too complex"));
2150 }
2151
2152 static void
2153 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2154                                               int arg3)
2155 {
2156   complaint (&symfile_complaints,
2157              _("const value length mismatch for '%s', got %d, expected %d"),
2158              arg1, arg2, arg3);
2159 }
2160
2161 static void
2162 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2163 {
2164   complaint (&symfile_complaints,
2165              _("debug info runs off end of %s section"
2166                " [in module %s]"),
2167              get_section_name (section),
2168              get_section_file_name (section));
2169 }
2170
2171 static void
2172 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2173 {
2174   complaint (&symfile_complaints,
2175              _("macro debug info contains a "
2176                "malformed macro definition:\n`%s'"),
2177              arg1);
2178 }
2179
2180 static void
2181 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2182 {
2183   complaint (&symfile_complaints,
2184              _("invalid attribute class or form for '%s' in '%s'"),
2185              arg1, arg2);
2186 }
2187
2188 /* Hash function for line_header_hash.  */
2189
2190 static hashval_t
2191 line_header_hash (const struct line_header *ofs)
2192 {
2193   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2194 }
2195
2196 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2197
2198 static hashval_t
2199 line_header_hash_voidp (const void *item)
2200 {
2201   const struct line_header *ofs = (const struct line_header *) item;
2202
2203   return line_header_hash (ofs);
2204 }
2205
2206 /* Equality function for line_header_hash.  */
2207
2208 static int
2209 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2210 {
2211   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2212   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2213
2214   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2215           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2216 }
2217
2218 \f
2219
2220 /* Read the given attribute value as an address, taking the attribute's
2221    form into account.  */
2222
2223 static CORE_ADDR
2224 attr_value_as_address (struct attribute *attr)
2225 {
2226   CORE_ADDR addr;
2227
2228   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2229     {
2230       /* Aside from a few clearly defined exceptions, attributes that
2231          contain an address must always be in DW_FORM_addr form.
2232          Unfortunately, some compilers happen to be violating this
2233          requirement by encoding addresses using other forms, such
2234          as DW_FORM_data4 for example.  For those broken compilers,
2235          we try to do our best, without any guarantee of success,
2236          to interpret the address correctly.  It would also be nice
2237          to generate a complaint, but that would require us to maintain
2238          a list of legitimate cases where a non-address form is allowed,
2239          as well as update callers to pass in at least the CU's DWARF
2240          version.  This is more overhead than what we're willing to
2241          expand for a pretty rare case.  */
2242       addr = DW_UNSND (attr);
2243     }
2244   else
2245     addr = DW_ADDR (attr);
2246
2247   return addr;
2248 }
2249
2250 /* The suffix for an index file.  */
2251 #define INDEX_SUFFIX ".gdb-index"
2252
2253 /* See declaration.  */
2254
2255 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2256                                         const dwarf2_debug_sections *names)
2257   : objfile (objfile_)
2258 {
2259   if (names == NULL)
2260     names = &dwarf2_elf_names;
2261
2262   bfd *obfd = objfile->obfd;
2263
2264   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2265     locate_sections (obfd, sec, *names);
2266 }
2267
2268 dwarf2_per_objfile::~dwarf2_per_objfile ()
2269 {
2270   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2271   free_cached_comp_units ();
2272
2273   if (quick_file_names_table)
2274     htab_delete (quick_file_names_table);
2275
2276   if (line_header_hash)
2277     htab_delete (line_header_hash);
2278
2279   /* Everything else should be on the objfile obstack.  */
2280 }
2281
2282 /* See declaration.  */
2283
2284 void
2285 dwarf2_per_objfile::free_cached_comp_units ()
2286 {
2287   dwarf2_per_cu_data *per_cu = read_in_chain;
2288   dwarf2_per_cu_data **last_chain = &read_in_chain;
2289   while (per_cu != NULL)
2290     {
2291       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2292
2293       free_heap_comp_unit (per_cu->cu);
2294       *last_chain = next_cu;
2295       per_cu = next_cu;
2296     }
2297 }
2298
2299 /* Try to locate the sections we need for DWARF 2 debugging
2300    information and return true if we have enough to do something.
2301    NAMES points to the dwarf2 section names, or is NULL if the standard
2302    ELF names are used.  */
2303
2304 int
2305 dwarf2_has_info (struct objfile *objfile,
2306                  const struct dwarf2_debug_sections *names)
2307 {
2308   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2309                         objfile_data (objfile, dwarf2_objfile_data_key));
2310   if (!dwarf2_per_objfile)
2311     {
2312       /* Initialize per-objfile state.  */
2313       struct dwarf2_per_objfile *data
2314         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2315
2316       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2317       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2318     }
2319   return (!dwarf2_per_objfile->info.is_virtual
2320           && dwarf2_per_objfile->info.s.section != NULL
2321           && !dwarf2_per_objfile->abbrev.is_virtual
2322           && dwarf2_per_objfile->abbrev.s.section != NULL);
2323 }
2324
2325 /* Return the containing section of virtual section SECTION.  */
2326
2327 static struct dwarf2_section_info *
2328 get_containing_section (const struct dwarf2_section_info *section)
2329 {
2330   gdb_assert (section->is_virtual);
2331   return section->s.containing_section;
2332 }
2333
2334 /* Return the bfd owner of SECTION.  */
2335
2336 static struct bfd *
2337 get_section_bfd_owner (const struct dwarf2_section_info *section)
2338 {
2339   if (section->is_virtual)
2340     {
2341       section = get_containing_section (section);
2342       gdb_assert (!section->is_virtual);
2343     }
2344   return section->s.section->owner;
2345 }
2346
2347 /* Return the bfd section of SECTION.
2348    Returns NULL if the section is not present.  */
2349
2350 static asection *
2351 get_section_bfd_section (const struct dwarf2_section_info *section)
2352 {
2353   if (section->is_virtual)
2354     {
2355       section = get_containing_section (section);
2356       gdb_assert (!section->is_virtual);
2357     }
2358   return section->s.section;
2359 }
2360
2361 /* Return the name of SECTION.  */
2362
2363 static const char *
2364 get_section_name (const struct dwarf2_section_info *section)
2365 {
2366   asection *sectp = get_section_bfd_section (section);
2367
2368   gdb_assert (sectp != NULL);
2369   return bfd_section_name (get_section_bfd_owner (section), sectp);
2370 }
2371
2372 /* Return the name of the file SECTION is in.  */
2373
2374 static const char *
2375 get_section_file_name (const struct dwarf2_section_info *section)
2376 {
2377   bfd *abfd = get_section_bfd_owner (section);
2378
2379   return bfd_get_filename (abfd);
2380 }
2381
2382 /* Return the id of SECTION.
2383    Returns 0 if SECTION doesn't exist.  */
2384
2385 static int
2386 get_section_id (const struct dwarf2_section_info *section)
2387 {
2388   asection *sectp = get_section_bfd_section (section);
2389
2390   if (sectp == NULL)
2391     return 0;
2392   return sectp->id;
2393 }
2394
2395 /* Return the flags of SECTION.
2396    SECTION (or containing section if this is a virtual section) must exist.  */
2397
2398 static int
2399 get_section_flags (const struct dwarf2_section_info *section)
2400 {
2401   asection *sectp = get_section_bfd_section (section);
2402
2403   gdb_assert (sectp != NULL);
2404   return bfd_get_section_flags (sectp->owner, sectp);
2405 }
2406
2407 /* When loading sections, we look either for uncompressed section or for
2408    compressed section names.  */
2409
2410 static int
2411 section_is_p (const char *section_name,
2412               const struct dwarf2_section_names *names)
2413 {
2414   if (names->normal != NULL
2415       && strcmp (section_name, names->normal) == 0)
2416     return 1;
2417   if (names->compressed != NULL
2418       && strcmp (section_name, names->compressed) == 0)
2419     return 1;
2420   return 0;
2421 }
2422
2423 /* See declaration.  */
2424
2425 void
2426 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2427                                      const dwarf2_debug_sections &names)
2428 {
2429   flagword aflag = bfd_get_section_flags (abfd, sectp);
2430
2431   if ((aflag & SEC_HAS_CONTENTS) == 0)
2432     {
2433     }
2434   else if (section_is_p (sectp->name, &names.info))
2435     {
2436       this->info.s.section = sectp;
2437       this->info.size = bfd_get_section_size (sectp);
2438     }
2439   else if (section_is_p (sectp->name, &names.abbrev))
2440     {
2441       this->abbrev.s.section = sectp;
2442       this->abbrev.size = bfd_get_section_size (sectp);
2443     }
2444   else if (section_is_p (sectp->name, &names.line))
2445     {
2446       this->line.s.section = sectp;
2447       this->line.size = bfd_get_section_size (sectp);
2448     }
2449   else if (section_is_p (sectp->name, &names.loc))
2450     {
2451       this->loc.s.section = sectp;
2452       this->loc.size = bfd_get_section_size (sectp);
2453     }
2454   else if (section_is_p (sectp->name, &names.loclists))
2455     {
2456       this->loclists.s.section = sectp;
2457       this->loclists.size = bfd_get_section_size (sectp);
2458     }
2459   else if (section_is_p (sectp->name, &names.macinfo))
2460     {
2461       this->macinfo.s.section = sectp;
2462       this->macinfo.size = bfd_get_section_size (sectp);
2463     }
2464   else if (section_is_p (sectp->name, &names.macro))
2465     {
2466       this->macro.s.section = sectp;
2467       this->macro.size = bfd_get_section_size (sectp);
2468     }
2469   else if (section_is_p (sectp->name, &names.str))
2470     {
2471       this->str.s.section = sectp;
2472       this->str.size = bfd_get_section_size (sectp);
2473     }
2474   else if (section_is_p (sectp->name, &names.line_str))
2475     {
2476       this->line_str.s.section = sectp;
2477       this->line_str.size = bfd_get_section_size (sectp);
2478     }
2479   else if (section_is_p (sectp->name, &names.addr))
2480     {
2481       this->addr.s.section = sectp;
2482       this->addr.size = bfd_get_section_size (sectp);
2483     }
2484   else if (section_is_p (sectp->name, &names.frame))
2485     {
2486       this->frame.s.section = sectp;
2487       this->frame.size = bfd_get_section_size (sectp);
2488     }
2489   else if (section_is_p (sectp->name, &names.eh_frame))
2490     {
2491       this->eh_frame.s.section = sectp;
2492       this->eh_frame.size = bfd_get_section_size (sectp);
2493     }
2494   else if (section_is_p (sectp->name, &names.ranges))
2495     {
2496       this->ranges.s.section = sectp;
2497       this->ranges.size = bfd_get_section_size (sectp);
2498     }
2499   else if (section_is_p (sectp->name, &names.rnglists))
2500     {
2501       this->rnglists.s.section = sectp;
2502       this->rnglists.size = bfd_get_section_size (sectp);
2503     }
2504   else if (section_is_p (sectp->name, &names.types))
2505     {
2506       struct dwarf2_section_info type_section;
2507
2508       memset (&type_section, 0, sizeof (type_section));
2509       type_section.s.section = sectp;
2510       type_section.size = bfd_get_section_size (sectp);
2511
2512       VEC_safe_push (dwarf2_section_info_def, this->types,
2513                      &type_section);
2514     }
2515   else if (section_is_p (sectp->name, &names.gdb_index))
2516     {
2517       this->gdb_index.s.section = sectp;
2518       this->gdb_index.size = bfd_get_section_size (sectp);
2519     }
2520
2521   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2522       && bfd_section_vma (abfd, sectp) == 0)
2523     this->has_section_at_zero = true;
2524 }
2525
2526 /* A helper function that decides whether a section is empty,
2527    or not present.  */
2528
2529 static int
2530 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2531 {
2532   if (section->is_virtual)
2533     return section->size == 0;
2534   return section->s.section == NULL || section->size == 0;
2535 }
2536
2537 /* Read the contents of the section INFO.
2538    OBJFILE is the main object file, but not necessarily the file where
2539    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2540    of the DWO file.
2541    If the section is compressed, uncompress it before returning.  */
2542
2543 static void
2544 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2545 {
2546   asection *sectp;
2547   bfd *abfd;
2548   gdb_byte *buf, *retbuf;
2549
2550   if (info->readin)
2551     return;
2552   info->buffer = NULL;
2553   info->readin = 1;
2554
2555   if (dwarf2_section_empty_p (info))
2556     return;
2557
2558   sectp = get_section_bfd_section (info);
2559
2560   /* If this is a virtual section we need to read in the real one first.  */
2561   if (info->is_virtual)
2562     {
2563       struct dwarf2_section_info *containing_section =
2564         get_containing_section (info);
2565
2566       gdb_assert (sectp != NULL);
2567       if ((sectp->flags & SEC_RELOC) != 0)
2568         {
2569           error (_("Dwarf Error: DWP format V2 with relocations is not"
2570                    " supported in section %s [in module %s]"),
2571                  get_section_name (info), get_section_file_name (info));
2572         }
2573       dwarf2_read_section (objfile, containing_section);
2574       /* Other code should have already caught virtual sections that don't
2575          fit.  */
2576       gdb_assert (info->virtual_offset + info->size
2577                   <= containing_section->size);
2578       /* If the real section is empty or there was a problem reading the
2579          section we shouldn't get here.  */
2580       gdb_assert (containing_section->buffer != NULL);
2581       info->buffer = containing_section->buffer + info->virtual_offset;
2582       return;
2583     }
2584
2585   /* If the section has relocations, we must read it ourselves.
2586      Otherwise we attach it to the BFD.  */
2587   if ((sectp->flags & SEC_RELOC) == 0)
2588     {
2589       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2590       return;
2591     }
2592
2593   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2594   info->buffer = buf;
2595
2596   /* When debugging .o files, we may need to apply relocations; see
2597      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2598      We never compress sections in .o files, so we only need to
2599      try this when the section is not compressed.  */
2600   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2601   if (retbuf != NULL)
2602     {
2603       info->buffer = retbuf;
2604       return;
2605     }
2606
2607   abfd = get_section_bfd_owner (info);
2608   gdb_assert (abfd != NULL);
2609
2610   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2611       || bfd_bread (buf, info->size, abfd) != info->size)
2612     {
2613       error (_("Dwarf Error: Can't read DWARF data"
2614                " in section %s [in module %s]"),
2615              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2616     }
2617 }
2618
2619 /* A helper function that returns the size of a section in a safe way.
2620    If you are positive that the section has been read before using the
2621    size, then it is safe to refer to the dwarf2_section_info object's
2622    "size" field directly.  In other cases, you must call this
2623    function, because for compressed sections the size field is not set
2624    correctly until the section has been read.  */
2625
2626 static bfd_size_type
2627 dwarf2_section_size (struct objfile *objfile,
2628                      struct dwarf2_section_info *info)
2629 {
2630   if (!info->readin)
2631     dwarf2_read_section (objfile, info);
2632   return info->size;
2633 }
2634
2635 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2636    SECTION_NAME.  */
2637
2638 void
2639 dwarf2_get_section_info (struct objfile *objfile,
2640                          enum dwarf2_section_enum sect,
2641                          asection **sectp, const gdb_byte **bufp,
2642                          bfd_size_type *sizep)
2643 {
2644   struct dwarf2_per_objfile *data
2645     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2646                                                   dwarf2_objfile_data_key);
2647   struct dwarf2_section_info *info;
2648
2649   /* We may see an objfile without any DWARF, in which case we just
2650      return nothing.  */
2651   if (data == NULL)
2652     {
2653       *sectp = NULL;
2654       *bufp = NULL;
2655       *sizep = 0;
2656       return;
2657     }
2658   switch (sect)
2659     {
2660     case DWARF2_DEBUG_FRAME:
2661       info = &data->frame;
2662       break;
2663     case DWARF2_EH_FRAME:
2664       info = &data->eh_frame;
2665       break;
2666     default:
2667       gdb_assert_not_reached ("unexpected section");
2668     }
2669
2670   dwarf2_read_section (objfile, info);
2671
2672   *sectp = get_section_bfd_section (info);
2673   *bufp = info->buffer;
2674   *sizep = info->size;
2675 }
2676
2677 /* A helper function to find the sections for a .dwz file.  */
2678
2679 static void
2680 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2681 {
2682   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2683
2684   /* Note that we only support the standard ELF names, because .dwz
2685      is ELF-only (at the time of writing).  */
2686   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2687     {
2688       dwz_file->abbrev.s.section = sectp;
2689       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2690     }
2691   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2692     {
2693       dwz_file->info.s.section = sectp;
2694       dwz_file->info.size = bfd_get_section_size (sectp);
2695     }
2696   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2697     {
2698       dwz_file->str.s.section = sectp;
2699       dwz_file->str.size = bfd_get_section_size (sectp);
2700     }
2701   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2702     {
2703       dwz_file->line.s.section = sectp;
2704       dwz_file->line.size = bfd_get_section_size (sectp);
2705     }
2706   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2707     {
2708       dwz_file->macro.s.section = sectp;
2709       dwz_file->macro.size = bfd_get_section_size (sectp);
2710     }
2711   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2712     {
2713       dwz_file->gdb_index.s.section = sectp;
2714       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2715     }
2716 }
2717
2718 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2719    there is no .gnu_debugaltlink section in the file.  Error if there
2720    is such a section but the file cannot be found.  */
2721
2722 static struct dwz_file *
2723 dwarf2_get_dwz_file (void)
2724 {
2725   const char *filename;
2726   struct dwz_file *result;
2727   bfd_size_type buildid_len_arg;
2728   size_t buildid_len;
2729   bfd_byte *buildid;
2730
2731   if (dwarf2_per_objfile->dwz_file != NULL)
2732     return dwarf2_per_objfile->dwz_file;
2733
2734   bfd_set_error (bfd_error_no_error);
2735   gdb::unique_xmalloc_ptr<char> data
2736     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2737                                   &buildid_len_arg, &buildid));
2738   if (data == NULL)
2739     {
2740       if (bfd_get_error () == bfd_error_no_error)
2741         return NULL;
2742       error (_("could not read '.gnu_debugaltlink' section: %s"),
2743              bfd_errmsg (bfd_get_error ()));
2744     }
2745
2746   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2747
2748   buildid_len = (size_t) buildid_len_arg;
2749
2750   filename = data.get ();
2751
2752   std::string abs_storage;
2753   if (!IS_ABSOLUTE_PATH (filename))
2754     {
2755       gdb::unique_xmalloc_ptr<char> abs
2756         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2757
2758       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2759       filename = abs_storage.c_str ();
2760     }
2761
2762   /* First try the file name given in the section.  If that doesn't
2763      work, try to use the build-id instead.  */
2764   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2765   if (dwz_bfd != NULL)
2766     {
2767       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2768         dwz_bfd.release ();
2769     }
2770
2771   if (dwz_bfd == NULL)
2772     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2773
2774   if (dwz_bfd == NULL)
2775     error (_("could not find '.gnu_debugaltlink' file for %s"),
2776            objfile_name (dwarf2_per_objfile->objfile));
2777
2778   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2779                            struct dwz_file);
2780   result->dwz_bfd = dwz_bfd.release ();
2781
2782   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2783
2784   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2785   dwarf2_per_objfile->dwz_file = result;
2786   return result;
2787 }
2788 \f
2789 /* DWARF quick_symbols_functions support.  */
2790
2791 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2792    unique line tables, so we maintain a separate table of all .debug_line
2793    derived entries to support the sharing.
2794    All the quick functions need is the list of file names.  We discard the
2795    line_header when we're done and don't need to record it here.  */
2796 struct quick_file_names
2797 {
2798   /* The data used to construct the hash key.  */
2799   struct stmt_list_hash hash;
2800
2801   /* The number of entries in file_names, real_names.  */
2802   unsigned int num_file_names;
2803
2804   /* The file names from the line table, after being run through
2805      file_full_name.  */
2806   const char **file_names;
2807
2808   /* The file names from the line table after being run through
2809      gdb_realpath.  These are computed lazily.  */
2810   const char **real_names;
2811 };
2812
2813 /* When using the index (and thus not using psymtabs), each CU has an
2814    object of this type.  This is used to hold information needed by
2815    the various "quick" methods.  */
2816 struct dwarf2_per_cu_quick_data
2817 {
2818   /* The file table.  This can be NULL if there was no file table
2819      or it's currently not read in.
2820      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2821   struct quick_file_names *file_names;
2822
2823   /* The corresponding symbol table.  This is NULL if symbols for this
2824      CU have not yet been read.  */
2825   struct compunit_symtab *compunit_symtab;
2826
2827   /* A temporary mark bit used when iterating over all CUs in
2828      expand_symtabs_matching.  */
2829   unsigned int mark : 1;
2830
2831   /* True if we've tried to read the file table and found there isn't one.
2832      There will be no point in trying to read it again next time.  */
2833   unsigned int no_file_data : 1;
2834 };
2835
2836 /* Utility hash function for a stmt_list_hash.  */
2837
2838 static hashval_t
2839 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2840 {
2841   hashval_t v = 0;
2842
2843   if (stmt_list_hash->dwo_unit != NULL)
2844     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2845   v += to_underlying (stmt_list_hash->line_sect_off);
2846   return v;
2847 }
2848
2849 /* Utility equality function for a stmt_list_hash.  */
2850
2851 static int
2852 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2853                     const struct stmt_list_hash *rhs)
2854 {
2855   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2856     return 0;
2857   if (lhs->dwo_unit != NULL
2858       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2859     return 0;
2860
2861   return lhs->line_sect_off == rhs->line_sect_off;
2862 }
2863
2864 /* Hash function for a quick_file_names.  */
2865
2866 static hashval_t
2867 hash_file_name_entry (const void *e)
2868 {
2869   const struct quick_file_names *file_data
2870     = (const struct quick_file_names *) e;
2871
2872   return hash_stmt_list_entry (&file_data->hash);
2873 }
2874
2875 /* Equality function for a quick_file_names.  */
2876
2877 static int
2878 eq_file_name_entry (const void *a, const void *b)
2879 {
2880   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2881   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2882
2883   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2884 }
2885
2886 /* Delete function for a quick_file_names.  */
2887
2888 static void
2889 delete_file_name_entry (void *e)
2890 {
2891   struct quick_file_names *file_data = (struct quick_file_names *) e;
2892   int i;
2893
2894   for (i = 0; i < file_data->num_file_names; ++i)
2895     {
2896       xfree ((void*) file_data->file_names[i]);
2897       if (file_data->real_names)
2898         xfree ((void*) file_data->real_names[i]);
2899     }
2900
2901   /* The space for the struct itself lives on objfile_obstack,
2902      so we don't free it here.  */
2903 }
2904
2905 /* Create a quick_file_names hash table.  */
2906
2907 static htab_t
2908 create_quick_file_names_table (unsigned int nr_initial_entries)
2909 {
2910   return htab_create_alloc (nr_initial_entries,
2911                             hash_file_name_entry, eq_file_name_entry,
2912                             delete_file_name_entry, xcalloc, xfree);
2913 }
2914
2915 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2916    have to be created afterwards.  You should call age_cached_comp_units after
2917    processing PER_CU->CU.  dw2_setup must have been already called.  */
2918
2919 static void
2920 load_cu (struct dwarf2_per_cu_data *per_cu)
2921 {
2922   if (per_cu->is_debug_types)
2923     load_full_type_unit (per_cu);
2924   else
2925     load_full_comp_unit (per_cu, language_minimal);
2926
2927   if (per_cu->cu == NULL)
2928     return;  /* Dummy CU.  */
2929
2930   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2931 }
2932
2933 /* Read in the symbols for PER_CU.  */
2934
2935 static void
2936 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2937 {
2938   struct cleanup *back_to;
2939
2940   /* Skip type_unit_groups, reading the type units they contain
2941      is handled elsewhere.  */
2942   if (IS_TYPE_UNIT_GROUP (per_cu))
2943     return;
2944
2945   back_to = make_cleanup (dwarf2_release_queue, NULL);
2946
2947   if (dwarf2_per_objfile->using_index
2948       ? per_cu->v.quick->compunit_symtab == NULL
2949       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2950     {
2951       queue_comp_unit (per_cu, language_minimal);
2952       load_cu (per_cu);
2953
2954       /* If we just loaded a CU from a DWO, and we're working with an index
2955          that may badly handle TUs, load all the TUs in that DWO as well.
2956          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2957       if (!per_cu->is_debug_types
2958           && per_cu->cu != NULL
2959           && per_cu->cu->dwo_unit != NULL
2960           && dwarf2_per_objfile->index_table != NULL
2961           && dwarf2_per_objfile->index_table->version <= 7
2962           /* DWP files aren't supported yet.  */
2963           && get_dwp_file () == NULL)
2964         queue_and_load_all_dwo_tus (per_cu);
2965     }
2966
2967   process_queue ();
2968
2969   /* Age the cache, releasing compilation units that have not
2970      been used recently.  */
2971   age_cached_comp_units ();
2972
2973   do_cleanups (back_to);
2974 }
2975
2976 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2977    the objfile from which this CU came.  Returns the resulting symbol
2978    table.  */
2979
2980 static struct compunit_symtab *
2981 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2982 {
2983   gdb_assert (dwarf2_per_objfile->using_index);
2984   if (!per_cu->v.quick->compunit_symtab)
2985     {
2986       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2987       scoped_restore decrementer = increment_reading_symtab ();
2988       dw2_do_instantiate_symtab (per_cu);
2989       process_cu_includes ();
2990       do_cleanups (back_to);
2991     }
2992
2993   return per_cu->v.quick->compunit_symtab;
2994 }
2995
2996 /* Return the CU/TU given its index.
2997
2998    This is intended for loops like:
2999
3000    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3001                     + dwarf2_per_objfile->n_type_units); ++i)
3002      {
3003        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3004
3005        ...;
3006      }
3007 */
3008
3009 static struct dwarf2_per_cu_data *
3010 dw2_get_cutu (int index)
3011 {
3012   if (index >= dwarf2_per_objfile->n_comp_units)
3013     {
3014       index -= dwarf2_per_objfile->n_comp_units;
3015       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3016       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3017     }
3018
3019   return dwarf2_per_objfile->all_comp_units[index];
3020 }
3021
3022 /* Return the CU given its index.
3023    This differs from dw2_get_cutu in that it's for when you know INDEX
3024    refers to a CU.  */
3025
3026 static struct dwarf2_per_cu_data *
3027 dw2_get_cu (int index)
3028 {
3029   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3030
3031   return dwarf2_per_objfile->all_comp_units[index];
3032 }
3033
3034 /* A helper for create_cus_from_index that handles a given list of
3035    CUs.  */
3036
3037 static void
3038 create_cus_from_index_list (struct objfile *objfile,
3039                             const gdb_byte *cu_list, offset_type n_elements,
3040                             struct dwarf2_section_info *section,
3041                             int is_dwz,
3042                             int base_offset)
3043 {
3044   offset_type i;
3045
3046   for (i = 0; i < n_elements; i += 2)
3047     {
3048       gdb_static_assert (sizeof (ULONGEST) >= 8);
3049
3050       sect_offset sect_off
3051         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3052       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3053       cu_list += 2 * 8;
3054
3055       dwarf2_per_cu_data *the_cu
3056         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                           struct dwarf2_per_cu_data);
3058       the_cu->sect_off = sect_off;
3059       the_cu->length = length;
3060       the_cu->objfile = objfile;
3061       the_cu->section = section;
3062       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3063                                         struct dwarf2_per_cu_quick_data);
3064       the_cu->is_dwz = is_dwz;
3065       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3066     }
3067 }
3068
3069 /* Read the CU list from the mapped index, and use it to create all
3070    the CU objects for this objfile.  */
3071
3072 static void
3073 create_cus_from_index (struct objfile *objfile,
3074                        const gdb_byte *cu_list, offset_type cu_list_elements,
3075                        const gdb_byte *dwz_list, offset_type dwz_elements)
3076 {
3077   struct dwz_file *dwz;
3078
3079   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3080   dwarf2_per_objfile->all_comp_units =
3081     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3082                dwarf2_per_objfile->n_comp_units);
3083
3084   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3085                               &dwarf2_per_objfile->info, 0, 0);
3086
3087   if (dwz_elements == 0)
3088     return;
3089
3090   dwz = dwarf2_get_dwz_file ();
3091   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3092                               cu_list_elements / 2);
3093 }
3094
3095 /* Create the signatured type hash table from the index.  */
3096
3097 static void
3098 create_signatured_type_table_from_index (struct objfile *objfile,
3099                                          struct dwarf2_section_info *section,
3100                                          const gdb_byte *bytes,
3101                                          offset_type elements)
3102 {
3103   offset_type i;
3104   htab_t sig_types_hash;
3105
3106   dwarf2_per_objfile->n_type_units
3107     = dwarf2_per_objfile->n_allocated_type_units
3108     = elements / 3;
3109   dwarf2_per_objfile->all_type_units =
3110     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3111
3112   sig_types_hash = allocate_signatured_type_table (objfile);
3113
3114   for (i = 0; i < elements; i += 3)
3115     {
3116       struct signatured_type *sig_type;
3117       ULONGEST signature;
3118       void **slot;
3119       cu_offset type_offset_in_tu;
3120
3121       gdb_static_assert (sizeof (ULONGEST) >= 8);
3122       sect_offset sect_off
3123         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3124       type_offset_in_tu
3125         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3126                                                 BFD_ENDIAN_LITTLE);
3127       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3128       bytes += 3 * 8;
3129
3130       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3131                                  struct signatured_type);
3132       sig_type->signature = signature;
3133       sig_type->type_offset_in_tu = type_offset_in_tu;
3134       sig_type->per_cu.is_debug_types = 1;
3135       sig_type->per_cu.section = section;
3136       sig_type->per_cu.sect_off = sect_off;
3137       sig_type->per_cu.objfile = objfile;
3138       sig_type->per_cu.v.quick
3139         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3140                           struct dwarf2_per_cu_quick_data);
3141
3142       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3143       *slot = sig_type;
3144
3145       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3146     }
3147
3148   dwarf2_per_objfile->signatured_types = sig_types_hash;
3149 }
3150
3151 /* Read the address map data from the mapped index, and use it to
3152    populate the objfile's psymtabs_addrmap.  */
3153
3154 static void
3155 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3156 {
3157   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3158   const gdb_byte *iter, *end;
3159   struct addrmap *mutable_map;
3160   CORE_ADDR baseaddr;
3161
3162   auto_obstack temp_obstack;
3163
3164   mutable_map = addrmap_create_mutable (&temp_obstack);
3165
3166   iter = index->address_table;
3167   end = iter + index->address_table_size;
3168
3169   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3170
3171   while (iter < end)
3172     {
3173       ULONGEST hi, lo, cu_index;
3174       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3175       iter += 8;
3176       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3177       iter += 8;
3178       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3179       iter += 4;
3180
3181       if (lo > hi)
3182         {
3183           complaint (&symfile_complaints,
3184                      _(".gdb_index address table has invalid range (%s - %s)"),
3185                      hex_string (lo), hex_string (hi));
3186           continue;
3187         }
3188
3189       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3190         {
3191           complaint (&symfile_complaints,
3192                      _(".gdb_index address table has invalid CU number %u"),
3193                      (unsigned) cu_index);
3194           continue;
3195         }
3196
3197       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3198       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3199       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3200     }
3201
3202   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3203                                                     &objfile->objfile_obstack);
3204 }
3205
3206 /* The hash function for strings in the mapped index.  This is the same as
3207    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3208    implementation.  This is necessary because the hash function is tied to the
3209    format of the mapped index file.  The hash values do not have to match with
3210    SYMBOL_HASH_NEXT.
3211    
3212    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3213
3214 static hashval_t
3215 mapped_index_string_hash (int index_version, const void *p)
3216 {
3217   const unsigned char *str = (const unsigned char *) p;
3218   hashval_t r = 0;
3219   unsigned char c;
3220
3221   while ((c = *str++) != 0)
3222     {
3223       if (index_version >= 5)
3224         c = tolower (c);
3225       r = r * 67 + c - 113;
3226     }
3227
3228   return r;
3229 }
3230
3231 /* Find a slot in the mapped index INDEX for the object named NAME.
3232    If NAME is found, set *VEC_OUT to point to the CU vector in the
3233    constant pool and return true.  If NAME cannot be found, return
3234    false.  */
3235
3236 static bool
3237 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3238                           offset_type **vec_out)
3239 {
3240   offset_type hash;
3241   offset_type slot, step;
3242   int (*cmp) (const char *, const char *);
3243
3244   gdb::unique_xmalloc_ptr<char> without_params;
3245   if (current_language->la_language == language_cplus
3246       || current_language->la_language == language_fortran
3247       || current_language->la_language == language_d)
3248     {
3249       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3250          not contain any.  */
3251
3252       if (strchr (name, '(') != NULL)
3253         {
3254           without_params = cp_remove_params (name);
3255
3256           if (without_params != NULL)
3257             name = without_params.get ();
3258         }
3259     }
3260
3261   /* Index version 4 did not support case insensitive searches.  But the
3262      indices for case insensitive languages are built in lowercase, therefore
3263      simulate our NAME being searched is also lowercased.  */
3264   hash = mapped_index_string_hash ((index->version == 4
3265                                     && case_sensitivity == case_sensitive_off
3266                                     ? 5 : index->version),
3267                                    name);
3268
3269   slot = hash & (index->symbol_table_slots - 1);
3270   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3271   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3272
3273   for (;;)
3274     {
3275       /* Convert a slot number to an offset into the table.  */
3276       offset_type i = 2 * slot;
3277       const char *str;
3278       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3279         return false;
3280
3281       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3282       if (!cmp (name, str))
3283         {
3284           *vec_out = (offset_type *) (index->constant_pool
3285                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3286           return true;
3287         }
3288
3289       slot = (slot + step) & (index->symbol_table_slots - 1);
3290     }
3291 }
3292
3293 /* A helper function that reads the .gdb_index from SECTION and fills
3294    in MAP.  FILENAME is the name of the file containing the section;
3295    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3296    ok to use deprecated sections.
3297
3298    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3299    out parameters that are filled in with information about the CU and
3300    TU lists in the section.
3301
3302    Returns 1 if all went well, 0 otherwise.  */
3303
3304 static int
3305 read_index_from_section (struct objfile *objfile,
3306                          const char *filename,
3307                          int deprecated_ok,
3308                          struct dwarf2_section_info *section,
3309                          struct mapped_index *map,
3310                          const gdb_byte **cu_list,
3311                          offset_type *cu_list_elements,
3312                          const gdb_byte **types_list,
3313                          offset_type *types_list_elements)
3314 {
3315   const gdb_byte *addr;
3316   offset_type version;
3317   offset_type *metadata;
3318   int i;
3319
3320   if (dwarf2_section_empty_p (section))
3321     return 0;
3322
3323   /* Older elfutils strip versions could keep the section in the main
3324      executable while splitting it for the separate debug info file.  */
3325   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3326     return 0;
3327
3328   dwarf2_read_section (objfile, section);
3329
3330   addr = section->buffer;
3331   /* Version check.  */
3332   version = MAYBE_SWAP (*(offset_type *) addr);
3333   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3334      causes the index to behave very poorly for certain requests.  Version 3
3335      contained incomplete addrmap.  So, it seems better to just ignore such
3336      indices.  */
3337   if (version < 4)
3338     {
3339       static int warning_printed = 0;
3340       if (!warning_printed)
3341         {
3342           warning (_("Skipping obsolete .gdb_index section in %s."),
3343                    filename);
3344           warning_printed = 1;
3345         }
3346       return 0;
3347     }
3348   /* Index version 4 uses a different hash function than index version
3349      5 and later.
3350
3351      Versions earlier than 6 did not emit psymbols for inlined
3352      functions.  Using these files will cause GDB not to be able to
3353      set breakpoints on inlined functions by name, so we ignore these
3354      indices unless the user has done
3355      "set use-deprecated-index-sections on".  */
3356   if (version < 6 && !deprecated_ok)
3357     {
3358       static int warning_printed = 0;
3359       if (!warning_printed)
3360         {
3361           warning (_("\
3362 Skipping deprecated .gdb_index section in %s.\n\
3363 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3364 to use the section anyway."),
3365                    filename);
3366           warning_printed = 1;
3367         }
3368       return 0;
3369     }
3370   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3371      of the TU (for symbols coming from TUs),
3372      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3373      Plus gold-generated indices can have duplicate entries for global symbols,
3374      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3375      These are just performance bugs, and we can't distinguish gdb-generated
3376      indices from gold-generated ones, so issue no warning here.  */
3377
3378   /* Indexes with higher version than the one supported by GDB may be no
3379      longer backward compatible.  */
3380   if (version > 8)
3381     return 0;
3382
3383   map->version = version;
3384   map->total_size = section->size;
3385
3386   metadata = (offset_type *) (addr + sizeof (offset_type));
3387
3388   i = 0;
3389   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3390   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3391                        / 8);
3392   ++i;
3393
3394   *types_list = addr + MAYBE_SWAP (metadata[i]);
3395   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3396                            - MAYBE_SWAP (metadata[i]))
3397                           / 8);
3398   ++i;
3399
3400   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3401   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3402                              - MAYBE_SWAP (metadata[i]));
3403   ++i;
3404
3405   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3406   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3407                               - MAYBE_SWAP (metadata[i]))
3408                              / (2 * sizeof (offset_type)));
3409   ++i;
3410
3411   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3412
3413   return 1;
3414 }
3415
3416
3417 /* Read the index file.  If everything went ok, initialize the "quick"
3418    elements of all the CUs and return 1.  Otherwise, return 0.  */
3419
3420 static int
3421 dwarf2_read_index (struct objfile *objfile)
3422 {
3423   struct mapped_index local_map, *map;
3424   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3425   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3426   struct dwz_file *dwz;
3427
3428   if (!read_index_from_section (objfile, objfile_name (objfile),
3429                                 use_deprecated_index_sections,
3430                                 &dwarf2_per_objfile->gdb_index, &local_map,
3431                                 &cu_list, &cu_list_elements,
3432                                 &types_list, &types_list_elements))
3433     return 0;
3434
3435   /* Don't use the index if it's empty.  */
3436   if (local_map.symbol_table_slots == 0)
3437     return 0;
3438
3439   /* If there is a .dwz file, read it so we can get its CU list as
3440      well.  */
3441   dwz = dwarf2_get_dwz_file ();
3442   if (dwz != NULL)
3443     {
3444       struct mapped_index dwz_map;
3445       const gdb_byte *dwz_types_ignore;
3446       offset_type dwz_types_elements_ignore;
3447
3448       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3449                                     1,
3450                                     &dwz->gdb_index, &dwz_map,
3451                                     &dwz_list, &dwz_list_elements,
3452                                     &dwz_types_ignore,
3453                                     &dwz_types_elements_ignore))
3454         {
3455           warning (_("could not read '.gdb_index' section from %s; skipping"),
3456                    bfd_get_filename (dwz->dwz_bfd));
3457           return 0;
3458         }
3459     }
3460
3461   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3462                          dwz_list_elements);
3463
3464   if (types_list_elements)
3465     {
3466       struct dwarf2_section_info *section;
3467
3468       /* We can only handle a single .debug_types when we have an
3469          index.  */
3470       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3471         return 0;
3472
3473       section = VEC_index (dwarf2_section_info_def,
3474                            dwarf2_per_objfile->types, 0);
3475
3476       create_signatured_type_table_from_index (objfile, section, types_list,
3477                                                types_list_elements);
3478     }
3479
3480   create_addrmap_from_index (objfile, &local_map);
3481
3482   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3483   map = new (map) mapped_index ();
3484   *map = local_map;
3485
3486   dwarf2_per_objfile->index_table = map;
3487   dwarf2_per_objfile->using_index = 1;
3488   dwarf2_per_objfile->quick_file_names_table =
3489     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3490
3491   return 1;
3492 }
3493
3494 /* A helper for the "quick" functions which sets the global
3495    dwarf2_per_objfile according to OBJFILE.  */
3496
3497 static void
3498 dw2_setup (struct objfile *objfile)
3499 {
3500   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3501                         objfile_data (objfile, dwarf2_objfile_data_key));
3502   gdb_assert (dwarf2_per_objfile);
3503 }
3504
3505 /* die_reader_func for dw2_get_file_names.  */
3506
3507 static void
3508 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3509                            const gdb_byte *info_ptr,
3510                            struct die_info *comp_unit_die,
3511                            int has_children,
3512                            void *data)
3513 {
3514   struct dwarf2_cu *cu = reader->cu;
3515   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3516   struct objfile *objfile = dwarf2_per_objfile->objfile;
3517   struct dwarf2_per_cu_data *lh_cu;
3518   struct attribute *attr;
3519   int i;
3520   void **slot;
3521   struct quick_file_names *qfn;
3522
3523   gdb_assert (! this_cu->is_debug_types);
3524
3525   /* Our callers never want to match partial units -- instead they
3526      will match the enclosing full CU.  */
3527   if (comp_unit_die->tag == DW_TAG_partial_unit)
3528     {
3529       this_cu->v.quick->no_file_data = 1;
3530       return;
3531     }
3532
3533   lh_cu = this_cu;
3534   slot = NULL;
3535
3536   line_header_up lh;
3537   sect_offset line_offset {};
3538
3539   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3540   if (attr)
3541     {
3542       struct quick_file_names find_entry;
3543
3544       line_offset = (sect_offset) DW_UNSND (attr);
3545
3546       /* We may have already read in this line header (TU line header sharing).
3547          If we have we're done.  */
3548       find_entry.hash.dwo_unit = cu->dwo_unit;
3549       find_entry.hash.line_sect_off = line_offset;
3550       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3551                              &find_entry, INSERT);
3552       if (*slot != NULL)
3553         {
3554           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3555           return;
3556         }
3557
3558       lh = dwarf_decode_line_header (line_offset, cu);
3559     }
3560   if (lh == NULL)
3561     {
3562       lh_cu->v.quick->no_file_data = 1;
3563       return;
3564     }
3565
3566   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3567   qfn->hash.dwo_unit = cu->dwo_unit;
3568   qfn->hash.line_sect_off = line_offset;
3569   gdb_assert (slot != NULL);
3570   *slot = qfn;
3571
3572   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3573
3574   qfn->num_file_names = lh->file_names.size ();
3575   qfn->file_names =
3576     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3577   for (i = 0; i < lh->file_names.size (); ++i)
3578     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3579   qfn->real_names = NULL;
3580
3581   lh_cu->v.quick->file_names = qfn;
3582 }
3583
3584 /* A helper for the "quick" functions which attempts to read the line
3585    table for THIS_CU.  */
3586
3587 static struct quick_file_names *
3588 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3589 {
3590   /* This should never be called for TUs.  */
3591   gdb_assert (! this_cu->is_debug_types);
3592   /* Nor type unit groups.  */
3593   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3594
3595   if (this_cu->v.quick->file_names != NULL)
3596     return this_cu->v.quick->file_names;
3597   /* If we know there is no line data, no point in looking again.  */
3598   if (this_cu->v.quick->no_file_data)
3599     return NULL;
3600
3601   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3602
3603   if (this_cu->v.quick->no_file_data)
3604     return NULL;
3605   return this_cu->v.quick->file_names;
3606 }
3607
3608 /* A helper for the "quick" functions which computes and caches the
3609    real path for a given file name from the line table.  */
3610
3611 static const char *
3612 dw2_get_real_path (struct objfile *objfile,
3613                    struct quick_file_names *qfn, int index)
3614 {
3615   if (qfn->real_names == NULL)
3616     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3617                                       qfn->num_file_names, const char *);
3618
3619   if (qfn->real_names[index] == NULL)
3620     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3621
3622   return qfn->real_names[index];
3623 }
3624
3625 static struct symtab *
3626 dw2_find_last_source_symtab (struct objfile *objfile)
3627 {
3628   struct compunit_symtab *cust;
3629   int index;
3630
3631   dw2_setup (objfile);
3632   index = dwarf2_per_objfile->n_comp_units - 1;
3633   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3634   if (cust == NULL)
3635     return NULL;
3636   return compunit_primary_filetab (cust);
3637 }
3638
3639 /* Traversal function for dw2_forget_cached_source_info.  */
3640
3641 static int
3642 dw2_free_cached_file_names (void **slot, void *info)
3643 {
3644   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3645
3646   if (file_data->real_names)
3647     {
3648       int i;
3649
3650       for (i = 0; i < file_data->num_file_names; ++i)
3651         {
3652           xfree ((void*) file_data->real_names[i]);
3653           file_data->real_names[i] = NULL;
3654         }
3655     }
3656
3657   return 1;
3658 }
3659
3660 static void
3661 dw2_forget_cached_source_info (struct objfile *objfile)
3662 {
3663   dw2_setup (objfile);
3664
3665   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3666                           dw2_free_cached_file_names, NULL);
3667 }
3668
3669 /* Helper function for dw2_map_symtabs_matching_filename that expands
3670    the symtabs and calls the iterator.  */
3671
3672 static int
3673 dw2_map_expand_apply (struct objfile *objfile,
3674                       struct dwarf2_per_cu_data *per_cu,
3675                       const char *name, const char *real_path,
3676                       gdb::function_view<bool (symtab *)> callback)
3677 {
3678   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3679
3680   /* Don't visit already-expanded CUs.  */
3681   if (per_cu->v.quick->compunit_symtab)
3682     return 0;
3683
3684   /* This may expand more than one symtab, and we want to iterate over
3685      all of them.  */
3686   dw2_instantiate_symtab (per_cu);
3687
3688   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3689                                     last_made, callback);
3690 }
3691
3692 /* Implementation of the map_symtabs_matching_filename method.  */
3693
3694 static bool
3695 dw2_map_symtabs_matching_filename
3696   (struct objfile *objfile, const char *name, const char *real_path,
3697    gdb::function_view<bool (symtab *)> callback)
3698 {
3699   int i;
3700   const char *name_basename = lbasename (name);
3701
3702   dw2_setup (objfile);
3703
3704   /* The rule is CUs specify all the files, including those used by
3705      any TU, so there's no need to scan TUs here.  */
3706
3707   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3708     {
3709       int j;
3710       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3711       struct quick_file_names *file_data;
3712
3713       /* We only need to look at symtabs not already expanded.  */
3714       if (per_cu->v.quick->compunit_symtab)
3715         continue;
3716
3717       file_data = dw2_get_file_names (per_cu);
3718       if (file_data == NULL)
3719         continue;
3720
3721       for (j = 0; j < file_data->num_file_names; ++j)
3722         {
3723           const char *this_name = file_data->file_names[j];
3724           const char *this_real_name;
3725
3726           if (compare_filenames_for_search (this_name, name))
3727             {
3728               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3729                                         callback))
3730                 return true;
3731               continue;
3732             }
3733
3734           /* Before we invoke realpath, which can get expensive when many
3735              files are involved, do a quick comparison of the basenames.  */
3736           if (! basenames_may_differ
3737               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3738             continue;
3739
3740           this_real_name = dw2_get_real_path (objfile, file_data, j);
3741           if (compare_filenames_for_search (this_real_name, name))
3742             {
3743               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3744                                         callback))
3745                 return true;
3746               continue;
3747             }
3748
3749           if (real_path != NULL)
3750             {
3751               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3752               gdb_assert (IS_ABSOLUTE_PATH (name));
3753               if (this_real_name != NULL
3754                   && FILENAME_CMP (real_path, this_real_name) == 0)
3755                 {
3756                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3757                                             callback))
3758                     return true;
3759                   continue;
3760                 }
3761             }
3762         }
3763     }
3764
3765   return false;
3766 }
3767
3768 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3769
3770 struct dw2_symtab_iterator
3771 {
3772   /* The internalized form of .gdb_index.  */
3773   struct mapped_index *index;
3774   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3775   int want_specific_block;
3776   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3777      Unused if !WANT_SPECIFIC_BLOCK.  */
3778   int block_index;
3779   /* The kind of symbol we're looking for.  */
3780   domain_enum domain;
3781   /* The list of CUs from the index entry of the symbol,
3782      or NULL if not found.  */
3783   offset_type *vec;
3784   /* The next element in VEC to look at.  */
3785   int next;
3786   /* The number of elements in VEC, or zero if there is no match.  */
3787   int length;
3788   /* Have we seen a global version of the symbol?
3789      If so we can ignore all further global instances.
3790      This is to work around gold/15646, inefficient gold-generated
3791      indices.  */
3792   int global_seen;
3793 };
3794
3795 /* Initialize the index symtab iterator ITER.
3796    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3797    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3798
3799 static void
3800 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3801                       struct mapped_index *index,
3802                       int want_specific_block,
3803                       int block_index,
3804                       domain_enum domain,
3805                       const char *name)
3806 {
3807   iter->index = index;
3808   iter->want_specific_block = want_specific_block;
3809   iter->block_index = block_index;
3810   iter->domain = domain;
3811   iter->next = 0;
3812   iter->global_seen = 0;
3813
3814   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3815     iter->length = MAYBE_SWAP (*iter->vec);
3816   else
3817     {
3818       iter->vec = NULL;
3819       iter->length = 0;
3820     }
3821 }
3822
3823 /* Return the next matching CU or NULL if there are no more.  */
3824
3825 static struct dwarf2_per_cu_data *
3826 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3827 {
3828   for ( ; iter->next < iter->length; ++iter->next)
3829     {
3830       offset_type cu_index_and_attrs =
3831         MAYBE_SWAP (iter->vec[iter->next + 1]);
3832       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3833       struct dwarf2_per_cu_data *per_cu;
3834       int want_static = iter->block_index != GLOBAL_BLOCK;
3835       /* This value is only valid for index versions >= 7.  */
3836       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3837       gdb_index_symbol_kind symbol_kind =
3838         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3839       /* Only check the symbol attributes if they're present.
3840          Indices prior to version 7 don't record them,
3841          and indices >= 7 may elide them for certain symbols
3842          (gold does this).  */
3843       int attrs_valid =
3844         (iter->index->version >= 7
3845          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3846
3847       /* Don't crash on bad data.  */
3848       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3849                        + dwarf2_per_objfile->n_type_units))
3850         {
3851           complaint (&symfile_complaints,
3852                      _(".gdb_index entry has bad CU index"
3853                        " [in module %s]"),
3854                      objfile_name (dwarf2_per_objfile->objfile));
3855           continue;
3856         }
3857
3858       per_cu = dw2_get_cutu (cu_index);
3859
3860       /* Skip if already read in.  */
3861       if (per_cu->v.quick->compunit_symtab)
3862         continue;
3863
3864       /* Check static vs global.  */
3865       if (attrs_valid)
3866         {
3867           if (iter->want_specific_block
3868               && want_static != is_static)
3869             continue;
3870           /* Work around gold/15646.  */
3871           if (!is_static && iter->global_seen)
3872             continue;
3873           if (!is_static)
3874             iter->global_seen = 1;
3875         }
3876
3877       /* Only check the symbol's kind if it has one.  */
3878       if (attrs_valid)
3879         {
3880           switch (iter->domain)
3881             {
3882             case VAR_DOMAIN:
3883               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3884                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3885                   /* Some types are also in VAR_DOMAIN.  */
3886                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3887                 continue;
3888               break;
3889             case STRUCT_DOMAIN:
3890               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3891                 continue;
3892               break;
3893             case LABEL_DOMAIN:
3894               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3895                 continue;
3896               break;
3897             default:
3898               break;
3899             }
3900         }
3901
3902       ++iter->next;
3903       return per_cu;
3904     }
3905
3906   return NULL;
3907 }
3908
3909 static struct compunit_symtab *
3910 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3911                    const char *name, domain_enum domain)
3912 {
3913   struct compunit_symtab *stab_best = NULL;
3914   struct mapped_index *index;
3915
3916   dw2_setup (objfile);
3917
3918   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3919
3920   index = dwarf2_per_objfile->index_table;
3921
3922   /* index is NULL if OBJF_READNOW.  */
3923   if (index)
3924     {
3925       struct dw2_symtab_iterator iter;
3926       struct dwarf2_per_cu_data *per_cu;
3927
3928       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3929
3930       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3931         {
3932           struct symbol *sym, *with_opaque = NULL;
3933           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3934           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3935           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3936
3937           sym = block_find_symbol (block, name, domain,
3938                                    block_find_non_opaque_type_preferred,
3939                                    &with_opaque);
3940
3941           /* Some caution must be observed with overloaded functions
3942              and methods, since the index will not contain any overload
3943              information (but NAME might contain it).  */
3944
3945           if (sym != NULL
3946               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3947             return stab;
3948           if (with_opaque != NULL
3949               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3950             stab_best = stab;
3951
3952           /* Keep looking through other CUs.  */
3953         }
3954     }
3955
3956   return stab_best;
3957 }
3958
3959 static void
3960 dw2_print_stats (struct objfile *objfile)
3961 {
3962   int i, total, count;
3963
3964   dw2_setup (objfile);
3965   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3966   count = 0;
3967   for (i = 0; i < total; ++i)
3968     {
3969       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3970
3971       if (!per_cu->v.quick->compunit_symtab)
3972         ++count;
3973     }
3974   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3975   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3976 }
3977
3978 /* This dumps minimal information about the index.
3979    It is called via "mt print objfiles".
3980    One use is to verify .gdb_index has been loaded by the
3981    gdb.dwarf2/gdb-index.exp testcase.  */
3982
3983 static void
3984 dw2_dump (struct objfile *objfile)
3985 {
3986   dw2_setup (objfile);
3987   gdb_assert (dwarf2_per_objfile->using_index);
3988   printf_filtered (".gdb_index:");
3989   if (dwarf2_per_objfile->index_table != NULL)
3990     {
3991       printf_filtered (" version %d\n",
3992                        dwarf2_per_objfile->index_table->version);
3993     }
3994   else
3995     printf_filtered (" faked for \"readnow\"\n");
3996   printf_filtered ("\n");
3997 }
3998
3999 static void
4000 dw2_relocate (struct objfile *objfile,
4001               const struct section_offsets *new_offsets,
4002               const struct section_offsets *delta)
4003 {
4004   /* There's nothing to relocate here.  */
4005 }
4006
4007 static void
4008 dw2_expand_symtabs_for_function (struct objfile *objfile,
4009                                  const char *func_name)
4010 {
4011   struct mapped_index *index;
4012
4013   dw2_setup (objfile);
4014
4015   index = dwarf2_per_objfile->index_table;
4016
4017   /* index is NULL if OBJF_READNOW.  */
4018   if (index)
4019     {
4020       struct dw2_symtab_iterator iter;
4021       struct dwarf2_per_cu_data *per_cu;
4022
4023       /* Note: It doesn't matter what we pass for block_index here.  */
4024       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4025                             func_name);
4026
4027       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4028         dw2_instantiate_symtab (per_cu);
4029     }
4030 }
4031
4032 static void
4033 dw2_expand_all_symtabs (struct objfile *objfile)
4034 {
4035   int i;
4036
4037   dw2_setup (objfile);
4038
4039   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4040                    + dwarf2_per_objfile->n_type_units); ++i)
4041     {
4042       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4043
4044       dw2_instantiate_symtab (per_cu);
4045     }
4046 }
4047
4048 static void
4049 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4050                                   const char *fullname)
4051 {
4052   int i;
4053
4054   dw2_setup (objfile);
4055
4056   /* We don't need to consider type units here.
4057      This is only called for examining code, e.g. expand_line_sal.
4058      There can be an order of magnitude (or more) more type units
4059      than comp units, and we avoid them if we can.  */
4060
4061   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4062     {
4063       int j;
4064       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4065       struct quick_file_names *file_data;
4066
4067       /* We only need to look at symtabs not already expanded.  */
4068       if (per_cu->v.quick->compunit_symtab)
4069         continue;
4070
4071       file_data = dw2_get_file_names (per_cu);
4072       if (file_data == NULL)
4073         continue;
4074
4075       for (j = 0; j < file_data->num_file_names; ++j)
4076         {
4077           const char *this_fullname = file_data->file_names[j];
4078
4079           if (filename_cmp (this_fullname, fullname) == 0)
4080             {
4081               dw2_instantiate_symtab (per_cu);
4082               break;
4083             }
4084         }
4085     }
4086 }
4087
4088 static void
4089 dw2_map_matching_symbols (struct objfile *objfile,
4090                           const char * name, domain_enum domain,
4091                           int global,
4092                           int (*callback) (struct block *,
4093                                            struct symbol *, void *),
4094                           void *data, symbol_name_match_type match,
4095                           symbol_compare_ftype *ordered_compare)
4096 {
4097   /* Currently unimplemented; used for Ada.  The function can be called if the
4098      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4099      does not look for non-Ada symbols this function should just return.  */
4100 }
4101
4102 /* Symbol name matcher for .gdb_index names.
4103
4104    Symbol names in .gdb_index have a few particularities:
4105
4106    - There's no indication of which is the language of each symbol.
4107
4108      Since each language has its own symbol name matching algorithm,
4109      and we don't know which language is the right one, we must match
4110      each symbol against all languages.  This would be a potential
4111      performance problem if it were not mitigated by the
4112      mapped_index::name_components lookup table, which significantly
4113      reduces the number of times we need to call into this matcher,
4114      making it a non-issue.
4115
4116    - Symbol names in the index have no overload (parameter)
4117      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4118      appear as "foo" in the index, for example.
4119
4120      This means that the lookup names passed to the symbol name
4121      matcher functions must have no parameter information either
4122      because (e.g.) symbol search name "foo" does not match
4123      lookup-name "foo(int)" [while swapping search name for lookup
4124      name would match].
4125 */
4126 class gdb_index_symbol_name_matcher
4127 {
4128 public:
4129   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4130   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4131
4132   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4133      Returns true if any matcher matches.  */
4134   bool matches (const char *symbol_name);
4135
4136 private:
4137   /* A reference to the lookup name we're matching against.  */
4138   const lookup_name_info &m_lookup_name;
4139
4140   /* A vector holding all the different symbol name matchers, for all
4141      languages.  */
4142   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4143 };
4144
4145 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4146   (const lookup_name_info &lookup_name)
4147     : m_lookup_name (lookup_name)
4148 {
4149   /* Prepare the vector of comparison functions upfront, to avoid
4150      doing the same work for each symbol.  Care is taken to avoid
4151      matching with the same matcher more than once if/when multiple
4152      languages use the same matcher function.  */
4153   auto &matchers = m_symbol_name_matcher_funcs;
4154   matchers.reserve (nr_languages);
4155
4156   matchers.push_back (default_symbol_name_matcher);
4157
4158   for (int i = 0; i < nr_languages; i++)
4159     {
4160       const language_defn *lang = language_def ((enum language) i);
4161       if (lang->la_get_symbol_name_matcher != NULL)
4162         {
4163           symbol_name_matcher_ftype *name_matcher
4164             = lang->la_get_symbol_name_matcher (m_lookup_name);
4165
4166           /* Don't insert the same comparison routine more than once.
4167              Note that we do this linear walk instead of a cheaper
4168              sorted insert, or use a std::set or something like that,
4169              because relative order of function addresses is not
4170              stable.  This is not a problem in practice because the
4171              number of supported languages is low, and the cost here
4172              is tiny compared to the number of searches we'll do
4173              afterwards using this object.  */
4174           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4175               == matchers.end ())
4176             matchers.push_back (name_matcher);
4177         }
4178     }
4179 }
4180
4181 bool
4182 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4183 {
4184   for (auto matches_name : m_symbol_name_matcher_funcs)
4185     if (matches_name (symbol_name, m_lookup_name, NULL))
4186       return true;
4187
4188   return false;
4189 }
4190
4191 static void
4192 dw2_expand_marked_cus
4193   (mapped_index &index, offset_type idx,
4194    struct objfile *objfile,
4195    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4196    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4197    search_domain kind);
4198
4199 static void
4200 dw2_expand_symtabs_matching_symbol
4201   (mapped_index &index,
4202    const lookup_name_info &lookup_name_in,
4203    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4204    enum search_domain kind,
4205    gdb::function_view<void (offset_type)> on_match);
4206
4207 static void
4208 dw2_expand_symtabs_matching
4209   (struct objfile *objfile,
4210    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4211    const lookup_name_info &lookup_name,
4212    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4213    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4214    enum search_domain kind)
4215 {
4216   int i;
4217   offset_type iter;
4218
4219   dw2_setup (objfile);
4220
4221   /* index_table is NULL if OBJF_READNOW.  */
4222   if (!dwarf2_per_objfile->index_table)
4223     return;
4224
4225   if (file_matcher != NULL)
4226     {
4227       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4228                                                 htab_eq_pointer,
4229                                                 NULL, xcalloc, xfree));
4230       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4231                                                     htab_eq_pointer,
4232                                                     NULL, xcalloc, xfree));
4233
4234       /* The rule is CUs specify all the files, including those used by
4235          any TU, so there's no need to scan TUs here.  */
4236
4237       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4238         {
4239           int j;
4240           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4241           struct quick_file_names *file_data;
4242           void **slot;
4243
4244           QUIT;
4245
4246           per_cu->v.quick->mark = 0;
4247
4248           /* We only need to look at symtabs not already expanded.  */
4249           if (per_cu->v.quick->compunit_symtab)
4250             continue;
4251
4252           file_data = dw2_get_file_names (per_cu);
4253           if (file_data == NULL)
4254             continue;
4255
4256           if (htab_find (visited_not_found.get (), file_data) != NULL)
4257             continue;
4258           else if (htab_find (visited_found.get (), file_data) != NULL)
4259             {
4260               per_cu->v.quick->mark = 1;
4261               continue;
4262             }
4263
4264           for (j = 0; j < file_data->num_file_names; ++j)
4265             {
4266               const char *this_real_name;
4267
4268               if (file_matcher (file_data->file_names[j], false))
4269                 {
4270                   per_cu->v.quick->mark = 1;
4271                   break;
4272                 }
4273
4274               /* Before we invoke realpath, which can get expensive when many
4275                  files are involved, do a quick comparison of the basenames.  */
4276               if (!basenames_may_differ
4277                   && !file_matcher (lbasename (file_data->file_names[j]),
4278                                     true))
4279                 continue;
4280
4281               this_real_name = dw2_get_real_path (objfile, file_data, j);
4282               if (file_matcher (this_real_name, false))
4283                 {
4284                   per_cu->v.quick->mark = 1;
4285                   break;
4286                 }
4287             }
4288
4289           slot = htab_find_slot (per_cu->v.quick->mark
4290                                  ? visited_found.get ()
4291                                  : visited_not_found.get (),
4292                                  file_data, INSERT);
4293           *slot = file_data;
4294         }
4295     }
4296
4297   mapped_index &index = *dwarf2_per_objfile->index_table;
4298
4299   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4300                                       symbol_matcher,
4301                                       kind, [&] (offset_type idx)
4302     {
4303       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
4304                              expansion_notify, kind);
4305     });
4306 }
4307
4308 /* Helper for dw2_expand_symtabs_matching that works with a
4309    mapped_index instead of the containing objfile.  This is split to a
4310    separate function in order to be able to unit test the
4311    name_components matching using a mock mapped_index.  For each
4312    symbol name that matches, calls MATCH_CALLBACK, passing it the
4313    symbol's index in the mapped_index symbol table.  */
4314
4315 static void
4316 dw2_expand_symtabs_matching_symbol
4317   (mapped_index &index,
4318    const lookup_name_info &lookup_name,
4319    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4320    enum search_domain kind,
4321    gdb::function_view<void (offset_type)> match_callback)
4322 {
4323   gdb_index_symbol_name_matcher lookup_name_matcher
4324     (lookup_name);
4325
4326   auto *name_cmp = case_sensitivity == case_sensitive_on ? strcmp : strcasecmp;
4327
4328   /* Build the symbol name component sorted vector, if we haven't yet.
4329      The code below only knows how to break apart components of C++
4330      symbol names (and other languages that use '::' as
4331      namespace/module separator).  If we add support for wild matching
4332      to some language that uses some other operator (E.g., Ada, Go and
4333      D use '.'), then we'll need to try splitting the symbol name
4334      according to that language too.  Note that Ada does support wild
4335      matching, but doesn't currently support .gdb_index.  */
4336   if (index.name_components.empty ())
4337     {
4338       for (size_t iter = 0; iter < index.symbol_table_slots; ++iter)
4339         {
4340           offset_type idx = 2 * iter;
4341
4342           if (index.symbol_table[idx] == 0
4343               && index.symbol_table[idx + 1] == 0)
4344             continue;
4345
4346           const char *name = index.symbol_name_at (idx);
4347
4348           /* Add each name component to the name component table.  */
4349           unsigned int previous_len = 0;
4350           for (unsigned int current_len = cp_find_first_component (name);
4351                name[current_len] != '\0';
4352                current_len += cp_find_first_component (name + current_len))
4353             {
4354               gdb_assert (name[current_len] == ':');
4355               index.name_components.push_back ({previous_len, idx});
4356               /* Skip the '::'.  */
4357               current_len += 2;
4358               previous_len = current_len;
4359             }
4360           index.name_components.push_back ({previous_len, idx});
4361         }
4362
4363       /* Sort name_components elements by name.  */
4364       auto name_comp_compare = [&] (const name_component &left,
4365                                     const name_component &right)
4366         {
4367           const char *left_qualified = index.symbol_name_at (left.idx);
4368           const char *right_qualified = index.symbol_name_at (right.idx);
4369
4370           const char *left_name = left_qualified + left.name_offset;
4371           const char *right_name = right_qualified + right.name_offset;
4372
4373           return name_cmp (left_name, right_name) < 0;
4374         };
4375
4376       std::sort (index.name_components.begin (),
4377                  index.name_components.end (),
4378                  name_comp_compare);
4379     }
4380
4381   const char *cplus
4382     = lookup_name.cplus ().lookup_name ().c_str ();
4383
4384   /* Comparison function object for lower_bound that matches against a
4385      given symbol name.  */
4386   auto lookup_compare_lower = [&] (const name_component &elem,
4387                                    const char *name)
4388     {
4389       const char *elem_qualified = index.symbol_name_at (elem.idx);
4390       const char *elem_name = elem_qualified + elem.name_offset;
4391       return name_cmp (elem_name, name) < 0;
4392     };
4393
4394   /* Comparison function object for upper_bound that matches against a
4395      given symbol name.  */
4396   auto lookup_compare_upper = [&] (const char *name,
4397                                    const name_component &elem)
4398     {
4399       const char *elem_qualified = index.symbol_name_at (elem.idx);
4400       const char *elem_name = elem_qualified + elem.name_offset;
4401       return name_cmp (name, elem_name) < 0;
4402     };
4403
4404   auto begin = index.name_components.begin ();
4405   auto end = index.name_components.end ();
4406
4407   /* Find the lower bound.  */
4408   auto lower = [&] ()
4409     {
4410       if (lookup_name.completion_mode () && cplus[0] == '\0')
4411         return begin;
4412       else
4413         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4414     } ();
4415
4416   /* Find the upper bound.  */
4417   auto upper = [&] ()
4418     {
4419       if (lookup_name.completion_mode ())
4420         {
4421           /* The string frobbing below won't work if the string is
4422              empty.  We don't need it then, anyway -- if we're
4423              completing an empty string, then we want to iterate over
4424              the whole range.  */
4425           if (cplus[0] == '\0')
4426             return end;
4427
4428           /* In completion mode, increment the last character because
4429              we want UPPER to point past all symbols names that have
4430              the same prefix.  */
4431           std::string after = cplus;
4432
4433           gdb_assert (after.back () != 0xff);
4434           after.back ()++;
4435
4436           return std::upper_bound (lower, end, after.c_str (),
4437                                    lookup_compare_upper);
4438         }
4439       else
4440         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4441     } ();
4442
4443   /* Now for each symbol name in range, check to see if we have a name
4444      match, and if so, call the MATCH_CALLBACK callback.  */
4445
4446   /* The same symbol may appear more than once in the range though.
4447      E.g., if we're looking for symbols that complete "w", and we have
4448      a symbol named "w1::w2", we'll find the two name components for
4449      that same symbol in the range.  To be sure we only call the
4450      callback once per symbol, we first collect the symbol name
4451      indexes that matched in a temporary vector and ignore
4452      duplicates.  */
4453   std::vector<offset_type> matches;
4454   matches.reserve (std::distance (lower, upper));
4455
4456   for (;lower != upper; ++lower)
4457     {
4458       const char *qualified = index.symbol_name_at (lower->idx);
4459
4460       if (!lookup_name_matcher.matches (qualified)
4461           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4462         continue;
4463
4464       matches.push_back (lower->idx);
4465     }
4466
4467   std::sort (matches.begin (), matches.end ());
4468
4469   /* Finally call the callback, once per match.  */
4470   ULONGEST prev = -1;
4471   for (offset_type idx : matches)
4472     {
4473       if (prev != idx)
4474         {
4475           match_callback (idx);
4476           prev = idx;
4477         }
4478     }
4479
4480   /* Above we use a type wider than idx's for 'prev', since 0 and
4481      (offset_type)-1 are both possible values.  */
4482   static_assert (sizeof (prev) > sizeof (offset_type), "");
4483 }
4484
4485 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4486    matched, to expand corresponding CUs that were marked.  IDX is the
4487    index of the symbol name that matched.  */
4488
4489 static void
4490 dw2_expand_marked_cus
4491   (mapped_index &index, offset_type idx,
4492    struct objfile *objfile,
4493    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4494    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4495    search_domain kind)
4496 {
4497   const char *name;
4498   offset_type *vec, vec_len, vec_idx;
4499   bool global_seen = false;
4500
4501       vec = (offset_type *) (index.constant_pool
4502                              + MAYBE_SWAP (index.symbol_table[idx + 1]));
4503       vec_len = MAYBE_SWAP (vec[0]);
4504       for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4505         {
4506           struct dwarf2_per_cu_data *per_cu;
4507           offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4508           /* This value is only valid for index versions >= 7.  */
4509           int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4510           gdb_index_symbol_kind symbol_kind =
4511             GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4512           int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4513           /* Only check the symbol attributes if they're present.
4514              Indices prior to version 7 don't record them,
4515              and indices >= 7 may elide them for certain symbols
4516              (gold does this).  */
4517           int attrs_valid =
4518             (index.version >= 7
4519              && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4520
4521           /* Work around gold/15646.  */
4522           if (attrs_valid)
4523             {
4524               if (!is_static && global_seen)
4525                 continue;
4526               if (!is_static)
4527                 global_seen = true;
4528             }
4529
4530           /* Only check the symbol's kind if it has one.  */
4531           if (attrs_valid)
4532             {
4533               switch (kind)
4534                 {
4535                 case VARIABLES_DOMAIN:
4536                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4537                     continue;
4538                   break;
4539                 case FUNCTIONS_DOMAIN:
4540                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4541                     continue;
4542                   break;
4543                 case TYPES_DOMAIN:
4544                   if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4545                     continue;
4546                   break;
4547                 default:
4548                   break;
4549                 }
4550             }
4551
4552           /* Don't crash on bad data.  */
4553           if (cu_index >= (dwarf2_per_objfile->n_comp_units
4554                            + dwarf2_per_objfile->n_type_units))
4555             {
4556               complaint (&symfile_complaints,
4557                          _(".gdb_index entry has bad CU index"
4558                            " [in module %s]"), objfile_name (objfile));
4559               continue;
4560             }
4561
4562           per_cu = dw2_get_cutu (cu_index);
4563           if (file_matcher == NULL || per_cu->v.quick->mark)
4564             {
4565               int symtab_was_null =
4566                 (per_cu->v.quick->compunit_symtab == NULL);
4567
4568               dw2_instantiate_symtab (per_cu);
4569
4570               if (expansion_notify != NULL
4571                   && symtab_was_null
4572                   && per_cu->v.quick->compunit_symtab != NULL)
4573                 {
4574                   expansion_notify (per_cu->v.quick->compunit_symtab);
4575                 }
4576             }
4577         }
4578 }
4579
4580 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4581    symtab.  */
4582
4583 static struct compunit_symtab *
4584 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4585                                           CORE_ADDR pc)
4586 {
4587   int i;
4588
4589   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4590       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4591     return cust;
4592
4593   if (cust->includes == NULL)
4594     return NULL;
4595
4596   for (i = 0; cust->includes[i]; ++i)
4597     {
4598       struct compunit_symtab *s = cust->includes[i];
4599
4600       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4601       if (s != NULL)
4602         return s;
4603     }
4604
4605   return NULL;
4606 }
4607
4608 static struct compunit_symtab *
4609 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4610                                   struct bound_minimal_symbol msymbol,
4611                                   CORE_ADDR pc,
4612                                   struct obj_section *section,
4613                                   int warn_if_readin)
4614 {
4615   struct dwarf2_per_cu_data *data;
4616   struct compunit_symtab *result;
4617
4618   dw2_setup (objfile);
4619
4620   if (!objfile->psymtabs_addrmap)
4621     return NULL;
4622
4623   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4624                                                      pc);
4625   if (!data)
4626     return NULL;
4627
4628   if (warn_if_readin && data->v.quick->compunit_symtab)
4629     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4630              paddress (get_objfile_arch (objfile), pc));
4631
4632   result
4633     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4634                                                 pc);
4635   gdb_assert (result != NULL);
4636   return result;
4637 }
4638
4639 static void
4640 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4641                           void *data, int need_fullname)
4642 {
4643   dw2_setup (objfile);
4644
4645   if (!dwarf2_per_objfile->filenames_cache)
4646     {
4647       dwarf2_per_objfile->filenames_cache.emplace ();
4648
4649       htab_up visited (htab_create_alloc (10,
4650                                           htab_hash_pointer, htab_eq_pointer,
4651                                           NULL, xcalloc, xfree));
4652
4653       /* The rule is CUs specify all the files, including those used
4654          by any TU, so there's no need to scan TUs here.  We can
4655          ignore file names coming from already-expanded CUs.  */
4656
4657       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4658         {
4659           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4660
4661           if (per_cu->v.quick->compunit_symtab)
4662             {
4663               void **slot = htab_find_slot (visited.get (),
4664                                             per_cu->v.quick->file_names,
4665                                             INSERT);
4666
4667               *slot = per_cu->v.quick->file_names;
4668             }
4669         }
4670
4671       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4672         {
4673           int j;
4674           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4675           struct quick_file_names *file_data;
4676           void **slot;
4677
4678           /* We only need to look at symtabs not already expanded.  */
4679           if (per_cu->v.quick->compunit_symtab)
4680             continue;
4681
4682           file_data = dw2_get_file_names (per_cu);
4683           if (file_data == NULL)
4684             continue;
4685
4686           slot = htab_find_slot (visited.get (), file_data, INSERT);
4687           if (*slot)
4688             {
4689               /* Already visited.  */
4690               continue;
4691             }
4692           *slot = file_data;
4693
4694           for (int j = 0; j < file_data->num_file_names; ++j)
4695             {
4696               const char *filename = file_data->file_names[j];
4697               dwarf2_per_objfile->filenames_cache->seen (filename);
4698             }
4699         }
4700     }
4701
4702   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4703     {
4704       gdb::unique_xmalloc_ptr<char> this_real_name;
4705
4706       if (need_fullname)
4707         this_real_name = gdb_realpath (filename);
4708       (*fun) (filename, this_real_name.get (), data);
4709     });
4710 }
4711
4712 static int
4713 dw2_has_symbols (struct objfile *objfile)
4714 {
4715   return 1;
4716 }
4717
4718 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4719 {
4720   dw2_has_symbols,
4721   dw2_find_last_source_symtab,
4722   dw2_forget_cached_source_info,
4723   dw2_map_symtabs_matching_filename,
4724   dw2_lookup_symbol,
4725   dw2_print_stats,
4726   dw2_dump,
4727   dw2_relocate,
4728   dw2_expand_symtabs_for_function,
4729   dw2_expand_all_symtabs,
4730   dw2_expand_symtabs_with_fullname,
4731   dw2_map_matching_symbols,
4732   dw2_expand_symtabs_matching,
4733   dw2_find_pc_sect_compunit_symtab,
4734   dw2_map_symbol_filenames
4735 };
4736
4737 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4738    file will use psymtabs, or 1 if using the GNU index.  */
4739
4740 int
4741 dwarf2_initialize_objfile (struct objfile *objfile)
4742 {
4743   /* If we're about to read full symbols, don't bother with the
4744      indices.  In this case we also don't care if some other debug
4745      format is making psymtabs, because they are all about to be
4746      expanded anyway.  */
4747   if ((objfile->flags & OBJF_READNOW))
4748     {
4749       int i;
4750
4751       dwarf2_per_objfile->using_index = 1;
4752       create_all_comp_units (objfile);
4753       create_all_type_units (objfile);
4754       dwarf2_per_objfile->quick_file_names_table =
4755         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4756
4757       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4758                        + dwarf2_per_objfile->n_type_units); ++i)
4759         {
4760           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4761
4762           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4763                                             struct dwarf2_per_cu_quick_data);
4764         }
4765
4766       /* Return 1 so that gdb sees the "quick" functions.  However,
4767          these functions will be no-ops because we will have expanded
4768          all symtabs.  */
4769       return 1;
4770     }
4771
4772   if (dwarf2_read_index (objfile))
4773     return 1;
4774
4775   return 0;
4776 }
4777
4778 \f
4779
4780 /* Build a partial symbol table.  */
4781
4782 void
4783 dwarf2_build_psymtabs (struct objfile *objfile)
4784 {
4785
4786   if (objfile->global_psymbols.capacity () == 0
4787       && objfile->static_psymbols.capacity () == 0)
4788     init_psymbol_list (objfile, 1024);
4789
4790   TRY
4791     {
4792       /* This isn't really ideal: all the data we allocate on the
4793          objfile's obstack is still uselessly kept around.  However,
4794          freeing it seems unsafe.  */
4795       psymtab_discarder psymtabs (objfile);
4796       dwarf2_build_psymtabs_hard (objfile);
4797       psymtabs.keep ();
4798     }
4799   CATCH (except, RETURN_MASK_ERROR)
4800     {
4801       exception_print (gdb_stderr, except);
4802     }
4803   END_CATCH
4804 }
4805
4806 /* Return the total length of the CU described by HEADER.  */
4807
4808 static unsigned int
4809 get_cu_length (const struct comp_unit_head *header)
4810 {
4811   return header->initial_length_size + header->length;
4812 }
4813
4814 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4815
4816 static inline bool
4817 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4818 {
4819   sect_offset bottom = cu_header->sect_off;
4820   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4821
4822   return sect_off >= bottom && sect_off < top;
4823 }
4824
4825 /* Find the base address of the compilation unit for range lists and
4826    location lists.  It will normally be specified by DW_AT_low_pc.
4827    In DWARF-3 draft 4, the base address could be overridden by
4828    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4829    compilation units with discontinuous ranges.  */
4830
4831 static void
4832 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4833 {
4834   struct attribute *attr;
4835
4836   cu->base_known = 0;
4837   cu->base_address = 0;
4838
4839   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4840   if (attr)
4841     {
4842       cu->base_address = attr_value_as_address (attr);
4843       cu->base_known = 1;
4844     }
4845   else
4846     {
4847       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4848       if (attr)
4849         {
4850           cu->base_address = attr_value_as_address (attr);
4851           cu->base_known = 1;
4852         }
4853     }
4854 }
4855
4856 /* Read in the comp unit header information from the debug_info at info_ptr.
4857    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4858    NOTE: This leaves members offset, first_die_offset to be filled in
4859    by the caller.  */
4860
4861 static const gdb_byte *
4862 read_comp_unit_head (struct comp_unit_head *cu_header,
4863                      const gdb_byte *info_ptr,
4864                      struct dwarf2_section_info *section,
4865                      rcuh_kind section_kind)
4866 {
4867   int signed_addr;
4868   unsigned int bytes_read;
4869   const char *filename = get_section_file_name (section);
4870   bfd *abfd = get_section_bfd_owner (section);
4871
4872   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4873   cu_header->initial_length_size = bytes_read;
4874   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4875   info_ptr += bytes_read;
4876   cu_header->version = read_2_bytes (abfd, info_ptr);
4877   info_ptr += 2;
4878   if (cu_header->version < 5)
4879     switch (section_kind)
4880       {
4881       case rcuh_kind::COMPILE:
4882         cu_header->unit_type = DW_UT_compile;
4883         break;
4884       case rcuh_kind::TYPE:
4885         cu_header->unit_type = DW_UT_type;
4886         break;
4887       default:
4888         internal_error (__FILE__, __LINE__,
4889                         _("read_comp_unit_head: invalid section_kind"));
4890       }
4891   else
4892     {
4893       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4894                                                  (read_1_byte (abfd, info_ptr));
4895       info_ptr += 1;
4896       switch (cu_header->unit_type)
4897         {
4898         case DW_UT_compile:
4899           if (section_kind != rcuh_kind::COMPILE)
4900             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4901                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4902                    filename);
4903           break;
4904         case DW_UT_type:
4905           section_kind = rcuh_kind::TYPE;
4906           break;
4907         default:
4908           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4909                  "(is %d, should be %d or %d) [in module %s]"),
4910                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4911         }
4912
4913       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4914       info_ptr += 1;
4915     }
4916   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4917                                                           cu_header,
4918                                                           &bytes_read);
4919   info_ptr += bytes_read;
4920   if (cu_header->version < 5)
4921     {
4922       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4923       info_ptr += 1;
4924     }
4925   signed_addr = bfd_get_sign_extend_vma (abfd);
4926   if (signed_addr < 0)
4927     internal_error (__FILE__, __LINE__,
4928                     _("read_comp_unit_head: dwarf from non elf file"));
4929   cu_header->signed_addr_p = signed_addr;
4930
4931   if (section_kind == rcuh_kind::TYPE)
4932     {
4933       LONGEST type_offset;
4934
4935       cu_header->signature = read_8_bytes (abfd, info_ptr);
4936       info_ptr += 8;
4937
4938       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4939       info_ptr += bytes_read;
4940       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4941       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4942         error (_("Dwarf Error: Too big type_offset in compilation unit "
4943                "header (is %s) [in module %s]"), plongest (type_offset),
4944                filename);
4945     }
4946
4947   return info_ptr;
4948 }
4949
4950 /* Helper function that returns the proper abbrev section for
4951    THIS_CU.  */
4952
4953 static struct dwarf2_section_info *
4954 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4955 {
4956   struct dwarf2_section_info *abbrev;
4957
4958   if (this_cu->is_dwz)
4959     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4960   else
4961     abbrev = &dwarf2_per_objfile->abbrev;
4962
4963   return abbrev;
4964 }
4965
4966 /* Subroutine of read_and_check_comp_unit_head and
4967    read_and_check_type_unit_head to simplify them.
4968    Perform various error checking on the header.  */
4969
4970 static void
4971 error_check_comp_unit_head (struct comp_unit_head *header,
4972                             struct dwarf2_section_info *section,
4973                             struct dwarf2_section_info *abbrev_section)
4974 {
4975   const char *filename = get_section_file_name (section);
4976
4977   if (header->version < 2 || header->version > 5)
4978     error (_("Dwarf Error: wrong version in compilation unit header "
4979            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4980            filename);
4981
4982   if (to_underlying (header->abbrev_sect_off)
4983       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4984     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4985            "(offset 0x%x + 6) [in module %s]"),
4986            to_underlying (header->abbrev_sect_off),
4987            to_underlying (header->sect_off),
4988            filename);
4989
4990   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4991      avoid potential 32-bit overflow.  */
4992   if (((ULONGEST) header->sect_off + get_cu_length (header))
4993       > section->size)
4994     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4995            "(offset 0x%x + 0) [in module %s]"),
4996            header->length, to_underlying (header->sect_off),
4997            filename);
4998 }
4999
5000 /* Read in a CU/TU header and perform some basic error checking.
5001    The contents of the header are stored in HEADER.
5002    The result is a pointer to the start of the first DIE.  */
5003
5004 static const gdb_byte *
5005 read_and_check_comp_unit_head (struct comp_unit_head *header,
5006                                struct dwarf2_section_info *section,
5007                                struct dwarf2_section_info *abbrev_section,
5008                                const gdb_byte *info_ptr,
5009                                rcuh_kind section_kind)
5010 {
5011   const gdb_byte *beg_of_comp_unit = info_ptr;
5012   bfd *abfd = get_section_bfd_owner (section);
5013
5014   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
5015
5016   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
5017
5018   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5019
5020   error_check_comp_unit_head (header, section, abbrev_section);
5021
5022   return info_ptr;
5023 }
5024
5025 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5026
5027 static sect_offset
5028 read_abbrev_offset (struct dwarf2_section_info *section,
5029                     sect_offset sect_off)
5030 {
5031   bfd *abfd = get_section_bfd_owner (section);
5032   const gdb_byte *info_ptr;
5033   unsigned int initial_length_size, offset_size;
5034   uint16_t version;
5035
5036   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5037   info_ptr = section->buffer + to_underlying (sect_off);
5038   read_initial_length (abfd, info_ptr, &initial_length_size);
5039   offset_size = initial_length_size == 4 ? 4 : 8;
5040   info_ptr += initial_length_size;
5041
5042   version = read_2_bytes (abfd, info_ptr);
5043   info_ptr += 2;
5044   if (version >= 5)
5045     {
5046       /* Skip unit type and address size.  */
5047       info_ptr += 2;
5048     }
5049
5050   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5051 }
5052
5053 /* Allocate a new partial symtab for file named NAME and mark this new
5054    partial symtab as being an include of PST.  */
5055
5056 static void
5057 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5058                                struct objfile *objfile)
5059 {
5060   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5061
5062   if (!IS_ABSOLUTE_PATH (subpst->filename))
5063     {
5064       /* It shares objfile->objfile_obstack.  */
5065       subpst->dirname = pst->dirname;
5066     }
5067
5068   subpst->textlow = 0;
5069   subpst->texthigh = 0;
5070
5071   subpst->dependencies
5072     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5073   subpst->dependencies[0] = pst;
5074   subpst->number_of_dependencies = 1;
5075
5076   subpst->globals_offset = 0;
5077   subpst->n_global_syms = 0;
5078   subpst->statics_offset = 0;
5079   subpst->n_static_syms = 0;
5080   subpst->compunit_symtab = NULL;
5081   subpst->read_symtab = pst->read_symtab;
5082   subpst->readin = 0;
5083
5084   /* No private part is necessary for include psymtabs.  This property
5085      can be used to differentiate between such include psymtabs and
5086      the regular ones.  */
5087   subpst->read_symtab_private = NULL;
5088 }
5089
5090 /* Read the Line Number Program data and extract the list of files
5091    included by the source file represented by PST.  Build an include
5092    partial symtab for each of these included files.  */
5093
5094 static void
5095 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5096                                struct die_info *die,
5097                                struct partial_symtab *pst)
5098 {
5099   line_header_up lh;
5100   struct attribute *attr;
5101
5102   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5103   if (attr)
5104     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5105   if (lh == NULL)
5106     return;  /* No linetable, so no includes.  */
5107
5108   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5109   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5110 }
5111
5112 static hashval_t
5113 hash_signatured_type (const void *item)
5114 {
5115   const struct signatured_type *sig_type
5116     = (const struct signatured_type *) item;
5117
5118   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5119   return sig_type->signature;
5120 }
5121
5122 static int
5123 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5124 {
5125   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5126   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5127
5128   return lhs->signature == rhs->signature;
5129 }
5130
5131 /* Allocate a hash table for signatured types.  */
5132
5133 static htab_t
5134 allocate_signatured_type_table (struct objfile *objfile)
5135 {
5136   return htab_create_alloc_ex (41,
5137                                hash_signatured_type,
5138                                eq_signatured_type,
5139                                NULL,
5140                                &objfile->objfile_obstack,
5141                                hashtab_obstack_allocate,
5142                                dummy_obstack_deallocate);
5143 }
5144
5145 /* A helper function to add a signatured type CU to a table.  */
5146
5147 static int
5148 add_signatured_type_cu_to_table (void **slot, void *datum)
5149 {
5150   struct signatured_type *sigt = (struct signatured_type *) *slot;
5151   struct signatured_type ***datap = (struct signatured_type ***) datum;
5152
5153   **datap = sigt;
5154   ++*datap;
5155
5156   return 1;
5157 }
5158
5159 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5160    and fill them into TYPES_HTAB.  It will process only type units,
5161    therefore DW_UT_type.  */
5162
5163 static void
5164 create_debug_type_hash_table (struct dwo_file *dwo_file,
5165                               dwarf2_section_info *section, htab_t &types_htab,
5166                               rcuh_kind section_kind)
5167 {
5168   struct objfile *objfile = dwarf2_per_objfile->objfile;
5169   struct dwarf2_section_info *abbrev_section;
5170   bfd *abfd;
5171   const gdb_byte *info_ptr, *end_ptr;
5172
5173   abbrev_section = (dwo_file != NULL
5174                     ? &dwo_file->sections.abbrev
5175                     : &dwarf2_per_objfile->abbrev);
5176
5177   if (dwarf_read_debug)
5178     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5179                         get_section_name (section),
5180                         get_section_file_name (abbrev_section));
5181
5182   dwarf2_read_section (objfile, section);
5183   info_ptr = section->buffer;
5184
5185   if (info_ptr == NULL)
5186     return;
5187
5188   /* We can't set abfd until now because the section may be empty or
5189      not present, in which case the bfd is unknown.  */
5190   abfd = get_section_bfd_owner (section);
5191
5192   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5193      because we don't need to read any dies: the signature is in the
5194      header.  */
5195
5196   end_ptr = info_ptr + section->size;
5197   while (info_ptr < end_ptr)
5198     {
5199       struct signatured_type *sig_type;
5200       struct dwo_unit *dwo_tu;
5201       void **slot;
5202       const gdb_byte *ptr = info_ptr;
5203       struct comp_unit_head header;
5204       unsigned int length;
5205
5206       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5207
5208       /* Initialize it due to a false compiler warning.  */
5209       header.signature = -1;
5210       header.type_cu_offset_in_tu = (cu_offset) -1;
5211
5212       /* We need to read the type's signature in order to build the hash
5213          table, but we don't need anything else just yet.  */
5214
5215       ptr = read_and_check_comp_unit_head (&header, section,
5216                                            abbrev_section, ptr, section_kind);
5217
5218       length = get_cu_length (&header);
5219
5220       /* Skip dummy type units.  */
5221       if (ptr >= info_ptr + length
5222           || peek_abbrev_code (abfd, ptr) == 0
5223           || header.unit_type != DW_UT_type)
5224         {
5225           info_ptr += length;
5226           continue;
5227         }
5228
5229       if (types_htab == NULL)
5230         {
5231           if (dwo_file)
5232             types_htab = allocate_dwo_unit_table (objfile);
5233           else
5234             types_htab = allocate_signatured_type_table (objfile);
5235         }
5236
5237       if (dwo_file)
5238         {
5239           sig_type = NULL;
5240           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5241                                    struct dwo_unit);
5242           dwo_tu->dwo_file = dwo_file;
5243           dwo_tu->signature = header.signature;
5244           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5245           dwo_tu->section = section;
5246           dwo_tu->sect_off = sect_off;
5247           dwo_tu->length = length;
5248         }
5249       else
5250         {
5251           /* N.B.: type_offset is not usable if this type uses a DWO file.
5252              The real type_offset is in the DWO file.  */
5253           dwo_tu = NULL;
5254           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5255                                      struct signatured_type);
5256           sig_type->signature = header.signature;
5257           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5258           sig_type->per_cu.objfile = objfile;
5259           sig_type->per_cu.is_debug_types = 1;
5260           sig_type->per_cu.section = section;
5261           sig_type->per_cu.sect_off = sect_off;
5262           sig_type->per_cu.length = length;
5263         }
5264
5265       slot = htab_find_slot (types_htab,
5266                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5267                              INSERT);
5268       gdb_assert (slot != NULL);
5269       if (*slot != NULL)
5270         {
5271           sect_offset dup_sect_off;
5272
5273           if (dwo_file)
5274             {
5275               const struct dwo_unit *dup_tu
5276                 = (const struct dwo_unit *) *slot;
5277
5278               dup_sect_off = dup_tu->sect_off;
5279             }
5280           else
5281             {
5282               const struct signatured_type *dup_tu
5283                 = (const struct signatured_type *) *slot;
5284
5285               dup_sect_off = dup_tu->per_cu.sect_off;
5286             }
5287
5288           complaint (&symfile_complaints,
5289                      _("debug type entry at offset 0x%x is duplicate to"
5290                        " the entry at offset 0x%x, signature %s"),
5291                      to_underlying (sect_off), to_underlying (dup_sect_off),
5292                      hex_string (header.signature));
5293         }
5294       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5295
5296       if (dwarf_read_debug > 1)
5297         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5298                             to_underlying (sect_off),
5299                             hex_string (header.signature));
5300
5301       info_ptr += length;
5302     }
5303 }
5304
5305 /* Create the hash table of all entries in the .debug_types
5306    (or .debug_types.dwo) section(s).
5307    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5308    otherwise it is NULL.
5309
5310    The result is a pointer to the hash table or NULL if there are no types.
5311
5312    Note: This function processes DWO files only, not DWP files.  */
5313
5314 static void
5315 create_debug_types_hash_table (struct dwo_file *dwo_file,
5316                                VEC (dwarf2_section_info_def) *types,
5317                                htab_t &types_htab)
5318 {
5319   int ix;
5320   struct dwarf2_section_info *section;
5321
5322   if (VEC_empty (dwarf2_section_info_def, types))
5323     return;
5324
5325   for (ix = 0;
5326        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5327        ++ix)
5328     create_debug_type_hash_table (dwo_file, section, types_htab,
5329                                   rcuh_kind::TYPE);
5330 }
5331
5332 /* Create the hash table of all entries in the .debug_types section,
5333    and initialize all_type_units.
5334    The result is zero if there is an error (e.g. missing .debug_types section),
5335    otherwise non-zero.  */
5336
5337 static int
5338 create_all_type_units (struct objfile *objfile)
5339 {
5340   htab_t types_htab = NULL;
5341   struct signatured_type **iter;
5342
5343   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5344                                 rcuh_kind::COMPILE);
5345   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5346   if (types_htab == NULL)
5347     {
5348       dwarf2_per_objfile->signatured_types = NULL;
5349       return 0;
5350     }
5351
5352   dwarf2_per_objfile->signatured_types = types_htab;
5353
5354   dwarf2_per_objfile->n_type_units
5355     = dwarf2_per_objfile->n_allocated_type_units
5356     = htab_elements (types_htab);
5357   dwarf2_per_objfile->all_type_units =
5358     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5359   iter = &dwarf2_per_objfile->all_type_units[0];
5360   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5361   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5362               == dwarf2_per_objfile->n_type_units);
5363
5364   return 1;
5365 }
5366
5367 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5368    If SLOT is non-NULL, it is the entry to use in the hash table.
5369    Otherwise we find one.  */
5370
5371 static struct signatured_type *
5372 add_type_unit (ULONGEST sig, void **slot)
5373 {
5374   struct objfile *objfile = dwarf2_per_objfile->objfile;
5375   int n_type_units = dwarf2_per_objfile->n_type_units;
5376   struct signatured_type *sig_type;
5377
5378   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5379   ++n_type_units;
5380   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5381     {
5382       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5383         dwarf2_per_objfile->n_allocated_type_units = 1;
5384       dwarf2_per_objfile->n_allocated_type_units *= 2;
5385       dwarf2_per_objfile->all_type_units
5386         = XRESIZEVEC (struct signatured_type *,
5387                       dwarf2_per_objfile->all_type_units,
5388                       dwarf2_per_objfile->n_allocated_type_units);
5389       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5390     }
5391   dwarf2_per_objfile->n_type_units = n_type_units;
5392
5393   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5394                              struct signatured_type);
5395   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5396   sig_type->signature = sig;
5397   sig_type->per_cu.is_debug_types = 1;
5398   if (dwarf2_per_objfile->using_index)
5399     {
5400       sig_type->per_cu.v.quick =
5401         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5402                         struct dwarf2_per_cu_quick_data);
5403     }
5404
5405   if (slot == NULL)
5406     {
5407       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5408                              sig_type, INSERT);
5409     }
5410   gdb_assert (*slot == NULL);
5411   *slot = sig_type;
5412   /* The rest of sig_type must be filled in by the caller.  */
5413   return sig_type;
5414 }
5415
5416 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5417    Fill in SIG_ENTRY with DWO_ENTRY.  */
5418
5419 static void
5420 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5421                                   struct signatured_type *sig_entry,
5422                                   struct dwo_unit *dwo_entry)
5423 {
5424   /* Make sure we're not clobbering something we don't expect to.  */
5425   gdb_assert (! sig_entry->per_cu.queued);
5426   gdb_assert (sig_entry->per_cu.cu == NULL);
5427   if (dwarf2_per_objfile->using_index)
5428     {
5429       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5430       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5431     }
5432   else
5433       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5434   gdb_assert (sig_entry->signature == dwo_entry->signature);
5435   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5436   gdb_assert (sig_entry->type_unit_group == NULL);
5437   gdb_assert (sig_entry->dwo_unit == NULL);
5438
5439   sig_entry->per_cu.section = dwo_entry->section;
5440   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5441   sig_entry->per_cu.length = dwo_entry->length;
5442   sig_entry->per_cu.reading_dwo_directly = 1;
5443   sig_entry->per_cu.objfile = objfile;
5444   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5445   sig_entry->dwo_unit = dwo_entry;
5446 }
5447
5448 /* Subroutine of lookup_signatured_type.
5449    If we haven't read the TU yet, create the signatured_type data structure
5450    for a TU to be read in directly from a DWO file, bypassing the stub.
5451    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5452    using .gdb_index, then when reading a CU we want to stay in the DWO file
5453    containing that CU.  Otherwise we could end up reading several other DWO
5454    files (due to comdat folding) to process the transitive closure of all the
5455    mentioned TUs, and that can be slow.  The current DWO file will have every
5456    type signature that it needs.
5457    We only do this for .gdb_index because in the psymtab case we already have
5458    to read all the DWOs to build the type unit groups.  */
5459
5460 static struct signatured_type *
5461 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5462 {
5463   struct objfile *objfile = dwarf2_per_objfile->objfile;
5464   struct dwo_file *dwo_file;
5465   struct dwo_unit find_dwo_entry, *dwo_entry;
5466   struct signatured_type find_sig_entry, *sig_entry;
5467   void **slot;
5468
5469   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5470
5471   /* If TU skeletons have been removed then we may not have read in any
5472      TUs yet.  */
5473   if (dwarf2_per_objfile->signatured_types == NULL)
5474     {
5475       dwarf2_per_objfile->signatured_types
5476         = allocate_signatured_type_table (objfile);
5477     }
5478
5479   /* We only ever need to read in one copy of a signatured type.
5480      Use the global signatured_types array to do our own comdat-folding
5481      of types.  If this is the first time we're reading this TU, and
5482      the TU has an entry in .gdb_index, replace the recorded data from
5483      .gdb_index with this TU.  */
5484
5485   find_sig_entry.signature = sig;
5486   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5487                          &find_sig_entry, INSERT);
5488   sig_entry = (struct signatured_type *) *slot;
5489
5490   /* We can get here with the TU already read, *or* in the process of being
5491      read.  Don't reassign the global entry to point to this DWO if that's
5492      the case.  Also note that if the TU is already being read, it may not
5493      have come from a DWO, the program may be a mix of Fission-compiled
5494      code and non-Fission-compiled code.  */
5495
5496   /* Have we already tried to read this TU?
5497      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5498      needn't exist in the global table yet).  */
5499   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5500     return sig_entry;
5501
5502   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5503      dwo_unit of the TU itself.  */
5504   dwo_file = cu->dwo_unit->dwo_file;
5505
5506   /* Ok, this is the first time we're reading this TU.  */
5507   if (dwo_file->tus == NULL)
5508     return NULL;
5509   find_dwo_entry.signature = sig;
5510   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5511   if (dwo_entry == NULL)
5512     return NULL;
5513
5514   /* If the global table doesn't have an entry for this TU, add one.  */
5515   if (sig_entry == NULL)
5516     sig_entry = add_type_unit (sig, slot);
5517
5518   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5519   sig_entry->per_cu.tu_read = 1;
5520   return sig_entry;
5521 }
5522
5523 /* Subroutine of lookup_signatured_type.
5524    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5525    then try the DWP file.  If the TU stub (skeleton) has been removed then
5526    it won't be in .gdb_index.  */
5527
5528 static struct signatured_type *
5529 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5530 {
5531   struct objfile *objfile = dwarf2_per_objfile->objfile;
5532   struct dwp_file *dwp_file = get_dwp_file ();
5533   struct dwo_unit *dwo_entry;
5534   struct signatured_type find_sig_entry, *sig_entry;
5535   void **slot;
5536
5537   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5538   gdb_assert (dwp_file != NULL);
5539
5540   /* If TU skeletons have been removed then we may not have read in any
5541      TUs yet.  */
5542   if (dwarf2_per_objfile->signatured_types == NULL)
5543     {
5544       dwarf2_per_objfile->signatured_types
5545         = allocate_signatured_type_table (objfile);
5546     }
5547
5548   find_sig_entry.signature = sig;
5549   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5550                          &find_sig_entry, INSERT);
5551   sig_entry = (struct signatured_type *) *slot;
5552
5553   /* Have we already tried to read this TU?
5554      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5555      needn't exist in the global table yet).  */
5556   if (sig_entry != NULL)
5557     return sig_entry;
5558
5559   if (dwp_file->tus == NULL)
5560     return NULL;
5561   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5562                                       sig, 1 /* is_debug_types */);
5563   if (dwo_entry == NULL)
5564     return NULL;
5565
5566   sig_entry = add_type_unit (sig, slot);
5567   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5568
5569   return sig_entry;
5570 }
5571
5572 /* Lookup a signature based type for DW_FORM_ref_sig8.
5573    Returns NULL if signature SIG is not present in the table.
5574    It is up to the caller to complain about this.  */
5575
5576 static struct signatured_type *
5577 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5578 {
5579   if (cu->dwo_unit
5580       && dwarf2_per_objfile->using_index)
5581     {
5582       /* We're in a DWO/DWP file, and we're using .gdb_index.
5583          These cases require special processing.  */
5584       if (get_dwp_file () == NULL)
5585         return lookup_dwo_signatured_type (cu, sig);
5586       else
5587         return lookup_dwp_signatured_type (cu, sig);
5588     }
5589   else
5590     {
5591       struct signatured_type find_entry, *entry;
5592
5593       if (dwarf2_per_objfile->signatured_types == NULL)
5594         return NULL;
5595       find_entry.signature = sig;
5596       entry = ((struct signatured_type *)
5597                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5598       return entry;
5599     }
5600 }
5601 \f
5602 /* Low level DIE reading support.  */
5603
5604 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5605
5606 static void
5607 init_cu_die_reader (struct die_reader_specs *reader,
5608                     struct dwarf2_cu *cu,
5609                     struct dwarf2_section_info *section,
5610                     struct dwo_file *dwo_file)
5611 {
5612   gdb_assert (section->readin && section->buffer != NULL);
5613   reader->abfd = get_section_bfd_owner (section);
5614   reader->cu = cu;
5615   reader->dwo_file = dwo_file;
5616   reader->die_section = section;
5617   reader->buffer = section->buffer;
5618   reader->buffer_end = section->buffer + section->size;
5619   reader->comp_dir = NULL;
5620 }
5621
5622 /* Subroutine of init_cutu_and_read_dies to simplify it.
5623    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5624    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5625    already.
5626
5627    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5628    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5629    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5630    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5631    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5632    STUB_COMP_DIR may be non-NULL.
5633    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5634    are filled in with the info of the DIE from the DWO file.
5635    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5636    provided an abbrev table to use.
5637    The result is non-zero if a valid (non-dummy) DIE was found.  */
5638
5639 static int
5640 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5641                         struct dwo_unit *dwo_unit,
5642                         int abbrev_table_provided,
5643                         struct die_info *stub_comp_unit_die,
5644                         const char *stub_comp_dir,
5645                         struct die_reader_specs *result_reader,
5646                         const gdb_byte **result_info_ptr,
5647                         struct die_info **result_comp_unit_die,
5648                         int *result_has_children)
5649 {
5650   struct objfile *objfile = dwarf2_per_objfile->objfile;
5651   struct dwarf2_cu *cu = this_cu->cu;
5652   struct dwarf2_section_info *section;
5653   bfd *abfd;
5654   const gdb_byte *begin_info_ptr, *info_ptr;
5655   ULONGEST signature; /* Or dwo_id.  */
5656   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5657   int i,num_extra_attrs;
5658   struct dwarf2_section_info *dwo_abbrev_section;
5659   struct attribute *attr;
5660   struct die_info *comp_unit_die;
5661
5662   /* At most one of these may be provided.  */
5663   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5664
5665   /* These attributes aren't processed until later:
5666      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5667      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5668      referenced later.  However, these attributes are found in the stub
5669      which we won't have later.  In order to not impose this complication
5670      on the rest of the code, we read them here and copy them to the
5671      DWO CU/TU die.  */
5672
5673   stmt_list = NULL;
5674   low_pc = NULL;
5675   high_pc = NULL;
5676   ranges = NULL;
5677   comp_dir = NULL;
5678
5679   if (stub_comp_unit_die != NULL)
5680     {
5681       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5682          DWO file.  */
5683       if (! this_cu->is_debug_types)
5684         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5685       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5686       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5687       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5688       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5689
5690       /* There should be a DW_AT_addr_base attribute here (if needed).
5691          We need the value before we can process DW_FORM_GNU_addr_index.  */
5692       cu->addr_base = 0;
5693       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5694       if (attr)
5695         cu->addr_base = DW_UNSND (attr);
5696
5697       /* There should be a DW_AT_ranges_base attribute here (if needed).
5698          We need the value before we can process DW_AT_ranges.  */
5699       cu->ranges_base = 0;
5700       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5701       if (attr)
5702         cu->ranges_base = DW_UNSND (attr);
5703     }
5704   else if (stub_comp_dir != NULL)
5705     {
5706       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5707       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5708       comp_dir->name = DW_AT_comp_dir;
5709       comp_dir->form = DW_FORM_string;
5710       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5711       DW_STRING (comp_dir) = stub_comp_dir;
5712     }
5713
5714   /* Set up for reading the DWO CU/TU.  */
5715   cu->dwo_unit = dwo_unit;
5716   section = dwo_unit->section;
5717   dwarf2_read_section (objfile, section);
5718   abfd = get_section_bfd_owner (section);
5719   begin_info_ptr = info_ptr = (section->buffer
5720                                + to_underlying (dwo_unit->sect_off));
5721   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5722   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5723
5724   if (this_cu->is_debug_types)
5725     {
5726       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5727
5728       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5729                                                 dwo_abbrev_section,
5730                                                 info_ptr, rcuh_kind::TYPE);
5731       /* This is not an assert because it can be caused by bad debug info.  */
5732       if (sig_type->signature != cu->header.signature)
5733         {
5734           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5735                    " TU at offset 0x%x [in module %s]"),
5736                  hex_string (sig_type->signature),
5737                  hex_string (cu->header.signature),
5738                  to_underlying (dwo_unit->sect_off),
5739                  bfd_get_filename (abfd));
5740         }
5741       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5742       /* For DWOs coming from DWP files, we don't know the CU length
5743          nor the type's offset in the TU until now.  */
5744       dwo_unit->length = get_cu_length (&cu->header);
5745       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5746
5747       /* Establish the type offset that can be used to lookup the type.
5748          For DWO files, we don't know it until now.  */
5749       sig_type->type_offset_in_section
5750         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5751     }
5752   else
5753     {
5754       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5755                                                 dwo_abbrev_section,
5756                                                 info_ptr, rcuh_kind::COMPILE);
5757       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5758       /* For DWOs coming from DWP files, we don't know the CU length
5759          until now.  */
5760       dwo_unit->length = get_cu_length (&cu->header);
5761     }
5762
5763   /* Replace the CU's original abbrev table with the DWO's.
5764      Reminder: We can't read the abbrev table until we've read the header.  */
5765   if (abbrev_table_provided)
5766     {
5767       /* Don't free the provided abbrev table, the caller of
5768          init_cutu_and_read_dies owns it.  */
5769       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5770       /* Ensure the DWO abbrev table gets freed.  */
5771       make_cleanup (dwarf2_free_abbrev_table, cu);
5772     }
5773   else
5774     {
5775       dwarf2_free_abbrev_table (cu);
5776       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5777       /* Leave any existing abbrev table cleanup as is.  */
5778     }
5779
5780   /* Read in the die, but leave space to copy over the attributes
5781      from the stub.  This has the benefit of simplifying the rest of
5782      the code - all the work to maintain the illusion of a single
5783      DW_TAG_{compile,type}_unit DIE is done here.  */
5784   num_extra_attrs = ((stmt_list != NULL)
5785                      + (low_pc != NULL)
5786                      + (high_pc != NULL)
5787                      + (ranges != NULL)
5788                      + (comp_dir != NULL));
5789   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5790                               result_has_children, num_extra_attrs);
5791
5792   /* Copy over the attributes from the stub to the DIE we just read in.  */
5793   comp_unit_die = *result_comp_unit_die;
5794   i = comp_unit_die->num_attrs;
5795   if (stmt_list != NULL)
5796     comp_unit_die->attrs[i++] = *stmt_list;
5797   if (low_pc != NULL)
5798     comp_unit_die->attrs[i++] = *low_pc;
5799   if (high_pc != NULL)
5800     comp_unit_die->attrs[i++] = *high_pc;
5801   if (ranges != NULL)
5802     comp_unit_die->attrs[i++] = *ranges;
5803   if (comp_dir != NULL)
5804     comp_unit_die->attrs[i++] = *comp_dir;
5805   comp_unit_die->num_attrs += num_extra_attrs;
5806
5807   if (dwarf_die_debug)
5808     {
5809       fprintf_unfiltered (gdb_stdlog,
5810                           "Read die from %s@0x%x of %s:\n",
5811                           get_section_name (section),
5812                           (unsigned) (begin_info_ptr - section->buffer),
5813                           bfd_get_filename (abfd));
5814       dump_die (comp_unit_die, dwarf_die_debug);
5815     }
5816
5817   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5818      TUs by skipping the stub and going directly to the entry in the DWO file.
5819      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5820      to get it via circuitous means.  Blech.  */
5821   if (comp_dir != NULL)
5822     result_reader->comp_dir = DW_STRING (comp_dir);
5823
5824   /* Skip dummy compilation units.  */
5825   if (info_ptr >= begin_info_ptr + dwo_unit->length
5826       || peek_abbrev_code (abfd, info_ptr) == 0)
5827     return 0;
5828
5829   *result_info_ptr = info_ptr;
5830   return 1;
5831 }
5832
5833 /* Subroutine of init_cutu_and_read_dies to simplify it.
5834    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5835    Returns NULL if the specified DWO unit cannot be found.  */
5836
5837 static struct dwo_unit *
5838 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5839                  struct die_info *comp_unit_die)
5840 {
5841   struct dwarf2_cu *cu = this_cu->cu;
5842   struct attribute *attr;
5843   ULONGEST signature;
5844   struct dwo_unit *dwo_unit;
5845   const char *comp_dir, *dwo_name;
5846
5847   gdb_assert (cu != NULL);
5848
5849   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5850   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5851   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5852
5853   if (this_cu->is_debug_types)
5854     {
5855       struct signatured_type *sig_type;
5856
5857       /* Since this_cu is the first member of struct signatured_type,
5858          we can go from a pointer to one to a pointer to the other.  */
5859       sig_type = (struct signatured_type *) this_cu;
5860       signature = sig_type->signature;
5861       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5862     }
5863   else
5864     {
5865       struct attribute *attr;
5866
5867       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5868       if (! attr)
5869         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5870                  " [in module %s]"),
5871                dwo_name, objfile_name (this_cu->objfile));
5872       signature = DW_UNSND (attr);
5873       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5874                                        signature);
5875     }
5876
5877   return dwo_unit;
5878 }
5879
5880 /* Subroutine of init_cutu_and_read_dies to simplify it.
5881    See it for a description of the parameters.
5882    Read a TU directly from a DWO file, bypassing the stub.
5883
5884    Note: This function could be a little bit simpler if we shared cleanups
5885    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5886    to do, so we keep this function self-contained.  Or we could move this
5887    into our caller, but it's complex enough already.  */
5888
5889 static void
5890 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5891                            int use_existing_cu, int keep,
5892                            die_reader_func_ftype *die_reader_func,
5893                            void *data)
5894 {
5895   struct dwarf2_cu *cu;
5896   struct signatured_type *sig_type;
5897   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5898   struct die_reader_specs reader;
5899   const gdb_byte *info_ptr;
5900   struct die_info *comp_unit_die;
5901   int has_children;
5902
5903   /* Verify we can do the following downcast, and that we have the
5904      data we need.  */
5905   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5906   sig_type = (struct signatured_type *) this_cu;
5907   gdb_assert (sig_type->dwo_unit != NULL);
5908
5909   cleanups = make_cleanup (null_cleanup, NULL);
5910
5911   if (use_existing_cu && this_cu->cu != NULL)
5912     {
5913       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5914       cu = this_cu->cu;
5915       /* There's no need to do the rereading_dwo_cu handling that
5916          init_cutu_and_read_dies does since we don't read the stub.  */
5917     }
5918   else
5919     {
5920       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5921       gdb_assert (this_cu->cu == NULL);
5922       cu = XNEW (struct dwarf2_cu);
5923       init_one_comp_unit (cu, this_cu);
5924       /* If an error occurs while loading, release our storage.  */
5925       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5926     }
5927
5928   /* A future optimization, if needed, would be to use an existing
5929      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5930      could share abbrev tables.  */
5931
5932   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5933                               0 /* abbrev_table_provided */,
5934                               NULL /* stub_comp_unit_die */,
5935                               sig_type->dwo_unit->dwo_file->comp_dir,
5936                               &reader, &info_ptr,
5937                               &comp_unit_die, &has_children) == 0)
5938     {
5939       /* Dummy die.  */
5940       do_cleanups (cleanups);
5941       return;
5942     }
5943
5944   /* All the "real" work is done here.  */
5945   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5946
5947   /* This duplicates the code in init_cutu_and_read_dies,
5948      but the alternative is making the latter more complex.
5949      This function is only for the special case of using DWO files directly:
5950      no point in overly complicating the general case just to handle this.  */
5951   if (free_cu_cleanup != NULL)
5952     {
5953       if (keep)
5954         {
5955           /* We've successfully allocated this compilation unit.  Let our
5956              caller clean it up when finished with it.  */
5957           discard_cleanups (free_cu_cleanup);
5958
5959           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5960              So we have to manually free the abbrev table.  */
5961           dwarf2_free_abbrev_table (cu);
5962
5963           /* Link this CU into read_in_chain.  */
5964           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5965           dwarf2_per_objfile->read_in_chain = this_cu;
5966         }
5967       else
5968         do_cleanups (free_cu_cleanup);
5969     }
5970
5971   do_cleanups (cleanups);
5972 }
5973
5974 /* Initialize a CU (or TU) and read its DIEs.
5975    If the CU defers to a DWO file, read the DWO file as well.
5976
5977    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5978    Otherwise the table specified in the comp unit header is read in and used.
5979    This is an optimization for when we already have the abbrev table.
5980
5981    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5982    Otherwise, a new CU is allocated with xmalloc.
5983
5984    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5985    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5986
5987    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5988    linker) then DIE_READER_FUNC will not get called.  */
5989
5990 static void
5991 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5992                          struct abbrev_table *abbrev_table,
5993                          int use_existing_cu, int keep,
5994                          die_reader_func_ftype *die_reader_func,
5995                          void *data)
5996 {
5997   struct objfile *objfile = dwarf2_per_objfile->objfile;
5998   struct dwarf2_section_info *section = this_cu->section;
5999   bfd *abfd = get_section_bfd_owner (section);
6000   struct dwarf2_cu *cu;
6001   const gdb_byte *begin_info_ptr, *info_ptr;
6002   struct die_reader_specs reader;
6003   struct die_info *comp_unit_die;
6004   int has_children;
6005   struct attribute *attr;
6006   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6007   struct signatured_type *sig_type = NULL;
6008   struct dwarf2_section_info *abbrev_section;
6009   /* Non-zero if CU currently points to a DWO file and we need to
6010      reread it.  When this happens we need to reread the skeleton die
6011      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6012   int rereading_dwo_cu = 0;
6013
6014   if (dwarf_die_debug)
6015     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6016                         this_cu->is_debug_types ? "type" : "comp",
6017                         to_underlying (this_cu->sect_off));
6018
6019   if (use_existing_cu)
6020     gdb_assert (keep);
6021
6022   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6023      file (instead of going through the stub), short-circuit all of this.  */
6024   if (this_cu->reading_dwo_directly)
6025     {
6026       /* Narrow down the scope of possibilities to have to understand.  */
6027       gdb_assert (this_cu->is_debug_types);
6028       gdb_assert (abbrev_table == NULL);
6029       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6030                                  die_reader_func, data);
6031       return;
6032     }
6033
6034   cleanups = make_cleanup (null_cleanup, NULL);
6035
6036   /* This is cheap if the section is already read in.  */
6037   dwarf2_read_section (objfile, section);
6038
6039   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6040
6041   abbrev_section = get_abbrev_section_for_cu (this_cu);
6042
6043   if (use_existing_cu && this_cu->cu != NULL)
6044     {
6045       cu = this_cu->cu;
6046       /* If this CU is from a DWO file we need to start over, we need to
6047          refetch the attributes from the skeleton CU.
6048          This could be optimized by retrieving those attributes from when we
6049          were here the first time: the previous comp_unit_die was stored in
6050          comp_unit_obstack.  But there's no data yet that we need this
6051          optimization.  */
6052       if (cu->dwo_unit != NULL)
6053         rereading_dwo_cu = 1;
6054     }
6055   else
6056     {
6057       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6058       gdb_assert (this_cu->cu == NULL);
6059       cu = XNEW (struct dwarf2_cu);
6060       init_one_comp_unit (cu, this_cu);
6061       /* If an error occurs while loading, release our storage.  */
6062       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6063     }
6064
6065   /* Get the header.  */
6066   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6067     {
6068       /* We already have the header, there's no need to read it in again.  */
6069       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6070     }
6071   else
6072     {
6073       if (this_cu->is_debug_types)
6074         {
6075           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6076                                                     abbrev_section, info_ptr,
6077                                                     rcuh_kind::TYPE);
6078
6079           /* Since per_cu is the first member of struct signatured_type,
6080              we can go from a pointer to one to a pointer to the other.  */
6081           sig_type = (struct signatured_type *) this_cu;
6082           gdb_assert (sig_type->signature == cu->header.signature);
6083           gdb_assert (sig_type->type_offset_in_tu
6084                       == cu->header.type_cu_offset_in_tu);
6085           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6086
6087           /* LENGTH has not been set yet for type units if we're
6088              using .gdb_index.  */
6089           this_cu->length = get_cu_length (&cu->header);
6090
6091           /* Establish the type offset that can be used to lookup the type.  */
6092           sig_type->type_offset_in_section =
6093             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6094
6095           this_cu->dwarf_version = cu->header.version;
6096         }
6097       else
6098         {
6099           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6100                                                     abbrev_section,
6101                                                     info_ptr,
6102                                                     rcuh_kind::COMPILE);
6103
6104           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6105           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6106           this_cu->dwarf_version = cu->header.version;
6107         }
6108     }
6109
6110   /* Skip dummy compilation units.  */
6111   if (info_ptr >= begin_info_ptr + this_cu->length
6112       || peek_abbrev_code (abfd, info_ptr) == 0)
6113     {
6114       do_cleanups (cleanups);
6115       return;
6116     }
6117
6118   /* If we don't have them yet, read the abbrevs for this compilation unit.
6119      And if we need to read them now, make sure they're freed when we're
6120      done.  Note that it's important that if the CU had an abbrev table
6121      on entry we don't free it when we're done: Somewhere up the call stack
6122      it may be in use.  */
6123   if (abbrev_table != NULL)
6124     {
6125       gdb_assert (cu->abbrev_table == NULL);
6126       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6127       cu->abbrev_table = abbrev_table;
6128     }
6129   else if (cu->abbrev_table == NULL)
6130     {
6131       dwarf2_read_abbrevs (cu, abbrev_section);
6132       make_cleanup (dwarf2_free_abbrev_table, cu);
6133     }
6134   else if (rereading_dwo_cu)
6135     {
6136       dwarf2_free_abbrev_table (cu);
6137       dwarf2_read_abbrevs (cu, abbrev_section);
6138     }
6139
6140   /* Read the top level CU/TU die.  */
6141   init_cu_die_reader (&reader, cu, section, NULL);
6142   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6143
6144   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6145      from the DWO file.
6146      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6147      DWO CU, that this test will fail (the attribute will not be present).  */
6148   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6149   if (attr)
6150     {
6151       struct dwo_unit *dwo_unit;
6152       struct die_info *dwo_comp_unit_die;
6153
6154       if (has_children)
6155         {
6156           complaint (&symfile_complaints,
6157                      _("compilation unit with DW_AT_GNU_dwo_name"
6158                        " has children (offset 0x%x) [in module %s]"),
6159                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6160         }
6161       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6162       if (dwo_unit != NULL)
6163         {
6164           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6165                                       abbrev_table != NULL,
6166                                       comp_unit_die, NULL,
6167                                       &reader, &info_ptr,
6168                                       &dwo_comp_unit_die, &has_children) == 0)
6169             {
6170               /* Dummy die.  */
6171               do_cleanups (cleanups);
6172               return;
6173             }
6174           comp_unit_die = dwo_comp_unit_die;
6175         }
6176       else
6177         {
6178           /* Yikes, we couldn't find the rest of the DIE, we only have
6179              the stub.  A complaint has already been logged.  There's
6180              not much more we can do except pass on the stub DIE to
6181              die_reader_func.  We don't want to throw an error on bad
6182              debug info.  */
6183         }
6184     }
6185
6186   /* All of the above is setup for this call.  Yikes.  */
6187   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6188
6189   /* Done, clean up.  */
6190   if (free_cu_cleanup != NULL)
6191     {
6192       if (keep)
6193         {
6194           /* We've successfully allocated this compilation unit.  Let our
6195              caller clean it up when finished with it.  */
6196           discard_cleanups (free_cu_cleanup);
6197
6198           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6199              So we have to manually free the abbrev table.  */
6200           dwarf2_free_abbrev_table (cu);
6201
6202           /* Link this CU into read_in_chain.  */
6203           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6204           dwarf2_per_objfile->read_in_chain = this_cu;
6205         }
6206       else
6207         do_cleanups (free_cu_cleanup);
6208     }
6209
6210   do_cleanups (cleanups);
6211 }
6212
6213 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6214    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6215    to have already done the lookup to find the DWO file).
6216
6217    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6218    THIS_CU->is_debug_types, but nothing else.
6219
6220    We fill in THIS_CU->length.
6221
6222    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6223    linker) then DIE_READER_FUNC will not get called.
6224
6225    THIS_CU->cu is always freed when done.
6226    This is done in order to not leave THIS_CU->cu in a state where we have
6227    to care whether it refers to the "main" CU or the DWO CU.  */
6228
6229 static void
6230 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6231                                    struct dwo_file *dwo_file,
6232                                    die_reader_func_ftype *die_reader_func,
6233                                    void *data)
6234 {
6235   struct objfile *objfile = dwarf2_per_objfile->objfile;
6236   struct dwarf2_section_info *section = this_cu->section;
6237   bfd *abfd = get_section_bfd_owner (section);
6238   struct dwarf2_section_info *abbrev_section;
6239   struct dwarf2_cu cu;
6240   const gdb_byte *begin_info_ptr, *info_ptr;
6241   struct die_reader_specs reader;
6242   struct cleanup *cleanups;
6243   struct die_info *comp_unit_die;
6244   int has_children;
6245
6246   if (dwarf_die_debug)
6247     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6248                         this_cu->is_debug_types ? "type" : "comp",
6249                         to_underlying (this_cu->sect_off));
6250
6251   gdb_assert (this_cu->cu == NULL);
6252
6253   abbrev_section = (dwo_file != NULL
6254                     ? &dwo_file->sections.abbrev
6255                     : get_abbrev_section_for_cu (this_cu));
6256
6257   /* This is cheap if the section is already read in.  */
6258   dwarf2_read_section (objfile, section);
6259
6260   init_one_comp_unit (&cu, this_cu);
6261
6262   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6263
6264   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6265   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6266                                             abbrev_section, info_ptr,
6267                                             (this_cu->is_debug_types
6268                                              ? rcuh_kind::TYPE
6269                                              : rcuh_kind::COMPILE));
6270
6271   this_cu->length = get_cu_length (&cu.header);
6272
6273   /* Skip dummy compilation units.  */
6274   if (info_ptr >= begin_info_ptr + this_cu->length
6275       || peek_abbrev_code (abfd, info_ptr) == 0)
6276     {
6277       do_cleanups (cleanups);
6278       return;
6279     }
6280
6281   dwarf2_read_abbrevs (&cu, abbrev_section);
6282   make_cleanup (dwarf2_free_abbrev_table, &cu);
6283
6284   init_cu_die_reader (&reader, &cu, section, dwo_file);
6285   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6286
6287   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6288
6289   do_cleanups (cleanups);
6290 }
6291
6292 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6293    does not lookup the specified DWO file.
6294    This cannot be used to read DWO files.
6295
6296    THIS_CU->cu is always freed when done.
6297    This is done in order to not leave THIS_CU->cu in a state where we have
6298    to care whether it refers to the "main" CU or the DWO CU.
6299    We can revisit this if the data shows there's a performance issue.  */
6300
6301 static void
6302 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6303                                 die_reader_func_ftype *die_reader_func,
6304                                 void *data)
6305 {
6306   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6307 }
6308 \f
6309 /* Type Unit Groups.
6310
6311    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6312    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6313    so that all types coming from the same compilation (.o file) are grouped
6314    together.  A future step could be to put the types in the same symtab as
6315    the CU the types ultimately came from.  */
6316
6317 static hashval_t
6318 hash_type_unit_group (const void *item)
6319 {
6320   const struct type_unit_group *tu_group
6321     = (const struct type_unit_group *) item;
6322
6323   return hash_stmt_list_entry (&tu_group->hash);
6324 }
6325
6326 static int
6327 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6328 {
6329   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6330   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6331
6332   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6333 }
6334
6335 /* Allocate a hash table for type unit groups.  */
6336
6337 static htab_t
6338 allocate_type_unit_groups_table (void)
6339 {
6340   return htab_create_alloc_ex (3,
6341                                hash_type_unit_group,
6342                                eq_type_unit_group,
6343                                NULL,
6344                                &dwarf2_per_objfile->objfile->objfile_obstack,
6345                                hashtab_obstack_allocate,
6346                                dummy_obstack_deallocate);
6347 }
6348
6349 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6350    partial symtabs.  We combine several TUs per psymtab to not let the size
6351    of any one psymtab grow too big.  */
6352 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6353 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6354
6355 /* Helper routine for get_type_unit_group.
6356    Create the type_unit_group object used to hold one or more TUs.  */
6357
6358 static struct type_unit_group *
6359 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6360 {
6361   struct objfile *objfile = dwarf2_per_objfile->objfile;
6362   struct dwarf2_per_cu_data *per_cu;
6363   struct type_unit_group *tu_group;
6364
6365   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6366                              struct type_unit_group);
6367   per_cu = &tu_group->per_cu;
6368   per_cu->objfile = objfile;
6369
6370   if (dwarf2_per_objfile->using_index)
6371     {
6372       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6373                                         struct dwarf2_per_cu_quick_data);
6374     }
6375   else
6376     {
6377       unsigned int line_offset = to_underlying (line_offset_struct);
6378       struct partial_symtab *pst;
6379       char *name;
6380
6381       /* Give the symtab a useful name for debug purposes.  */
6382       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6383         name = xstrprintf ("<type_units_%d>",
6384                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6385       else
6386         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6387
6388       pst = create_partial_symtab (per_cu, name);
6389       pst->anonymous = 1;
6390
6391       xfree (name);
6392     }
6393
6394   tu_group->hash.dwo_unit = cu->dwo_unit;
6395   tu_group->hash.line_sect_off = line_offset_struct;
6396
6397   return tu_group;
6398 }
6399
6400 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6401    STMT_LIST is a DW_AT_stmt_list attribute.  */
6402
6403 static struct type_unit_group *
6404 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6405 {
6406   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6407   struct type_unit_group *tu_group;
6408   void **slot;
6409   unsigned int line_offset;
6410   struct type_unit_group type_unit_group_for_lookup;
6411
6412   if (dwarf2_per_objfile->type_unit_groups == NULL)
6413     {
6414       dwarf2_per_objfile->type_unit_groups =
6415         allocate_type_unit_groups_table ();
6416     }
6417
6418   /* Do we need to create a new group, or can we use an existing one?  */
6419
6420   if (stmt_list)
6421     {
6422       line_offset = DW_UNSND (stmt_list);
6423       ++tu_stats->nr_symtab_sharers;
6424     }
6425   else
6426     {
6427       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6428          We can do various things here like create one group per TU or
6429          spread them over multiple groups to split up the expansion work.
6430          To avoid worst case scenarios (too many groups or too large groups)
6431          we, umm, group them in bunches.  */
6432       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6433                      | (tu_stats->nr_stmt_less_type_units
6434                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6435       ++tu_stats->nr_stmt_less_type_units;
6436     }
6437
6438   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6439   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6440   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6441                          &type_unit_group_for_lookup, INSERT);
6442   if (*slot != NULL)
6443     {
6444       tu_group = (struct type_unit_group *) *slot;
6445       gdb_assert (tu_group != NULL);
6446     }
6447   else
6448     {
6449       sect_offset line_offset_struct = (sect_offset) line_offset;
6450       tu_group = create_type_unit_group (cu, line_offset_struct);
6451       *slot = tu_group;
6452       ++tu_stats->nr_symtabs;
6453     }
6454
6455   return tu_group;
6456 }
6457 \f
6458 /* Partial symbol tables.  */
6459
6460 /* Create a psymtab named NAME and assign it to PER_CU.
6461
6462    The caller must fill in the following details:
6463    dirname, textlow, texthigh.  */
6464
6465 static struct partial_symtab *
6466 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6467 {
6468   struct objfile *objfile = per_cu->objfile;
6469   struct partial_symtab *pst;
6470
6471   pst = start_psymtab_common (objfile, name, 0,
6472                               objfile->global_psymbols,
6473                               objfile->static_psymbols);
6474
6475   pst->psymtabs_addrmap_supported = 1;
6476
6477   /* This is the glue that links PST into GDB's symbol API.  */
6478   pst->read_symtab_private = per_cu;
6479   pst->read_symtab = dwarf2_read_symtab;
6480   per_cu->v.psymtab = pst;
6481
6482   return pst;
6483 }
6484
6485 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6486    type.  */
6487
6488 struct process_psymtab_comp_unit_data
6489 {
6490   /* True if we are reading a DW_TAG_partial_unit.  */
6491
6492   int want_partial_unit;
6493
6494   /* The "pretend" language that is used if the CU doesn't declare a
6495      language.  */
6496
6497   enum language pretend_language;
6498 };
6499
6500 /* die_reader_func for process_psymtab_comp_unit.  */
6501
6502 static void
6503 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6504                                   const gdb_byte *info_ptr,
6505                                   struct die_info *comp_unit_die,
6506                                   int has_children,
6507                                   void *data)
6508 {
6509   struct dwarf2_cu *cu = reader->cu;
6510   struct objfile *objfile = cu->objfile;
6511   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6512   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6513   CORE_ADDR baseaddr;
6514   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6515   struct partial_symtab *pst;
6516   enum pc_bounds_kind cu_bounds_kind;
6517   const char *filename;
6518   struct process_psymtab_comp_unit_data *info
6519     = (struct process_psymtab_comp_unit_data *) data;
6520
6521   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6522     return;
6523
6524   gdb_assert (! per_cu->is_debug_types);
6525
6526   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6527
6528   cu->list_in_scope = &file_symbols;
6529
6530   /* Allocate a new partial symbol table structure.  */
6531   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6532   if (filename == NULL)
6533     filename = "";
6534
6535   pst = create_partial_symtab (per_cu, filename);
6536
6537   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6538   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6539
6540   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6541
6542   dwarf2_find_base_address (comp_unit_die, cu);
6543
6544   /* Possibly set the default values of LOWPC and HIGHPC from
6545      `DW_AT_ranges'.  */
6546   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6547                                          &best_highpc, cu, pst);
6548   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6549     /* Store the contiguous range if it is not empty; it can be empty for
6550        CUs with no code.  */
6551     addrmap_set_empty (objfile->psymtabs_addrmap,
6552                        gdbarch_adjust_dwarf2_addr (gdbarch,
6553                                                    best_lowpc + baseaddr),
6554                        gdbarch_adjust_dwarf2_addr (gdbarch,
6555                                                    best_highpc + baseaddr) - 1,
6556                        pst);
6557
6558   /* Check if comp unit has_children.
6559      If so, read the rest of the partial symbols from this comp unit.
6560      If not, there's no more debug_info for this comp unit.  */
6561   if (has_children)
6562     {
6563       struct partial_die_info *first_die;
6564       CORE_ADDR lowpc, highpc;
6565
6566       lowpc = ((CORE_ADDR) -1);
6567       highpc = ((CORE_ADDR) 0);
6568
6569       first_die = load_partial_dies (reader, info_ptr, 1);
6570
6571       scan_partial_symbols (first_die, &lowpc, &highpc,
6572                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6573
6574       /* If we didn't find a lowpc, set it to highpc to avoid
6575          complaints from `maint check'.  */
6576       if (lowpc == ((CORE_ADDR) -1))
6577         lowpc = highpc;
6578
6579       /* If the compilation unit didn't have an explicit address range,
6580          then use the information extracted from its child dies.  */
6581       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6582         {
6583           best_lowpc = lowpc;
6584           best_highpc = highpc;
6585         }
6586     }
6587   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6588   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6589
6590   end_psymtab_common (objfile, pst);
6591
6592   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6593     {
6594       int i;
6595       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6596       struct dwarf2_per_cu_data *iter;
6597
6598       /* Fill in 'dependencies' here; we fill in 'users' in a
6599          post-pass.  */
6600       pst->number_of_dependencies = len;
6601       pst->dependencies =
6602         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6603       for (i = 0;
6604            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6605                         i, iter);
6606            ++i)
6607         pst->dependencies[i] = iter->v.psymtab;
6608
6609       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6610     }
6611
6612   /* Get the list of files included in the current compilation unit,
6613      and build a psymtab for each of them.  */
6614   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6615
6616   if (dwarf_read_debug)
6617     {
6618       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6619
6620       fprintf_unfiltered (gdb_stdlog,
6621                           "Psymtab for %s unit @0x%x: %s - %s"
6622                           ", %d global, %d static syms\n",
6623                           per_cu->is_debug_types ? "type" : "comp",
6624                           to_underlying (per_cu->sect_off),
6625                           paddress (gdbarch, pst->textlow),
6626                           paddress (gdbarch, pst->texthigh),
6627                           pst->n_global_syms, pst->n_static_syms);
6628     }
6629 }
6630
6631 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6632    Process compilation unit THIS_CU for a psymtab.  */
6633
6634 static void
6635 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6636                            int want_partial_unit,
6637                            enum language pretend_language)
6638 {
6639   /* If this compilation unit was already read in, free the
6640      cached copy in order to read it in again.  This is
6641      necessary because we skipped some symbols when we first
6642      read in the compilation unit (see load_partial_dies).
6643      This problem could be avoided, but the benefit is unclear.  */
6644   if (this_cu->cu != NULL)
6645     free_one_cached_comp_unit (this_cu);
6646
6647   if (this_cu->is_debug_types)
6648     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6649                              NULL);
6650   else
6651     {
6652       process_psymtab_comp_unit_data info;
6653       info.want_partial_unit = want_partial_unit;
6654       info.pretend_language = pretend_language;
6655       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6656                                process_psymtab_comp_unit_reader, &info);
6657     }
6658
6659   /* Age out any secondary CUs.  */
6660   age_cached_comp_units ();
6661 }
6662
6663 /* Reader function for build_type_psymtabs.  */
6664
6665 static void
6666 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6667                             const gdb_byte *info_ptr,
6668                             struct die_info *type_unit_die,
6669                             int has_children,
6670                             void *data)
6671 {
6672   struct objfile *objfile = dwarf2_per_objfile->objfile;
6673   struct dwarf2_cu *cu = reader->cu;
6674   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6675   struct signatured_type *sig_type;
6676   struct type_unit_group *tu_group;
6677   struct attribute *attr;
6678   struct partial_die_info *first_die;
6679   CORE_ADDR lowpc, highpc;
6680   struct partial_symtab *pst;
6681
6682   gdb_assert (data == NULL);
6683   gdb_assert (per_cu->is_debug_types);
6684   sig_type = (struct signatured_type *) per_cu;
6685
6686   if (! has_children)
6687     return;
6688
6689   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6690   tu_group = get_type_unit_group (cu, attr);
6691
6692   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6693
6694   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6695   cu->list_in_scope = &file_symbols;
6696   pst = create_partial_symtab (per_cu, "");
6697   pst->anonymous = 1;
6698
6699   first_die = load_partial_dies (reader, info_ptr, 1);
6700
6701   lowpc = (CORE_ADDR) -1;
6702   highpc = (CORE_ADDR) 0;
6703   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6704
6705   end_psymtab_common (objfile, pst);
6706 }
6707
6708 /* Struct used to sort TUs by their abbreviation table offset.  */
6709
6710 struct tu_abbrev_offset
6711 {
6712   struct signatured_type *sig_type;
6713   sect_offset abbrev_offset;
6714 };
6715
6716 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6717
6718 static int
6719 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6720 {
6721   const struct tu_abbrev_offset * const *a
6722     = (const struct tu_abbrev_offset * const*) ap;
6723   const struct tu_abbrev_offset * const *b
6724     = (const struct tu_abbrev_offset * const*) bp;
6725   sect_offset aoff = (*a)->abbrev_offset;
6726   sect_offset boff = (*b)->abbrev_offset;
6727
6728   return (aoff > boff) - (aoff < boff);
6729 }
6730
6731 /* Efficiently read all the type units.
6732    This does the bulk of the work for build_type_psymtabs.
6733
6734    The efficiency is because we sort TUs by the abbrev table they use and
6735    only read each abbrev table once.  In one program there are 200K TUs
6736    sharing 8K abbrev tables.
6737
6738    The main purpose of this function is to support building the
6739    dwarf2_per_objfile->type_unit_groups table.
6740    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6741    can collapse the search space by grouping them by stmt_list.
6742    The savings can be significant, in the same program from above the 200K TUs
6743    share 8K stmt_list tables.
6744
6745    FUNC is expected to call get_type_unit_group, which will create the
6746    struct type_unit_group if necessary and add it to
6747    dwarf2_per_objfile->type_unit_groups.  */
6748
6749 static void
6750 build_type_psymtabs_1 (void)
6751 {
6752   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6753   struct cleanup *cleanups;
6754   struct abbrev_table *abbrev_table;
6755   sect_offset abbrev_offset;
6756   struct tu_abbrev_offset *sorted_by_abbrev;
6757   int i;
6758
6759   /* It's up to the caller to not call us multiple times.  */
6760   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6761
6762   if (dwarf2_per_objfile->n_type_units == 0)
6763     return;
6764
6765   /* TUs typically share abbrev tables, and there can be way more TUs than
6766      abbrev tables.  Sort by abbrev table to reduce the number of times we
6767      read each abbrev table in.
6768      Alternatives are to punt or to maintain a cache of abbrev tables.
6769      This is simpler and efficient enough for now.
6770
6771      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6772      symtab to use).  Typically TUs with the same abbrev offset have the same
6773      stmt_list value too so in practice this should work well.
6774
6775      The basic algorithm here is:
6776
6777       sort TUs by abbrev table
6778       for each TU with same abbrev table:
6779         read abbrev table if first user
6780         read TU top level DIE
6781           [IWBN if DWO skeletons had DW_AT_stmt_list]
6782         call FUNC  */
6783
6784   if (dwarf_read_debug)
6785     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6786
6787   /* Sort in a separate table to maintain the order of all_type_units
6788      for .gdb_index: TU indices directly index all_type_units.  */
6789   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6790                               dwarf2_per_objfile->n_type_units);
6791   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6792     {
6793       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6794
6795       sorted_by_abbrev[i].sig_type = sig_type;
6796       sorted_by_abbrev[i].abbrev_offset =
6797         read_abbrev_offset (sig_type->per_cu.section,
6798                             sig_type->per_cu.sect_off);
6799     }
6800   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6801   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6802          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6803
6804   abbrev_offset = (sect_offset) ~(unsigned) 0;
6805   abbrev_table = NULL;
6806   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6807
6808   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6809     {
6810       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6811
6812       /* Switch to the next abbrev table if necessary.  */
6813       if (abbrev_table == NULL
6814           || tu->abbrev_offset != abbrev_offset)
6815         {
6816           if (abbrev_table != NULL)
6817             {
6818               abbrev_table_free (abbrev_table);
6819               /* Reset to NULL in case abbrev_table_read_table throws
6820                  an error: abbrev_table_free_cleanup will get called.  */
6821               abbrev_table = NULL;
6822             }
6823           abbrev_offset = tu->abbrev_offset;
6824           abbrev_table =
6825             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6826                                      abbrev_offset);
6827           ++tu_stats->nr_uniq_abbrev_tables;
6828         }
6829
6830       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6831                                build_type_psymtabs_reader, NULL);
6832     }
6833
6834   do_cleanups (cleanups);
6835 }
6836
6837 /* Print collected type unit statistics.  */
6838
6839 static void
6840 print_tu_stats (void)
6841 {
6842   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6843
6844   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6845   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6846                       dwarf2_per_objfile->n_type_units);
6847   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6848                       tu_stats->nr_uniq_abbrev_tables);
6849   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6850                       tu_stats->nr_symtabs);
6851   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6852                       tu_stats->nr_symtab_sharers);
6853   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6854                       tu_stats->nr_stmt_less_type_units);
6855   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6856                       tu_stats->nr_all_type_units_reallocs);
6857 }
6858
6859 /* Traversal function for build_type_psymtabs.  */
6860
6861 static int
6862 build_type_psymtab_dependencies (void **slot, void *info)
6863 {
6864   struct objfile *objfile = dwarf2_per_objfile->objfile;
6865   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6866   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6867   struct partial_symtab *pst = per_cu->v.psymtab;
6868   int len = VEC_length (sig_type_ptr, tu_group->tus);
6869   struct signatured_type *iter;
6870   int i;
6871
6872   gdb_assert (len > 0);
6873   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6874
6875   pst->number_of_dependencies = len;
6876   pst->dependencies =
6877     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6878   for (i = 0;
6879        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6880        ++i)
6881     {
6882       gdb_assert (iter->per_cu.is_debug_types);
6883       pst->dependencies[i] = iter->per_cu.v.psymtab;
6884       iter->type_unit_group = tu_group;
6885     }
6886
6887   VEC_free (sig_type_ptr, tu_group->tus);
6888
6889   return 1;
6890 }
6891
6892 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6893    Build partial symbol tables for the .debug_types comp-units.  */
6894
6895 static void
6896 build_type_psymtabs (struct objfile *objfile)
6897 {
6898   if (! create_all_type_units (objfile))
6899     return;
6900
6901   build_type_psymtabs_1 ();
6902 }
6903
6904 /* Traversal function for process_skeletonless_type_unit.
6905    Read a TU in a DWO file and build partial symbols for it.  */
6906
6907 static int
6908 process_skeletonless_type_unit (void **slot, void *info)
6909 {
6910   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6911   struct objfile *objfile = (struct objfile *) info;
6912   struct signatured_type find_entry, *entry;
6913
6914   /* If this TU doesn't exist in the global table, add it and read it in.  */
6915
6916   if (dwarf2_per_objfile->signatured_types == NULL)
6917     {
6918       dwarf2_per_objfile->signatured_types
6919         = allocate_signatured_type_table (objfile);
6920     }
6921
6922   find_entry.signature = dwo_unit->signature;
6923   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6924                          INSERT);
6925   /* If we've already seen this type there's nothing to do.  What's happening
6926      is we're doing our own version of comdat-folding here.  */
6927   if (*slot != NULL)
6928     return 1;
6929
6930   /* This does the job that create_all_type_units would have done for
6931      this TU.  */
6932   entry = add_type_unit (dwo_unit->signature, slot);
6933   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6934   *slot = entry;
6935
6936   /* This does the job that build_type_psymtabs_1 would have done.  */
6937   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6938                            build_type_psymtabs_reader, NULL);
6939
6940   return 1;
6941 }
6942
6943 /* Traversal function for process_skeletonless_type_units.  */
6944
6945 static int
6946 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6947 {
6948   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6949
6950   if (dwo_file->tus != NULL)
6951     {
6952       htab_traverse_noresize (dwo_file->tus,
6953                               process_skeletonless_type_unit, info);
6954     }
6955
6956   return 1;
6957 }
6958
6959 /* Scan all TUs of DWO files, verifying we've processed them.
6960    This is needed in case a TU was emitted without its skeleton.
6961    Note: This can't be done until we know what all the DWO files are.  */
6962
6963 static void
6964 process_skeletonless_type_units (struct objfile *objfile)
6965 {
6966   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6967   if (get_dwp_file () == NULL
6968       && dwarf2_per_objfile->dwo_files != NULL)
6969     {
6970       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6971                               process_dwo_file_for_skeletonless_type_units,
6972                               objfile);
6973     }
6974 }
6975
6976 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6977
6978 static void
6979 set_partial_user (struct objfile *objfile)
6980 {
6981   int i;
6982
6983   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6984     {
6985       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6986       struct partial_symtab *pst = per_cu->v.psymtab;
6987       int j;
6988
6989       if (pst == NULL)
6990         continue;
6991
6992       for (j = 0; j < pst->number_of_dependencies; ++j)
6993         {
6994           /* Set the 'user' field only if it is not already set.  */
6995           if (pst->dependencies[j]->user == NULL)
6996             pst->dependencies[j]->user = pst;
6997         }
6998     }
6999 }
7000
7001 /* Build the partial symbol table by doing a quick pass through the
7002    .debug_info and .debug_abbrev sections.  */
7003
7004 static void
7005 dwarf2_build_psymtabs_hard (struct objfile *objfile)
7006 {
7007   struct cleanup *back_to;
7008   int i;
7009
7010   if (dwarf_read_debug)
7011     {
7012       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7013                           objfile_name (objfile));
7014     }
7015
7016   dwarf2_per_objfile->reading_partial_symbols = 1;
7017
7018   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7019
7020   /* Any cached compilation units will be linked by the per-objfile
7021      read_in_chain.  Make sure to free them when we're done.  */
7022   back_to = make_cleanup (free_cached_comp_units, NULL);
7023
7024   build_type_psymtabs (objfile);
7025
7026   create_all_comp_units (objfile);
7027
7028   /* Create a temporary address map on a temporary obstack.  We later
7029      copy this to the final obstack.  */
7030   auto_obstack temp_obstack;
7031
7032   scoped_restore save_psymtabs_addrmap
7033     = make_scoped_restore (&objfile->psymtabs_addrmap,
7034                            addrmap_create_mutable (&temp_obstack));
7035
7036   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7037     {
7038       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7039
7040       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7041     }
7042
7043   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7044   process_skeletonless_type_units (objfile);
7045
7046   /* Now that all TUs have been processed we can fill in the dependencies.  */
7047   if (dwarf2_per_objfile->type_unit_groups != NULL)
7048     {
7049       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7050                               build_type_psymtab_dependencies, NULL);
7051     }
7052
7053   if (dwarf_read_debug)
7054     print_tu_stats ();
7055
7056   set_partial_user (objfile);
7057
7058   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7059                                                     &objfile->objfile_obstack);
7060   /* At this point we want to keep the address map.  */
7061   save_psymtabs_addrmap.release ();
7062
7063   do_cleanups (back_to);
7064
7065   if (dwarf_read_debug)
7066     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7067                         objfile_name (objfile));
7068 }
7069
7070 /* die_reader_func for load_partial_comp_unit.  */
7071
7072 static void
7073 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7074                                const gdb_byte *info_ptr,
7075                                struct die_info *comp_unit_die,
7076                                int has_children,
7077                                void *data)
7078 {
7079   struct dwarf2_cu *cu = reader->cu;
7080
7081   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7082
7083   /* Check if comp unit has_children.
7084      If so, read the rest of the partial symbols from this comp unit.
7085      If not, there's no more debug_info for this comp unit.  */
7086   if (has_children)
7087     load_partial_dies (reader, info_ptr, 0);
7088 }
7089
7090 /* Load the partial DIEs for a secondary CU into memory.
7091    This is also used when rereading a primary CU with load_all_dies.  */
7092
7093 static void
7094 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7095 {
7096   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7097                            load_partial_comp_unit_reader, NULL);
7098 }
7099
7100 static void
7101 read_comp_units_from_section (struct objfile *objfile,
7102                               struct dwarf2_section_info *section,
7103                               struct dwarf2_section_info *abbrev_section,
7104                               unsigned int is_dwz,
7105                               int *n_allocated,
7106                               int *n_comp_units,
7107                               struct dwarf2_per_cu_data ***all_comp_units)
7108 {
7109   const gdb_byte *info_ptr;
7110   bfd *abfd = get_section_bfd_owner (section);
7111
7112   if (dwarf_read_debug)
7113     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7114                         get_section_name (section),
7115                         get_section_file_name (section));
7116
7117   dwarf2_read_section (objfile, section);
7118
7119   info_ptr = section->buffer;
7120
7121   while (info_ptr < section->buffer + section->size)
7122     {
7123       struct dwarf2_per_cu_data *this_cu;
7124
7125       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7126
7127       comp_unit_head cu_header;
7128       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7129                                      info_ptr, rcuh_kind::COMPILE);
7130
7131       /* Save the compilation unit for later lookup.  */
7132       if (cu_header.unit_type != DW_UT_type)
7133         {
7134           this_cu = XOBNEW (&objfile->objfile_obstack,
7135                             struct dwarf2_per_cu_data);
7136           memset (this_cu, 0, sizeof (*this_cu));
7137         }
7138       else
7139         {
7140           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7141                                   struct signatured_type);
7142           memset (sig_type, 0, sizeof (*sig_type));
7143           sig_type->signature = cu_header.signature;
7144           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7145           this_cu = &sig_type->per_cu;
7146         }
7147       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7148       this_cu->sect_off = sect_off;
7149       this_cu->length = cu_header.length + cu_header.initial_length_size;
7150       this_cu->is_dwz = is_dwz;
7151       this_cu->objfile = objfile;
7152       this_cu->section = section;
7153
7154       if (*n_comp_units == *n_allocated)
7155         {
7156           *n_allocated *= 2;
7157           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7158                                         *all_comp_units, *n_allocated);
7159         }
7160       (*all_comp_units)[*n_comp_units] = this_cu;
7161       ++*n_comp_units;
7162
7163       info_ptr = info_ptr + this_cu->length;
7164     }
7165 }
7166
7167 /* Create a list of all compilation units in OBJFILE.
7168    This is only done for -readnow and building partial symtabs.  */
7169
7170 static void
7171 create_all_comp_units (struct objfile *objfile)
7172 {
7173   int n_allocated;
7174   int n_comp_units;
7175   struct dwarf2_per_cu_data **all_comp_units;
7176   struct dwz_file *dwz;
7177
7178   n_comp_units = 0;
7179   n_allocated = 10;
7180   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7181
7182   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7183                                 &dwarf2_per_objfile->abbrev, 0,
7184                                 &n_allocated, &n_comp_units, &all_comp_units);
7185
7186   dwz = dwarf2_get_dwz_file ();
7187   if (dwz != NULL)
7188     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7189                                   &n_allocated, &n_comp_units,
7190                                   &all_comp_units);
7191
7192   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7193                                                   struct dwarf2_per_cu_data *,
7194                                                   n_comp_units);
7195   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7196           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7197   xfree (all_comp_units);
7198   dwarf2_per_objfile->n_comp_units = n_comp_units;
7199 }
7200
7201 /* Process all loaded DIEs for compilation unit CU, starting at
7202    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7203    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7204    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7205    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7206
7207 static void
7208 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7209                       CORE_ADDR *highpc, int set_addrmap,
7210                       struct dwarf2_cu *cu)
7211 {
7212   struct partial_die_info *pdi;
7213
7214   /* Now, march along the PDI's, descending into ones which have
7215      interesting children but skipping the children of the other ones,
7216      until we reach the end of the compilation unit.  */
7217
7218   pdi = first_die;
7219
7220   while (pdi != NULL)
7221     {
7222       fixup_partial_die (pdi, cu);
7223
7224       /* Anonymous namespaces or modules have no name but have interesting
7225          children, so we need to look at them.  Ditto for anonymous
7226          enums.  */
7227
7228       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7229           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7230           || pdi->tag == DW_TAG_imported_unit)
7231         {
7232           switch (pdi->tag)
7233             {
7234             case DW_TAG_subprogram:
7235               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7236               break;
7237             case DW_TAG_constant:
7238             case DW_TAG_variable:
7239             case DW_TAG_typedef:
7240             case DW_TAG_union_type:
7241               if (!pdi->is_declaration)
7242                 {
7243                   add_partial_symbol (pdi, cu);
7244                 }
7245               break;
7246             case DW_TAG_class_type:
7247             case DW_TAG_interface_type:
7248             case DW_TAG_structure_type:
7249               if (!pdi->is_declaration)
7250                 {
7251                   add_partial_symbol (pdi, cu);
7252                 }
7253               if (cu->language == language_rust && pdi->has_children)
7254                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7255                                       set_addrmap, cu);
7256               break;
7257             case DW_TAG_enumeration_type:
7258               if (!pdi->is_declaration)
7259                 add_partial_enumeration (pdi, cu);
7260               break;
7261             case DW_TAG_base_type:
7262             case DW_TAG_subrange_type:
7263               /* File scope base type definitions are added to the partial
7264                  symbol table.  */
7265               add_partial_symbol (pdi, cu);
7266               break;
7267             case DW_TAG_namespace:
7268               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7269               break;
7270             case DW_TAG_module:
7271               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7272               break;
7273             case DW_TAG_imported_unit:
7274               {
7275                 struct dwarf2_per_cu_data *per_cu;
7276
7277                 /* For now we don't handle imported units in type units.  */
7278                 if (cu->per_cu->is_debug_types)
7279                   {
7280                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7281                              " supported in type units [in module %s]"),
7282                            objfile_name (cu->objfile));
7283                   }
7284
7285                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7286                                                            pdi->is_dwz,
7287                                                            cu->objfile);
7288
7289                 /* Go read the partial unit, if needed.  */
7290                 if (per_cu->v.psymtab == NULL)
7291                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7292
7293                 VEC_safe_push (dwarf2_per_cu_ptr,
7294                                cu->per_cu->imported_symtabs, per_cu);
7295               }
7296               break;
7297             case DW_TAG_imported_declaration:
7298               add_partial_symbol (pdi, cu);
7299               break;
7300             default:
7301               break;
7302             }
7303         }
7304
7305       /* If the die has a sibling, skip to the sibling.  */
7306
7307       pdi = pdi->die_sibling;
7308     }
7309 }
7310
7311 /* Functions used to compute the fully scoped name of a partial DIE.
7312
7313    Normally, this is simple.  For C++, the parent DIE's fully scoped
7314    name is concatenated with "::" and the partial DIE's name.
7315    Enumerators are an exception; they use the scope of their parent
7316    enumeration type, i.e. the name of the enumeration type is not
7317    prepended to the enumerator.
7318
7319    There are two complexities.  One is DW_AT_specification; in this
7320    case "parent" means the parent of the target of the specification,
7321    instead of the direct parent of the DIE.  The other is compilers
7322    which do not emit DW_TAG_namespace; in this case we try to guess
7323    the fully qualified name of structure types from their members'
7324    linkage names.  This must be done using the DIE's children rather
7325    than the children of any DW_AT_specification target.  We only need
7326    to do this for structures at the top level, i.e. if the target of
7327    any DW_AT_specification (if any; otherwise the DIE itself) does not
7328    have a parent.  */
7329
7330 /* Compute the scope prefix associated with PDI's parent, in
7331    compilation unit CU.  The result will be allocated on CU's
7332    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7333    field.  NULL is returned if no prefix is necessary.  */
7334 static const char *
7335 partial_die_parent_scope (struct partial_die_info *pdi,
7336                           struct dwarf2_cu *cu)
7337 {
7338   const char *grandparent_scope;
7339   struct partial_die_info *parent, *real_pdi;
7340
7341   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7342      then this means the parent of the specification DIE.  */
7343
7344   real_pdi = pdi;
7345   while (real_pdi->has_specification)
7346     real_pdi = find_partial_die (real_pdi->spec_offset,
7347                                  real_pdi->spec_is_dwz, cu);
7348
7349   parent = real_pdi->die_parent;
7350   if (parent == NULL)
7351     return NULL;
7352
7353   if (parent->scope_set)
7354     return parent->scope;
7355
7356   fixup_partial_die (parent, cu);
7357
7358   grandparent_scope = partial_die_parent_scope (parent, cu);
7359
7360   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7361      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7362      Work around this problem here.  */
7363   if (cu->language == language_cplus
7364       && parent->tag == DW_TAG_namespace
7365       && strcmp (parent->name, "::") == 0
7366       && grandparent_scope == NULL)
7367     {
7368       parent->scope = NULL;
7369       parent->scope_set = 1;
7370       return NULL;
7371     }
7372
7373   if (pdi->tag == DW_TAG_enumerator)
7374     /* Enumerators should not get the name of the enumeration as a prefix.  */
7375     parent->scope = grandparent_scope;
7376   else if (parent->tag == DW_TAG_namespace
7377       || parent->tag == DW_TAG_module
7378       || parent->tag == DW_TAG_structure_type
7379       || parent->tag == DW_TAG_class_type
7380       || parent->tag == DW_TAG_interface_type
7381       || parent->tag == DW_TAG_union_type
7382       || parent->tag == DW_TAG_enumeration_type)
7383     {
7384       if (grandparent_scope == NULL)
7385         parent->scope = parent->name;
7386       else
7387         parent->scope = typename_concat (&cu->comp_unit_obstack,
7388                                          grandparent_scope,
7389                                          parent->name, 0, cu);
7390     }
7391   else
7392     {
7393       /* FIXME drow/2004-04-01: What should we be doing with
7394          function-local names?  For partial symbols, we should probably be
7395          ignoring them.  */
7396       complaint (&symfile_complaints,
7397                  _("unhandled containing DIE tag %d for DIE at %d"),
7398                  parent->tag, to_underlying (pdi->sect_off));
7399       parent->scope = grandparent_scope;
7400     }
7401
7402   parent->scope_set = 1;
7403   return parent->scope;
7404 }
7405
7406 /* Return the fully scoped name associated with PDI, from compilation unit
7407    CU.  The result will be allocated with malloc.  */
7408
7409 static char *
7410 partial_die_full_name (struct partial_die_info *pdi,
7411                        struct dwarf2_cu *cu)
7412 {
7413   const char *parent_scope;
7414
7415   /* If this is a template instantiation, we can not work out the
7416      template arguments from partial DIEs.  So, unfortunately, we have
7417      to go through the full DIEs.  At least any work we do building
7418      types here will be reused if full symbols are loaded later.  */
7419   if (pdi->has_template_arguments)
7420     {
7421       fixup_partial_die (pdi, cu);
7422
7423       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7424         {
7425           struct die_info *die;
7426           struct attribute attr;
7427           struct dwarf2_cu *ref_cu = cu;
7428
7429           /* DW_FORM_ref_addr is using section offset.  */
7430           attr.name = (enum dwarf_attribute) 0;
7431           attr.form = DW_FORM_ref_addr;
7432           attr.u.unsnd = to_underlying (pdi->sect_off);
7433           die = follow_die_ref (NULL, &attr, &ref_cu);
7434
7435           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7436         }
7437     }
7438
7439   parent_scope = partial_die_parent_scope (pdi, cu);
7440   if (parent_scope == NULL)
7441     return NULL;
7442   else
7443     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7444 }
7445
7446 static void
7447 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7448 {
7449   struct objfile *objfile = cu->objfile;
7450   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7451   CORE_ADDR addr = 0;
7452   const char *actual_name = NULL;
7453   CORE_ADDR baseaddr;
7454   char *built_actual_name;
7455
7456   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7457
7458   built_actual_name = partial_die_full_name (pdi, cu);
7459   if (built_actual_name != NULL)
7460     actual_name = built_actual_name;
7461
7462   if (actual_name == NULL)
7463     actual_name = pdi->name;
7464
7465   switch (pdi->tag)
7466     {
7467     case DW_TAG_subprogram:
7468       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7469       if (pdi->is_external || cu->language == language_ada)
7470         {
7471           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7472              of the global scope.  But in Ada, we want to be able to access
7473              nested procedures globally.  So all Ada subprograms are stored
7474              in the global scope.  */
7475           add_psymbol_to_list (actual_name, strlen (actual_name),
7476                                built_actual_name != NULL,
7477                                VAR_DOMAIN, LOC_BLOCK,
7478                                &objfile->global_psymbols,
7479                                addr, cu->language, objfile);
7480         }
7481       else
7482         {
7483           add_psymbol_to_list (actual_name, strlen (actual_name),
7484                                built_actual_name != NULL,
7485                                VAR_DOMAIN, LOC_BLOCK,
7486                                &objfile->static_psymbols,
7487                                addr, cu->language, objfile);
7488         }
7489
7490       if (pdi->main_subprogram && actual_name != NULL)
7491         set_objfile_main_name (objfile, actual_name, cu->language);
7492       break;
7493     case DW_TAG_constant:
7494       {
7495         std::vector<partial_symbol *> *list;
7496
7497         if (pdi->is_external)
7498           list = &objfile->global_psymbols;
7499         else
7500           list = &objfile->static_psymbols;
7501         add_psymbol_to_list (actual_name, strlen (actual_name),
7502                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7503                              list, 0, cu->language, objfile);
7504       }
7505       break;
7506     case DW_TAG_variable:
7507       if (pdi->d.locdesc)
7508         addr = decode_locdesc (pdi->d.locdesc, cu);
7509
7510       if (pdi->d.locdesc
7511           && addr == 0
7512           && !dwarf2_per_objfile->has_section_at_zero)
7513         {
7514           /* A global or static variable may also have been stripped
7515              out by the linker if unused, in which case its address
7516              will be nullified; do not add such variables into partial
7517              symbol table then.  */
7518         }
7519       else if (pdi->is_external)
7520         {
7521           /* Global Variable.
7522              Don't enter into the minimal symbol tables as there is
7523              a minimal symbol table entry from the ELF symbols already.
7524              Enter into partial symbol table if it has a location
7525              descriptor or a type.
7526              If the location descriptor is missing, new_symbol will create
7527              a LOC_UNRESOLVED symbol, the address of the variable will then
7528              be determined from the minimal symbol table whenever the variable
7529              is referenced.
7530              The address for the partial symbol table entry is not
7531              used by GDB, but it comes in handy for debugging partial symbol
7532              table building.  */
7533
7534           if (pdi->d.locdesc || pdi->has_type)
7535             add_psymbol_to_list (actual_name, strlen (actual_name),
7536                                  built_actual_name != NULL,
7537                                  VAR_DOMAIN, LOC_STATIC,
7538                                  &objfile->global_psymbols,
7539                                  addr + baseaddr,
7540                                  cu->language, objfile);
7541         }
7542       else
7543         {
7544           int has_loc = pdi->d.locdesc != NULL;
7545
7546           /* Static Variable.  Skip symbols whose value we cannot know (those
7547              without location descriptors or constant values).  */
7548           if (!has_loc && !pdi->has_const_value)
7549             {
7550               xfree (built_actual_name);
7551               return;
7552             }
7553
7554           add_psymbol_to_list (actual_name, strlen (actual_name),
7555                                built_actual_name != NULL,
7556                                VAR_DOMAIN, LOC_STATIC,
7557                                &objfile->static_psymbols,
7558                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7559                                cu->language, objfile);
7560         }
7561       break;
7562     case DW_TAG_typedef:
7563     case DW_TAG_base_type:
7564     case DW_TAG_subrange_type:
7565       add_psymbol_to_list (actual_name, strlen (actual_name),
7566                            built_actual_name != NULL,
7567                            VAR_DOMAIN, LOC_TYPEDEF,
7568                            &objfile->static_psymbols,
7569                            0, cu->language, objfile);
7570       break;
7571     case DW_TAG_imported_declaration:
7572     case DW_TAG_namespace:
7573       add_psymbol_to_list (actual_name, strlen (actual_name),
7574                            built_actual_name != NULL,
7575                            VAR_DOMAIN, LOC_TYPEDEF,
7576                            &objfile->global_psymbols,
7577                            0, cu->language, objfile);
7578       break;
7579     case DW_TAG_module:
7580       add_psymbol_to_list (actual_name, strlen (actual_name),
7581                            built_actual_name != NULL,
7582                            MODULE_DOMAIN, LOC_TYPEDEF,
7583                            &objfile->global_psymbols,
7584                            0, cu->language, objfile);
7585       break;
7586     case DW_TAG_class_type:
7587     case DW_TAG_interface_type:
7588     case DW_TAG_structure_type:
7589     case DW_TAG_union_type:
7590     case DW_TAG_enumeration_type:
7591       /* Skip external references.  The DWARF standard says in the section
7592          about "Structure, Union, and Class Type Entries": "An incomplete
7593          structure, union or class type is represented by a structure,
7594          union or class entry that does not have a byte size attribute
7595          and that has a DW_AT_declaration attribute."  */
7596       if (!pdi->has_byte_size && pdi->is_declaration)
7597         {
7598           xfree (built_actual_name);
7599           return;
7600         }
7601
7602       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7603          static vs. global.  */
7604       add_psymbol_to_list (actual_name, strlen (actual_name),
7605                            built_actual_name != NULL,
7606                            STRUCT_DOMAIN, LOC_TYPEDEF,
7607                            cu->language == language_cplus
7608                            ? &objfile->global_psymbols
7609                            : &objfile->static_psymbols,
7610                            0, cu->language, objfile);
7611
7612       break;
7613     case DW_TAG_enumerator:
7614       add_psymbol_to_list (actual_name, strlen (actual_name),
7615                            built_actual_name != NULL,
7616                            VAR_DOMAIN, LOC_CONST,
7617                            cu->language == language_cplus
7618                            ? &objfile->global_psymbols
7619                            : &objfile->static_psymbols,
7620                            0, cu->language, objfile);
7621       break;
7622     default:
7623       break;
7624     }
7625
7626   xfree (built_actual_name);
7627 }
7628
7629 /* Read a partial die corresponding to a namespace; also, add a symbol
7630    corresponding to that namespace to the symbol table.  NAMESPACE is
7631    the name of the enclosing namespace.  */
7632
7633 static void
7634 add_partial_namespace (struct partial_die_info *pdi,
7635                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7636                        int set_addrmap, struct dwarf2_cu *cu)
7637 {
7638   /* Add a symbol for the namespace.  */
7639
7640   add_partial_symbol (pdi, cu);
7641
7642   /* Now scan partial symbols in that namespace.  */
7643
7644   if (pdi->has_children)
7645     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7646 }
7647
7648 /* Read a partial die corresponding to a Fortran module.  */
7649
7650 static void
7651 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7652                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7653 {
7654   /* Add a symbol for the namespace.  */
7655
7656   add_partial_symbol (pdi, cu);
7657
7658   /* Now scan partial symbols in that module.  */
7659
7660   if (pdi->has_children)
7661     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7662 }
7663
7664 /* Read a partial die corresponding to a subprogram and create a partial
7665    symbol for that subprogram.  When the CU language allows it, this
7666    routine also defines a partial symbol for each nested subprogram
7667    that this subprogram contains.  If SET_ADDRMAP is true, record the
7668    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7669    and highest PC values found in PDI.
7670
7671    PDI may also be a lexical block, in which case we simply search
7672    recursively for subprograms defined inside that lexical block.
7673    Again, this is only performed when the CU language allows this
7674    type of definitions.  */
7675
7676 static void
7677 add_partial_subprogram (struct partial_die_info *pdi,
7678                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7679                         int set_addrmap, struct dwarf2_cu *cu)
7680 {
7681   if (pdi->tag == DW_TAG_subprogram)
7682     {
7683       if (pdi->has_pc_info)
7684         {
7685           if (pdi->lowpc < *lowpc)
7686             *lowpc = pdi->lowpc;
7687           if (pdi->highpc > *highpc)
7688             *highpc = pdi->highpc;
7689           if (set_addrmap)
7690             {
7691               struct objfile *objfile = cu->objfile;
7692               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7693               CORE_ADDR baseaddr;
7694               CORE_ADDR highpc;
7695               CORE_ADDR lowpc;
7696
7697               baseaddr = ANOFFSET (objfile->section_offsets,
7698                                    SECT_OFF_TEXT (objfile));
7699               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7700                                                   pdi->lowpc + baseaddr);
7701               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7702                                                    pdi->highpc + baseaddr);
7703               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7704                                  cu->per_cu->v.psymtab);
7705             }
7706         }
7707
7708       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7709         {
7710           if (!pdi->is_declaration)
7711             /* Ignore subprogram DIEs that do not have a name, they are
7712                illegal.  Do not emit a complaint at this point, we will
7713                do so when we convert this psymtab into a symtab.  */
7714             if (pdi->name)
7715               add_partial_symbol (pdi, cu);
7716         }
7717     }
7718
7719   if (! pdi->has_children)
7720     return;
7721
7722   if (cu->language == language_ada)
7723     {
7724       pdi = pdi->die_child;
7725       while (pdi != NULL)
7726         {
7727           fixup_partial_die (pdi, cu);
7728           if (pdi->tag == DW_TAG_subprogram
7729               || pdi->tag == DW_TAG_lexical_block)
7730             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7731           pdi = pdi->die_sibling;
7732         }
7733     }
7734 }
7735
7736 /* Read a partial die corresponding to an enumeration type.  */
7737
7738 static void
7739 add_partial_enumeration (struct partial_die_info *enum_pdi,
7740                          struct dwarf2_cu *cu)
7741 {
7742   struct partial_die_info *pdi;
7743
7744   if (enum_pdi->name != NULL)
7745     add_partial_symbol (enum_pdi, cu);
7746
7747   pdi = enum_pdi->die_child;
7748   while (pdi)
7749     {
7750       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7751         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7752       else
7753         add_partial_symbol (pdi, cu);
7754       pdi = pdi->die_sibling;
7755     }
7756 }
7757
7758 /* Return the initial uleb128 in the die at INFO_PTR.  */
7759
7760 static unsigned int
7761 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7762 {
7763   unsigned int bytes_read;
7764
7765   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7766 }
7767
7768 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7769    Return the corresponding abbrev, or NULL if the number is zero (indicating
7770    an empty DIE).  In either case *BYTES_READ will be set to the length of
7771    the initial number.  */
7772
7773 static struct abbrev_info *
7774 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7775                  struct dwarf2_cu *cu)
7776 {
7777   bfd *abfd = cu->objfile->obfd;
7778   unsigned int abbrev_number;
7779   struct abbrev_info *abbrev;
7780
7781   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7782
7783   if (abbrev_number == 0)
7784     return NULL;
7785
7786   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7787   if (!abbrev)
7788     {
7789       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7790                " at offset 0x%x [in module %s]"),
7791              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7792              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7793     }
7794
7795   return abbrev;
7796 }
7797
7798 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7799    Returns a pointer to the end of a series of DIEs, terminated by an empty
7800    DIE.  Any children of the skipped DIEs will also be skipped.  */
7801
7802 static const gdb_byte *
7803 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7804 {
7805   struct dwarf2_cu *cu = reader->cu;
7806   struct abbrev_info *abbrev;
7807   unsigned int bytes_read;
7808
7809   while (1)
7810     {
7811       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7812       if (abbrev == NULL)
7813         return info_ptr + bytes_read;
7814       else
7815         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7816     }
7817 }
7818
7819 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7820    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7821    abbrev corresponding to that skipped uleb128 should be passed in
7822    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7823    children.  */
7824
7825 static const gdb_byte *
7826 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7827               struct abbrev_info *abbrev)
7828 {
7829   unsigned int bytes_read;
7830   struct attribute attr;
7831   bfd *abfd = reader->abfd;
7832   struct dwarf2_cu *cu = reader->cu;
7833   const gdb_byte *buffer = reader->buffer;
7834   const gdb_byte *buffer_end = reader->buffer_end;
7835   unsigned int form, i;
7836
7837   for (i = 0; i < abbrev->num_attrs; i++)
7838     {
7839       /* The only abbrev we care about is DW_AT_sibling.  */
7840       if (abbrev->attrs[i].name == DW_AT_sibling)
7841         {
7842           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7843           if (attr.form == DW_FORM_ref_addr)
7844             complaint (&symfile_complaints,
7845                        _("ignoring absolute DW_AT_sibling"));
7846           else
7847             {
7848               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7849               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7850
7851               if (sibling_ptr < info_ptr)
7852                 complaint (&symfile_complaints,
7853                            _("DW_AT_sibling points backwards"));
7854               else if (sibling_ptr > reader->buffer_end)
7855                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7856               else
7857                 return sibling_ptr;
7858             }
7859         }
7860
7861       /* If it isn't DW_AT_sibling, skip this attribute.  */
7862       form = abbrev->attrs[i].form;
7863     skip_attribute:
7864       switch (form)
7865         {
7866         case DW_FORM_ref_addr:
7867           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7868              and later it is offset sized.  */
7869           if (cu->header.version == 2)
7870             info_ptr += cu->header.addr_size;
7871           else
7872             info_ptr += cu->header.offset_size;
7873           break;
7874         case DW_FORM_GNU_ref_alt:
7875           info_ptr += cu->header.offset_size;
7876           break;
7877         case DW_FORM_addr:
7878           info_ptr += cu->header.addr_size;
7879           break;
7880         case DW_FORM_data1:
7881         case DW_FORM_ref1:
7882         case DW_FORM_flag:
7883           info_ptr += 1;
7884           break;
7885         case DW_FORM_flag_present:
7886         case DW_FORM_implicit_const:
7887           break;
7888         case DW_FORM_data2:
7889         case DW_FORM_ref2:
7890           info_ptr += 2;
7891           break;
7892         case DW_FORM_data4:
7893         case DW_FORM_ref4:
7894           info_ptr += 4;
7895           break;
7896         case DW_FORM_data8:
7897         case DW_FORM_ref8:
7898         case DW_FORM_ref_sig8:
7899           info_ptr += 8;
7900           break;
7901         case DW_FORM_data16:
7902           info_ptr += 16;
7903           break;
7904         case DW_FORM_string:
7905           read_direct_string (abfd, info_ptr, &bytes_read);
7906           info_ptr += bytes_read;
7907           break;
7908         case DW_FORM_sec_offset:
7909         case DW_FORM_strp:
7910         case DW_FORM_GNU_strp_alt:
7911           info_ptr += cu->header.offset_size;
7912           break;
7913         case DW_FORM_exprloc:
7914         case DW_FORM_block:
7915           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7916           info_ptr += bytes_read;
7917           break;
7918         case DW_FORM_block1:
7919           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7920           break;
7921         case DW_FORM_block2:
7922           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7923           break;
7924         case DW_FORM_block4:
7925           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7926           break;
7927         case DW_FORM_sdata:
7928         case DW_FORM_udata:
7929         case DW_FORM_ref_udata:
7930         case DW_FORM_GNU_addr_index:
7931         case DW_FORM_GNU_str_index:
7932           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7933           break;
7934         case DW_FORM_indirect:
7935           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7936           info_ptr += bytes_read;
7937           /* We need to continue parsing from here, so just go back to
7938              the top.  */
7939           goto skip_attribute;
7940
7941         default:
7942           error (_("Dwarf Error: Cannot handle %s "
7943                    "in DWARF reader [in module %s]"),
7944                  dwarf_form_name (form),
7945                  bfd_get_filename (abfd));
7946         }
7947     }
7948
7949   if (abbrev->has_children)
7950     return skip_children (reader, info_ptr);
7951   else
7952     return info_ptr;
7953 }
7954
7955 /* Locate ORIG_PDI's sibling.
7956    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7957
7958 static const gdb_byte *
7959 locate_pdi_sibling (const struct die_reader_specs *reader,
7960                     struct partial_die_info *orig_pdi,
7961                     const gdb_byte *info_ptr)
7962 {
7963   /* Do we know the sibling already?  */
7964
7965   if (orig_pdi->sibling)
7966     return orig_pdi->sibling;
7967
7968   /* Are there any children to deal with?  */
7969
7970   if (!orig_pdi->has_children)
7971     return info_ptr;
7972
7973   /* Skip the children the long way.  */
7974
7975   return skip_children (reader, info_ptr);
7976 }
7977
7978 /* Expand this partial symbol table into a full symbol table.  SELF is
7979    not NULL.  */
7980
7981 static void
7982 dwarf2_read_symtab (struct partial_symtab *self,
7983                     struct objfile *objfile)
7984 {
7985   if (self->readin)
7986     {
7987       warning (_("bug: psymtab for %s is already read in."),
7988                self->filename);
7989     }
7990   else
7991     {
7992       if (info_verbose)
7993         {
7994           printf_filtered (_("Reading in symbols for %s..."),
7995                            self->filename);
7996           gdb_flush (gdb_stdout);
7997         }
7998
7999       /* Restore our global data.  */
8000       dwarf2_per_objfile
8001         = (struct dwarf2_per_objfile *) objfile_data (objfile,
8002                                                       dwarf2_objfile_data_key);
8003
8004       /* If this psymtab is constructed from a debug-only objfile, the
8005          has_section_at_zero flag will not necessarily be correct.  We
8006          can get the correct value for this flag by looking at the data
8007          associated with the (presumably stripped) associated objfile.  */
8008       if (objfile->separate_debug_objfile_backlink)
8009         {
8010           struct dwarf2_per_objfile *dpo_backlink
8011             = ((struct dwarf2_per_objfile *)
8012                objfile_data (objfile->separate_debug_objfile_backlink,
8013                              dwarf2_objfile_data_key));
8014
8015           dwarf2_per_objfile->has_section_at_zero
8016             = dpo_backlink->has_section_at_zero;
8017         }
8018
8019       dwarf2_per_objfile->reading_partial_symbols = 0;
8020
8021       psymtab_to_symtab_1 (self);
8022
8023       /* Finish up the debug error message.  */
8024       if (info_verbose)
8025         printf_filtered (_("done.\n"));
8026     }
8027
8028   process_cu_includes ();
8029 }
8030 \f
8031 /* Reading in full CUs.  */
8032
8033 /* Add PER_CU to the queue.  */
8034
8035 static void
8036 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8037                  enum language pretend_language)
8038 {
8039   struct dwarf2_queue_item *item;
8040
8041   per_cu->queued = 1;
8042   item = XNEW (struct dwarf2_queue_item);
8043   item->per_cu = per_cu;
8044   item->pretend_language = pretend_language;
8045   item->next = NULL;
8046
8047   if (dwarf2_queue == NULL)
8048     dwarf2_queue = item;
8049   else
8050     dwarf2_queue_tail->next = item;
8051
8052   dwarf2_queue_tail = item;
8053 }
8054
8055 /* If PER_CU is not yet queued, add it to the queue.
8056    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8057    dependency.
8058    The result is non-zero if PER_CU was queued, otherwise the result is zero
8059    meaning either PER_CU is already queued or it is already loaded.
8060
8061    N.B. There is an invariant here that if a CU is queued then it is loaded.
8062    The caller is required to load PER_CU if we return non-zero.  */
8063
8064 static int
8065 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8066                        struct dwarf2_per_cu_data *per_cu,
8067                        enum language pretend_language)
8068 {
8069   /* We may arrive here during partial symbol reading, if we need full
8070      DIEs to process an unusual case (e.g. template arguments).  Do
8071      not queue PER_CU, just tell our caller to load its DIEs.  */
8072   if (dwarf2_per_objfile->reading_partial_symbols)
8073     {
8074       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8075         return 1;
8076       return 0;
8077     }
8078
8079   /* Mark the dependence relation so that we don't flush PER_CU
8080      too early.  */
8081   if (dependent_cu != NULL)
8082     dwarf2_add_dependence (dependent_cu, per_cu);
8083
8084   /* If it's already on the queue, we have nothing to do.  */
8085   if (per_cu->queued)
8086     return 0;
8087
8088   /* If the compilation unit is already loaded, just mark it as
8089      used.  */
8090   if (per_cu->cu != NULL)
8091     {
8092       per_cu->cu->last_used = 0;
8093       return 0;
8094     }
8095
8096   /* Add it to the queue.  */
8097   queue_comp_unit (per_cu, pretend_language);
8098
8099   return 1;
8100 }
8101
8102 /* Process the queue.  */
8103
8104 static void
8105 process_queue (void)
8106 {
8107   struct dwarf2_queue_item *item, *next_item;
8108
8109   if (dwarf_read_debug)
8110     {
8111       fprintf_unfiltered (gdb_stdlog,
8112                           "Expanding one or more symtabs of objfile %s ...\n",
8113                           objfile_name (dwarf2_per_objfile->objfile));
8114     }
8115
8116   /* The queue starts out with one item, but following a DIE reference
8117      may load a new CU, adding it to the end of the queue.  */
8118   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8119     {
8120       if ((dwarf2_per_objfile->using_index
8121            ? !item->per_cu->v.quick->compunit_symtab
8122            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8123           /* Skip dummy CUs.  */
8124           && item->per_cu->cu != NULL)
8125         {
8126           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8127           unsigned int debug_print_threshold;
8128           char buf[100];
8129
8130           if (per_cu->is_debug_types)
8131             {
8132               struct signatured_type *sig_type =
8133                 (struct signatured_type *) per_cu;
8134
8135               sprintf (buf, "TU %s at offset 0x%x",
8136                        hex_string (sig_type->signature),
8137                        to_underlying (per_cu->sect_off));
8138               /* There can be 100s of TUs.
8139                  Only print them in verbose mode.  */
8140               debug_print_threshold = 2;
8141             }
8142           else
8143             {
8144               sprintf (buf, "CU at offset 0x%x",
8145                        to_underlying (per_cu->sect_off));
8146               debug_print_threshold = 1;
8147             }
8148
8149           if (dwarf_read_debug >= debug_print_threshold)
8150             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8151
8152           if (per_cu->is_debug_types)
8153             process_full_type_unit (per_cu, item->pretend_language);
8154           else
8155             process_full_comp_unit (per_cu, item->pretend_language);
8156
8157           if (dwarf_read_debug >= debug_print_threshold)
8158             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8159         }
8160
8161       item->per_cu->queued = 0;
8162       next_item = item->next;
8163       xfree (item);
8164     }
8165
8166   dwarf2_queue_tail = NULL;
8167
8168   if (dwarf_read_debug)
8169     {
8170       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8171                           objfile_name (dwarf2_per_objfile->objfile));
8172     }
8173 }
8174
8175 /* Free all allocated queue entries.  This function only releases anything if
8176    an error was thrown; if the queue was processed then it would have been
8177    freed as we went along.  */
8178
8179 static void
8180 dwarf2_release_queue (void *dummy)
8181 {
8182   struct dwarf2_queue_item *item, *last;
8183
8184   item = dwarf2_queue;
8185   while (item)
8186     {
8187       /* Anything still marked queued is likely to be in an
8188          inconsistent state, so discard it.  */
8189       if (item->per_cu->queued)
8190         {
8191           if (item->per_cu->cu != NULL)
8192             free_one_cached_comp_unit (item->per_cu);
8193           item->per_cu->queued = 0;
8194         }
8195
8196       last = item;
8197       item = item->next;
8198       xfree (last);
8199     }
8200
8201   dwarf2_queue = dwarf2_queue_tail = NULL;
8202 }
8203
8204 /* Read in full symbols for PST, and anything it depends on.  */
8205
8206 static void
8207 psymtab_to_symtab_1 (struct partial_symtab *pst)
8208 {
8209   struct dwarf2_per_cu_data *per_cu;
8210   int i;
8211
8212   if (pst->readin)
8213     return;
8214
8215   for (i = 0; i < pst->number_of_dependencies; i++)
8216     if (!pst->dependencies[i]->readin
8217         && pst->dependencies[i]->user == NULL)
8218       {
8219         /* Inform about additional files that need to be read in.  */
8220         if (info_verbose)
8221           {
8222             /* FIXME: i18n: Need to make this a single string.  */
8223             fputs_filtered (" ", gdb_stdout);
8224             wrap_here ("");
8225             fputs_filtered ("and ", gdb_stdout);
8226             wrap_here ("");
8227             printf_filtered ("%s...", pst->dependencies[i]->filename);
8228             wrap_here ("");     /* Flush output.  */
8229             gdb_flush (gdb_stdout);
8230           }
8231         psymtab_to_symtab_1 (pst->dependencies[i]);
8232       }
8233
8234   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8235
8236   if (per_cu == NULL)
8237     {
8238       /* It's an include file, no symbols to read for it.
8239          Everything is in the parent symtab.  */
8240       pst->readin = 1;
8241       return;
8242     }
8243
8244   dw2_do_instantiate_symtab (per_cu);
8245 }
8246
8247 /* Trivial hash function for die_info: the hash value of a DIE
8248    is its offset in .debug_info for this objfile.  */
8249
8250 static hashval_t
8251 die_hash (const void *item)
8252 {
8253   const struct die_info *die = (const struct die_info *) item;
8254
8255   return to_underlying (die->sect_off);
8256 }
8257
8258 /* Trivial comparison function for die_info structures: two DIEs
8259    are equal if they have the same offset.  */
8260
8261 static int
8262 die_eq (const void *item_lhs, const void *item_rhs)
8263 {
8264   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8265   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8266
8267   return die_lhs->sect_off == die_rhs->sect_off;
8268 }
8269
8270 /* die_reader_func for load_full_comp_unit.
8271    This is identical to read_signatured_type_reader,
8272    but is kept separate for now.  */
8273
8274 static void
8275 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8276                             const gdb_byte *info_ptr,
8277                             struct die_info *comp_unit_die,
8278                             int has_children,
8279                             void *data)
8280 {
8281   struct dwarf2_cu *cu = reader->cu;
8282   enum language *language_ptr = (enum language *) data;
8283
8284   gdb_assert (cu->die_hash == NULL);
8285   cu->die_hash =
8286     htab_create_alloc_ex (cu->header.length / 12,
8287                           die_hash,
8288                           die_eq,
8289                           NULL,
8290                           &cu->comp_unit_obstack,
8291                           hashtab_obstack_allocate,
8292                           dummy_obstack_deallocate);
8293
8294   if (has_children)
8295     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8296                                                   &info_ptr, comp_unit_die);
8297   cu->dies = comp_unit_die;
8298   /* comp_unit_die is not stored in die_hash, no need.  */
8299
8300   /* We try not to read any attributes in this function, because not
8301      all CUs needed for references have been loaded yet, and symbol
8302      table processing isn't initialized.  But we have to set the CU language,
8303      or we won't be able to build types correctly.
8304      Similarly, if we do not read the producer, we can not apply
8305      producer-specific interpretation.  */
8306   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8307 }
8308
8309 /* Load the DIEs associated with PER_CU into memory.  */
8310
8311 static void
8312 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8313                      enum language pretend_language)
8314 {
8315   gdb_assert (! this_cu->is_debug_types);
8316
8317   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8318                            load_full_comp_unit_reader, &pretend_language);
8319 }
8320
8321 /* Add a DIE to the delayed physname list.  */
8322
8323 static void
8324 add_to_method_list (struct type *type, int fnfield_index, int index,
8325                     const char *name, struct die_info *die,
8326                     struct dwarf2_cu *cu)
8327 {
8328   struct delayed_method_info mi;
8329   mi.type = type;
8330   mi.fnfield_index = fnfield_index;
8331   mi.index = index;
8332   mi.name = name;
8333   mi.die = die;
8334   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8335 }
8336
8337 /* A cleanup for freeing the delayed method list.  */
8338
8339 static void
8340 free_delayed_list (void *ptr)
8341 {
8342   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8343   if (cu->method_list != NULL)
8344     {
8345       VEC_free (delayed_method_info, cu->method_list);
8346       cu->method_list = NULL;
8347     }
8348 }
8349
8350 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8351    "const" / "volatile".  If so, decrements LEN by the length of the
8352    modifier and return true.  Otherwise return false.  */
8353
8354 template<size_t N>
8355 static bool
8356 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8357 {
8358   size_t mod_len = sizeof (mod) - 1;
8359   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8360     {
8361       len -= mod_len;
8362       return true;
8363     }
8364   return false;
8365 }
8366
8367 /* Compute the physnames of any methods on the CU's method list.
8368
8369    The computation of method physnames is delayed in order to avoid the
8370    (bad) condition that one of the method's formal parameters is of an as yet
8371    incomplete type.  */
8372
8373 static void
8374 compute_delayed_physnames (struct dwarf2_cu *cu)
8375 {
8376   int i;
8377   struct delayed_method_info *mi;
8378
8379   /* Only C++ delays computing physnames.  */
8380   if (VEC_empty (delayed_method_info, cu->method_list))
8381     return;
8382   gdb_assert (cu->language == language_cplus);
8383
8384   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8385     {
8386       const char *physname;
8387       struct fn_fieldlist *fn_flp
8388         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8389       physname = dwarf2_physname (mi->name, mi->die, cu);
8390       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8391         = physname ? physname : "";
8392
8393       /* Since there's no tag to indicate whether a method is a
8394          const/volatile overload, extract that information out of the
8395          demangled name.  */
8396       if (physname != NULL)
8397         {
8398           size_t len = strlen (physname);
8399
8400           while (1)
8401             {
8402               if (physname[len] == ')') /* shortcut */
8403                 break;
8404               else if (check_modifier (physname, len, " const"))
8405                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8406               else if (check_modifier (physname, len, " volatile"))
8407                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8408               else
8409                 break;
8410             }
8411         }
8412     }
8413 }
8414
8415 /* Go objects should be embedded in a DW_TAG_module DIE,
8416    and it's not clear if/how imported objects will appear.
8417    To keep Go support simple until that's worked out,
8418    go back through what we've read and create something usable.
8419    We could do this while processing each DIE, and feels kinda cleaner,
8420    but that way is more invasive.
8421    This is to, for example, allow the user to type "p var" or "b main"
8422    without having to specify the package name, and allow lookups
8423    of module.object to work in contexts that use the expression
8424    parser.  */
8425
8426 static void
8427 fixup_go_packaging (struct dwarf2_cu *cu)
8428 {
8429   char *package_name = NULL;
8430   struct pending *list;
8431   int i;
8432
8433   for (list = global_symbols; list != NULL; list = list->next)
8434     {
8435       for (i = 0; i < list->nsyms; ++i)
8436         {
8437           struct symbol *sym = list->symbol[i];
8438
8439           if (SYMBOL_LANGUAGE (sym) == language_go
8440               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8441             {
8442               char *this_package_name = go_symbol_package_name (sym);
8443
8444               if (this_package_name == NULL)
8445                 continue;
8446               if (package_name == NULL)
8447                 package_name = this_package_name;
8448               else
8449                 {
8450                   if (strcmp (package_name, this_package_name) != 0)
8451                     complaint (&symfile_complaints,
8452                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8453                                (symbol_symtab (sym) != NULL
8454                                 ? symtab_to_filename_for_display
8455                                     (symbol_symtab (sym))
8456                                 : objfile_name (cu->objfile)),
8457                                this_package_name, package_name);
8458                   xfree (this_package_name);
8459                 }
8460             }
8461         }
8462     }
8463
8464   if (package_name != NULL)
8465     {
8466       struct objfile *objfile = cu->objfile;
8467       const char *saved_package_name
8468         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8469                                         package_name,
8470                                         strlen (package_name));
8471       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8472                                      saved_package_name);
8473       struct symbol *sym;
8474
8475       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8476
8477       sym = allocate_symbol (objfile);
8478       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8479       SYMBOL_SET_NAMES (sym, saved_package_name,
8480                         strlen (saved_package_name), 0, objfile);
8481       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8482          e.g., "main" finds the "main" module and not C's main().  */
8483       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8484       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8485       SYMBOL_TYPE (sym) = type;
8486
8487       add_symbol_to_list (sym, &global_symbols);
8488
8489       xfree (package_name);
8490     }
8491 }
8492
8493 /* Return the symtab for PER_CU.  This works properly regardless of
8494    whether we're using the index or psymtabs.  */
8495
8496 static struct compunit_symtab *
8497 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8498 {
8499   return (dwarf2_per_objfile->using_index
8500           ? per_cu->v.quick->compunit_symtab
8501           : per_cu->v.psymtab->compunit_symtab);
8502 }
8503
8504 /* A helper function for computing the list of all symbol tables
8505    included by PER_CU.  */
8506
8507 static void
8508 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8509                                 htab_t all_children, htab_t all_type_symtabs,
8510                                 struct dwarf2_per_cu_data *per_cu,
8511                                 struct compunit_symtab *immediate_parent)
8512 {
8513   void **slot;
8514   int ix;
8515   struct compunit_symtab *cust;
8516   struct dwarf2_per_cu_data *iter;
8517
8518   slot = htab_find_slot (all_children, per_cu, INSERT);
8519   if (*slot != NULL)
8520     {
8521       /* This inclusion and its children have been processed.  */
8522       return;
8523     }
8524
8525   *slot = per_cu;
8526   /* Only add a CU if it has a symbol table.  */
8527   cust = get_compunit_symtab (per_cu);
8528   if (cust != NULL)
8529     {
8530       /* If this is a type unit only add its symbol table if we haven't
8531          seen it yet (type unit per_cu's can share symtabs).  */
8532       if (per_cu->is_debug_types)
8533         {
8534           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8535           if (*slot == NULL)
8536             {
8537               *slot = cust;
8538               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8539               if (cust->user == NULL)
8540                 cust->user = immediate_parent;
8541             }
8542         }
8543       else
8544         {
8545           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8546           if (cust->user == NULL)
8547             cust->user = immediate_parent;
8548         }
8549     }
8550
8551   for (ix = 0;
8552        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8553        ++ix)
8554     {
8555       recursively_compute_inclusions (result, all_children,
8556                                       all_type_symtabs, iter, cust);
8557     }
8558 }
8559
8560 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8561    PER_CU.  */
8562
8563 static void
8564 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8565 {
8566   gdb_assert (! per_cu->is_debug_types);
8567
8568   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8569     {
8570       int ix, len;
8571       struct dwarf2_per_cu_data *per_cu_iter;
8572       struct compunit_symtab *compunit_symtab_iter;
8573       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8574       htab_t all_children, all_type_symtabs;
8575       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8576
8577       /* If we don't have a symtab, we can just skip this case.  */
8578       if (cust == NULL)
8579         return;
8580
8581       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8582                                         NULL, xcalloc, xfree);
8583       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8584                                             NULL, xcalloc, xfree);
8585
8586       for (ix = 0;
8587            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8588                         ix, per_cu_iter);
8589            ++ix)
8590         {
8591           recursively_compute_inclusions (&result_symtabs, all_children,
8592                                           all_type_symtabs, per_cu_iter,
8593                                           cust);
8594         }
8595
8596       /* Now we have a transitive closure of all the included symtabs.  */
8597       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8598       cust->includes
8599         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8600                      struct compunit_symtab *, len + 1);
8601       for (ix = 0;
8602            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8603                         compunit_symtab_iter);
8604            ++ix)
8605         cust->includes[ix] = compunit_symtab_iter;
8606       cust->includes[len] = NULL;
8607
8608       VEC_free (compunit_symtab_ptr, result_symtabs);
8609       htab_delete (all_children);
8610       htab_delete (all_type_symtabs);
8611     }
8612 }
8613
8614 /* Compute the 'includes' field for the symtabs of all the CUs we just
8615    read.  */
8616
8617 static void
8618 process_cu_includes (void)
8619 {
8620   int ix;
8621   struct dwarf2_per_cu_data *iter;
8622
8623   for (ix = 0;
8624        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8625                     ix, iter);
8626        ++ix)
8627     {
8628       if (! iter->is_debug_types)
8629         compute_compunit_symtab_includes (iter);
8630     }
8631
8632   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8633 }
8634
8635 /* Generate full symbol information for PER_CU, whose DIEs have
8636    already been loaded into memory.  */
8637
8638 static void
8639 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8640                         enum language pretend_language)
8641 {
8642   struct dwarf2_cu *cu = per_cu->cu;
8643   struct objfile *objfile = per_cu->objfile;
8644   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8645   CORE_ADDR lowpc, highpc;
8646   struct compunit_symtab *cust;
8647   struct cleanup *delayed_list_cleanup;
8648   CORE_ADDR baseaddr;
8649   struct block *static_block;
8650   CORE_ADDR addr;
8651
8652   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8653
8654   buildsym_init ();
8655   scoped_free_pendings free_pending;
8656   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8657
8658   cu->list_in_scope = &file_symbols;
8659
8660   cu->language = pretend_language;
8661   cu->language_defn = language_def (cu->language);
8662
8663   /* Do line number decoding in read_file_scope () */
8664   process_die (cu->dies, cu);
8665
8666   /* For now fudge the Go package.  */
8667   if (cu->language == language_go)
8668     fixup_go_packaging (cu);
8669
8670   /* Now that we have processed all the DIEs in the CU, all the types 
8671      should be complete, and it should now be safe to compute all of the
8672      physnames.  */
8673   compute_delayed_physnames (cu);
8674   do_cleanups (delayed_list_cleanup);
8675
8676   /* Some compilers don't define a DW_AT_high_pc attribute for the
8677      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8678      it, by scanning the DIE's below the compilation unit.  */
8679   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8680
8681   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8682   static_block = end_symtab_get_static_block (addr, 0, 1);
8683
8684   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8685      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8686      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8687      addrmap to help ensure it has an accurate map of pc values belonging to
8688      this comp unit.  */
8689   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8690
8691   cust = end_symtab_from_static_block (static_block,
8692                                        SECT_OFF_TEXT (objfile), 0);
8693
8694   if (cust != NULL)
8695     {
8696       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8697
8698       /* Set symtab language to language from DW_AT_language.  If the
8699          compilation is from a C file generated by language preprocessors, do
8700          not set the language if it was already deduced by start_subfile.  */
8701       if (!(cu->language == language_c
8702             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8703         COMPUNIT_FILETABS (cust)->language = cu->language;
8704
8705       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8706          produce DW_AT_location with location lists but it can be possibly
8707          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8708          there were bugs in prologue debug info, fixed later in GCC-4.5
8709          by "unwind info for epilogues" patch (which is not directly related).
8710
8711          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8712          needed, it would be wrong due to missing DW_AT_producer there.
8713
8714          Still one can confuse GDB by using non-standard GCC compilation
8715          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8716          */ 
8717       if (cu->has_loclist && gcc_4_minor >= 5)
8718         cust->locations_valid = 1;
8719
8720       if (gcc_4_minor >= 5)
8721         cust->epilogue_unwind_valid = 1;
8722
8723       cust->call_site_htab = cu->call_site_htab;
8724     }
8725
8726   if (dwarf2_per_objfile->using_index)
8727     per_cu->v.quick->compunit_symtab = cust;
8728   else
8729     {
8730       struct partial_symtab *pst = per_cu->v.psymtab;
8731       pst->compunit_symtab = cust;
8732       pst->readin = 1;
8733     }
8734
8735   /* Push it for inclusion processing later.  */
8736   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8737 }
8738
8739 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8740    already been loaded into memory.  */
8741
8742 static void
8743 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8744                         enum language pretend_language)
8745 {
8746   struct dwarf2_cu *cu = per_cu->cu;
8747   struct objfile *objfile = per_cu->objfile;
8748   struct compunit_symtab *cust;
8749   struct cleanup *delayed_list_cleanup;
8750   struct signatured_type *sig_type;
8751
8752   gdb_assert (per_cu->is_debug_types);
8753   sig_type = (struct signatured_type *) per_cu;
8754
8755   buildsym_init ();
8756   scoped_free_pendings free_pending;
8757   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8758
8759   cu->list_in_scope = &file_symbols;
8760
8761   cu->language = pretend_language;
8762   cu->language_defn = language_def (cu->language);
8763
8764   /* The symbol tables are set up in read_type_unit_scope.  */
8765   process_die (cu->dies, cu);
8766
8767   /* For now fudge the Go package.  */
8768   if (cu->language == language_go)
8769     fixup_go_packaging (cu);
8770
8771   /* Now that we have processed all the DIEs in the CU, all the types 
8772      should be complete, and it should now be safe to compute all of the
8773      physnames.  */
8774   compute_delayed_physnames (cu);
8775   do_cleanups (delayed_list_cleanup);
8776
8777   /* TUs share symbol tables.
8778      If this is the first TU to use this symtab, complete the construction
8779      of it with end_expandable_symtab.  Otherwise, complete the addition of
8780      this TU's symbols to the existing symtab.  */
8781   if (sig_type->type_unit_group->compunit_symtab == NULL)
8782     {
8783       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8784       sig_type->type_unit_group->compunit_symtab = cust;
8785
8786       if (cust != NULL)
8787         {
8788           /* Set symtab language to language from DW_AT_language.  If the
8789              compilation is from a C file generated by language preprocessors,
8790              do not set the language if it was already deduced by
8791              start_subfile.  */
8792           if (!(cu->language == language_c
8793                 && COMPUNIT_FILETABS (cust)->language != language_c))
8794             COMPUNIT_FILETABS (cust)->language = cu->language;
8795         }
8796     }
8797   else
8798     {
8799       augment_type_symtab ();
8800       cust = sig_type->type_unit_group->compunit_symtab;
8801     }
8802
8803   if (dwarf2_per_objfile->using_index)
8804     per_cu->v.quick->compunit_symtab = cust;
8805   else
8806     {
8807       struct partial_symtab *pst = per_cu->v.psymtab;
8808       pst->compunit_symtab = cust;
8809       pst->readin = 1;
8810     }
8811 }
8812
8813 /* Process an imported unit DIE.  */
8814
8815 static void
8816 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8817 {
8818   struct attribute *attr;
8819
8820   /* For now we don't handle imported units in type units.  */
8821   if (cu->per_cu->is_debug_types)
8822     {
8823       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8824                " supported in type units [in module %s]"),
8825              objfile_name (cu->objfile));
8826     }
8827
8828   attr = dwarf2_attr (die, DW_AT_import, cu);
8829   if (attr != NULL)
8830     {
8831       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8832       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8833       dwarf2_per_cu_data *per_cu
8834         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8835
8836       /* If necessary, add it to the queue and load its DIEs.  */
8837       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8838         load_full_comp_unit (per_cu, cu->language);
8839
8840       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8841                      per_cu);
8842     }
8843 }
8844
8845 /* RAII object that represents a process_die scope: i.e.,
8846    starts/finishes processing a DIE.  */
8847 class process_die_scope
8848 {
8849 public:
8850   process_die_scope (die_info *die, dwarf2_cu *cu)
8851     : m_die (die), m_cu (cu)
8852   {
8853     /* We should only be processing DIEs not already in process.  */
8854     gdb_assert (!m_die->in_process);
8855     m_die->in_process = true;
8856   }
8857
8858   ~process_die_scope ()
8859   {
8860     m_die->in_process = false;
8861
8862     /* If we're done processing the DIE for the CU that owns the line
8863        header, we don't need the line header anymore.  */
8864     if (m_cu->line_header_die_owner == m_die)
8865       {
8866         delete m_cu->line_header;
8867         m_cu->line_header = NULL;
8868         m_cu->line_header_die_owner = NULL;
8869       }
8870   }
8871
8872 private:
8873   die_info *m_die;
8874   dwarf2_cu *m_cu;
8875 };
8876
8877 /* Process a die and its children.  */
8878
8879 static void
8880 process_die (struct die_info *die, struct dwarf2_cu *cu)
8881 {
8882   process_die_scope scope (die, cu);
8883
8884   switch (die->tag)
8885     {
8886     case DW_TAG_padding:
8887       break;
8888     case DW_TAG_compile_unit:
8889     case DW_TAG_partial_unit:
8890       read_file_scope (die, cu);
8891       break;
8892     case DW_TAG_type_unit:
8893       read_type_unit_scope (die, cu);
8894       break;
8895     case DW_TAG_subprogram:
8896     case DW_TAG_inlined_subroutine:
8897       read_func_scope (die, cu);
8898       break;
8899     case DW_TAG_lexical_block:
8900     case DW_TAG_try_block:
8901     case DW_TAG_catch_block:
8902       read_lexical_block_scope (die, cu);
8903       break;
8904     case DW_TAG_call_site:
8905     case DW_TAG_GNU_call_site:
8906       read_call_site_scope (die, cu);
8907       break;
8908     case DW_TAG_class_type:
8909     case DW_TAG_interface_type:
8910     case DW_TAG_structure_type:
8911     case DW_TAG_union_type:
8912       process_structure_scope (die, cu);
8913       break;
8914     case DW_TAG_enumeration_type:
8915       process_enumeration_scope (die, cu);
8916       break;
8917
8918     /* These dies have a type, but processing them does not create
8919        a symbol or recurse to process the children.  Therefore we can
8920        read them on-demand through read_type_die.  */
8921     case DW_TAG_subroutine_type:
8922     case DW_TAG_set_type:
8923     case DW_TAG_array_type:
8924     case DW_TAG_pointer_type:
8925     case DW_TAG_ptr_to_member_type:
8926     case DW_TAG_reference_type:
8927     case DW_TAG_rvalue_reference_type:
8928     case DW_TAG_string_type:
8929       break;
8930
8931     case DW_TAG_base_type:
8932     case DW_TAG_subrange_type:
8933     case DW_TAG_typedef:
8934       /* Add a typedef symbol for the type definition, if it has a
8935          DW_AT_name.  */
8936       new_symbol (die, read_type_die (die, cu), cu);
8937       break;
8938     case DW_TAG_common_block:
8939       read_common_block (die, cu);
8940       break;
8941     case DW_TAG_common_inclusion:
8942       break;
8943     case DW_TAG_namespace:
8944       cu->processing_has_namespace_info = 1;
8945       read_namespace (die, cu);
8946       break;
8947     case DW_TAG_module:
8948       cu->processing_has_namespace_info = 1;
8949       read_module (die, cu);
8950       break;
8951     case DW_TAG_imported_declaration:
8952       cu->processing_has_namespace_info = 1;
8953       if (read_namespace_alias (die, cu))
8954         break;
8955       /* The declaration is not a global namespace alias: fall through.  */
8956     case DW_TAG_imported_module:
8957       cu->processing_has_namespace_info = 1;
8958       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8959                                  || cu->language != language_fortran))
8960         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8961                    dwarf_tag_name (die->tag));
8962       read_import_statement (die, cu);
8963       break;
8964
8965     case DW_TAG_imported_unit:
8966       process_imported_unit_die (die, cu);
8967       break;
8968
8969     default:
8970       new_symbol (die, NULL, cu);
8971       break;
8972     }
8973 }
8974 \f
8975 /* DWARF name computation.  */
8976
8977 /* A helper function for dwarf2_compute_name which determines whether DIE
8978    needs to have the name of the scope prepended to the name listed in the
8979    die.  */
8980
8981 static int
8982 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8983 {
8984   struct attribute *attr;
8985
8986   switch (die->tag)
8987     {
8988     case DW_TAG_namespace:
8989     case DW_TAG_typedef:
8990     case DW_TAG_class_type:
8991     case DW_TAG_interface_type:
8992     case DW_TAG_structure_type:
8993     case DW_TAG_union_type:
8994     case DW_TAG_enumeration_type:
8995     case DW_TAG_enumerator:
8996     case DW_TAG_subprogram:
8997     case DW_TAG_inlined_subroutine:
8998     case DW_TAG_member:
8999     case DW_TAG_imported_declaration:
9000       return 1;
9001
9002     case DW_TAG_variable:
9003     case DW_TAG_constant:
9004       /* We only need to prefix "globally" visible variables.  These include
9005          any variable marked with DW_AT_external or any variable that
9006          lives in a namespace.  [Variables in anonymous namespaces
9007          require prefixing, but they are not DW_AT_external.]  */
9008
9009       if (dwarf2_attr (die, DW_AT_specification, cu))
9010         {
9011           struct dwarf2_cu *spec_cu = cu;
9012
9013           return die_needs_namespace (die_specification (die, &spec_cu),
9014                                       spec_cu);
9015         }
9016
9017       attr = dwarf2_attr (die, DW_AT_external, cu);
9018       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9019           && die->parent->tag != DW_TAG_module)
9020         return 0;
9021       /* A variable in a lexical block of some kind does not need a
9022          namespace, even though in C++ such variables may be external
9023          and have a mangled name.  */
9024       if (die->parent->tag ==  DW_TAG_lexical_block
9025           || die->parent->tag ==  DW_TAG_try_block
9026           || die->parent->tag ==  DW_TAG_catch_block
9027           || die->parent->tag == DW_TAG_subprogram)
9028         return 0;
9029       return 1;
9030
9031     default:
9032       return 0;
9033     }
9034 }
9035
9036 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9037    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9038    defined for the given DIE.  */
9039
9040 static struct attribute *
9041 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9042 {
9043   struct attribute *attr;
9044
9045   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9046   if (attr == NULL)
9047     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9048
9049   return attr;
9050 }
9051
9052 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9053    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9054    defined for the given DIE.  */
9055
9056 static const char *
9057 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9058 {
9059   const char *linkage_name;
9060
9061   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9062   if (linkage_name == NULL)
9063     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9064
9065   return linkage_name;
9066 }
9067
9068 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9069    compute the physname for the object, which include a method's:
9070    - formal parameters (C++),
9071    - receiver type (Go),
9072
9073    The term "physname" is a bit confusing.
9074    For C++, for example, it is the demangled name.
9075    For Go, for example, it's the mangled name.
9076
9077    For Ada, return the DIE's linkage name rather than the fully qualified
9078    name.  PHYSNAME is ignored..
9079
9080    The result is allocated on the objfile_obstack and canonicalized.  */
9081
9082 static const char *
9083 dwarf2_compute_name (const char *name,
9084                      struct die_info *die, struct dwarf2_cu *cu,
9085                      int physname)
9086 {
9087   struct objfile *objfile = cu->objfile;
9088
9089   if (name == NULL)
9090     name = dwarf2_name (die, cu);
9091
9092   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9093      but otherwise compute it by typename_concat inside GDB.
9094      FIXME: Actually this is not really true, or at least not always true.
9095      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9096      Fortran names because there is no mangling standard.  So new_symbol_full
9097      will set the demangled name to the result of dwarf2_full_name, and it is
9098      the demangled name that GDB uses if it exists.  */
9099   if (cu->language == language_ada
9100       || (cu->language == language_fortran && physname))
9101     {
9102       /* For Ada unit, we prefer the linkage name over the name, as
9103          the former contains the exported name, which the user expects
9104          to be able to reference.  Ideally, we want the user to be able
9105          to reference this entity using either natural or linkage name,
9106          but we haven't started looking at this enhancement yet.  */
9107       const char *linkage_name = dw2_linkage_name (die, cu);
9108
9109       if (linkage_name != NULL)
9110         return linkage_name;
9111     }
9112
9113   /* These are the only languages we know how to qualify names in.  */
9114   if (name != NULL
9115       && (cu->language == language_cplus
9116           || cu->language == language_fortran || cu->language == language_d
9117           || cu->language == language_rust))
9118     {
9119       if (die_needs_namespace (die, cu))
9120         {
9121           long length;
9122           const char *prefix;
9123           const char *canonical_name = NULL;
9124
9125           string_file buf;
9126
9127           prefix = determine_prefix (die, cu);
9128           if (*prefix != '\0')
9129             {
9130               char *prefixed_name = typename_concat (NULL, prefix, name,
9131                                                      physname, cu);
9132
9133               buf.puts (prefixed_name);
9134               xfree (prefixed_name);
9135             }
9136           else
9137             buf.puts (name);
9138
9139           /* Template parameters may be specified in the DIE's DW_AT_name, or
9140              as children with DW_TAG_template_type_param or
9141              DW_TAG_value_type_param.  If the latter, add them to the name
9142              here.  If the name already has template parameters, then
9143              skip this step; some versions of GCC emit both, and
9144              it is more efficient to use the pre-computed name.
9145
9146              Something to keep in mind about this process: it is very
9147              unlikely, or in some cases downright impossible, to produce
9148              something that will match the mangled name of a function.
9149              If the definition of the function has the same debug info,
9150              we should be able to match up with it anyway.  But fallbacks
9151              using the minimal symbol, for instance to find a method
9152              implemented in a stripped copy of libstdc++, will not work.
9153              If we do not have debug info for the definition, we will have to
9154              match them up some other way.
9155
9156              When we do name matching there is a related problem with function
9157              templates; two instantiated function templates are allowed to
9158              differ only by their return types, which we do not add here.  */
9159
9160           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9161             {
9162               struct attribute *attr;
9163               struct die_info *child;
9164               int first = 1;
9165
9166               die->building_fullname = 1;
9167
9168               for (child = die->child; child != NULL; child = child->sibling)
9169                 {
9170                   struct type *type;
9171                   LONGEST value;
9172                   const gdb_byte *bytes;
9173                   struct dwarf2_locexpr_baton *baton;
9174                   struct value *v;
9175
9176                   if (child->tag != DW_TAG_template_type_param
9177                       && child->tag != DW_TAG_template_value_param)
9178                     continue;
9179
9180                   if (first)
9181                     {
9182                       buf.puts ("<");
9183                       first = 0;
9184                     }
9185                   else
9186                     buf.puts (", ");
9187
9188                   attr = dwarf2_attr (child, DW_AT_type, cu);
9189                   if (attr == NULL)
9190                     {
9191                       complaint (&symfile_complaints,
9192                                  _("template parameter missing DW_AT_type"));
9193                       buf.puts ("UNKNOWN_TYPE");
9194                       continue;
9195                     }
9196                   type = die_type (child, cu);
9197
9198                   if (child->tag == DW_TAG_template_type_param)
9199                     {
9200                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9201                       continue;
9202                     }
9203
9204                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9205                   if (attr == NULL)
9206                     {
9207                       complaint (&symfile_complaints,
9208                                  _("template parameter missing "
9209                                    "DW_AT_const_value"));
9210                       buf.puts ("UNKNOWN_VALUE");
9211                       continue;
9212                     }
9213
9214                   dwarf2_const_value_attr (attr, type, name,
9215                                            &cu->comp_unit_obstack, cu,
9216                                            &value, &bytes, &baton);
9217
9218                   if (TYPE_NOSIGN (type))
9219                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9220                        changed, this can use value_print instead.  */
9221                     c_printchar (value, type, &buf);
9222                   else
9223                     {
9224                       struct value_print_options opts;
9225
9226                       if (baton != NULL)
9227                         v = dwarf2_evaluate_loc_desc (type, NULL,
9228                                                       baton->data,
9229                                                       baton->size,
9230                                                       baton->per_cu);
9231                       else if (bytes != NULL)
9232                         {
9233                           v = allocate_value (type);
9234                           memcpy (value_contents_writeable (v), bytes,
9235                                   TYPE_LENGTH (type));
9236                         }
9237                       else
9238                         v = value_from_longest (type, value);
9239
9240                       /* Specify decimal so that we do not depend on
9241                          the radix.  */
9242                       get_formatted_print_options (&opts, 'd');
9243                       opts.raw = 1;
9244                       value_print (v, &buf, &opts);
9245                       release_value (v);
9246                       value_free (v);
9247                     }
9248                 }
9249
9250               die->building_fullname = 0;
9251
9252               if (!first)
9253                 {
9254                   /* Close the argument list, with a space if necessary
9255                      (nested templates).  */
9256                   if (!buf.empty () && buf.string ().back () == '>')
9257                     buf.puts (" >");
9258                   else
9259                     buf.puts (">");
9260                 }
9261             }
9262
9263           /* For C++ methods, append formal parameter type
9264              information, if PHYSNAME.  */
9265
9266           if (physname && die->tag == DW_TAG_subprogram
9267               && cu->language == language_cplus)
9268             {
9269               struct type *type = read_type_die (die, cu);
9270
9271               c_type_print_args (type, &buf, 1, cu->language,
9272                                  &type_print_raw_options);
9273
9274               if (cu->language == language_cplus)
9275                 {
9276                   /* Assume that an artificial first parameter is
9277                      "this", but do not crash if it is not.  RealView
9278                      marks unnamed (and thus unused) parameters as
9279                      artificial; there is no way to differentiate
9280                      the two cases.  */
9281                   if (TYPE_NFIELDS (type) > 0
9282                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9283                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9284                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9285                                                                         0))))
9286                     buf.puts (" const");
9287                 }
9288             }
9289
9290           const std::string &intermediate_name = buf.string ();
9291
9292           if (cu->language == language_cplus)
9293             canonical_name
9294               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9295                                           &objfile->per_bfd->storage_obstack);
9296
9297           /* If we only computed INTERMEDIATE_NAME, or if
9298              INTERMEDIATE_NAME is already canonical, then we need to
9299              copy it to the appropriate obstack.  */
9300           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9301             name = ((const char *)
9302                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9303                                    intermediate_name.c_str (),
9304                                    intermediate_name.length ()));
9305           else
9306             name = canonical_name;
9307         }
9308     }
9309
9310   return name;
9311 }
9312
9313 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9314    If scope qualifiers are appropriate they will be added.  The result
9315    will be allocated on the storage_obstack, or NULL if the DIE does
9316    not have a name.  NAME may either be from a previous call to
9317    dwarf2_name or NULL.
9318
9319    The output string will be canonicalized (if C++).  */
9320
9321 static const char *
9322 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9323 {
9324   return dwarf2_compute_name (name, die, cu, 0);
9325 }
9326
9327 /* Construct a physname for the given DIE in CU.  NAME may either be
9328    from a previous call to dwarf2_name or NULL.  The result will be
9329    allocated on the objfile_objstack or NULL if the DIE does not have a
9330    name.
9331
9332    The output string will be canonicalized (if C++).  */
9333
9334 static const char *
9335 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9336 {
9337   struct objfile *objfile = cu->objfile;
9338   const char *retval, *mangled = NULL, *canon = NULL;
9339   int need_copy = 1;
9340
9341   /* In this case dwarf2_compute_name is just a shortcut not building anything
9342      on its own.  */
9343   if (!die_needs_namespace (die, cu))
9344     return dwarf2_compute_name (name, die, cu, 1);
9345
9346   mangled = dw2_linkage_name (die, cu);
9347
9348   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9349      See https://github.com/rust-lang/rust/issues/32925.  */
9350   if (cu->language == language_rust && mangled != NULL
9351       && strchr (mangled, '{') != NULL)
9352     mangled = NULL;
9353
9354   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9355      has computed.  */
9356   gdb::unique_xmalloc_ptr<char> demangled;
9357   if (mangled != NULL)
9358     {
9359       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9360          type.  It is easier for GDB users to search for such functions as
9361          `name(params)' than `long name(params)'.  In such case the minimal
9362          symbol names do not match the full symbol names but for template
9363          functions there is never a need to look up their definition from their
9364          declaration so the only disadvantage remains the minimal symbol
9365          variant `long name(params)' does not have the proper inferior type.
9366          */
9367
9368       if (cu->language == language_go)
9369         {
9370           /* This is a lie, but we already lie to the caller new_symbol_full.
9371              new_symbol_full assumes we return the mangled name.
9372              This just undoes that lie until things are cleaned up.  */
9373         }
9374       else
9375         {
9376           demangled.reset (gdb_demangle (mangled,
9377                                          (DMGL_PARAMS | DMGL_ANSI
9378                                           | DMGL_RET_DROP)));
9379         }
9380       if (demangled)
9381         canon = demangled.get ();
9382       else
9383         {
9384           canon = mangled;
9385           need_copy = 0;
9386         }
9387     }
9388
9389   if (canon == NULL || check_physname)
9390     {
9391       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9392
9393       if (canon != NULL && strcmp (physname, canon) != 0)
9394         {
9395           /* It may not mean a bug in GDB.  The compiler could also
9396              compute DW_AT_linkage_name incorrectly.  But in such case
9397              GDB would need to be bug-to-bug compatible.  */
9398
9399           complaint (&symfile_complaints,
9400                      _("Computed physname <%s> does not match demangled <%s> "
9401                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9402                      physname, canon, mangled, to_underlying (die->sect_off),
9403                      objfile_name (objfile));
9404
9405           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9406              is available here - over computed PHYSNAME.  It is safer
9407              against both buggy GDB and buggy compilers.  */
9408
9409           retval = canon;
9410         }
9411       else
9412         {
9413           retval = physname;
9414           need_copy = 0;
9415         }
9416     }
9417   else
9418     retval = canon;
9419
9420   if (need_copy)
9421     retval = ((const char *)
9422               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9423                              retval, strlen (retval)));
9424
9425   return retval;
9426 }
9427
9428 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9429    a new symbol for it.
9430
9431    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9432
9433 static int
9434 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9435 {
9436   struct attribute *attr;
9437
9438   /* If the die does not have a name, this is not a namespace
9439      alias.  */
9440   attr = dwarf2_attr (die, DW_AT_name, cu);
9441   if (attr != NULL)
9442     {
9443       int num;
9444       struct die_info *d = die;
9445       struct dwarf2_cu *imported_cu = cu;
9446
9447       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9448          keep inspecting DIEs until we hit the underlying import.  */
9449 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9450       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9451         {
9452           attr = dwarf2_attr (d, DW_AT_import, cu);
9453           if (attr == NULL)
9454             break;
9455
9456           d = follow_die_ref (d, attr, &imported_cu);
9457           if (d->tag != DW_TAG_imported_declaration)
9458             break;
9459         }
9460
9461       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9462         {
9463           complaint (&symfile_complaints,
9464                      _("DIE at 0x%x has too many recursively imported "
9465                        "declarations"), to_underlying (d->sect_off));
9466           return 0;
9467         }
9468
9469       if (attr != NULL)
9470         {
9471           struct type *type;
9472           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9473
9474           type = get_die_type_at_offset (sect_off, cu->per_cu);
9475           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9476             {
9477               /* This declaration is a global namespace alias.  Add
9478                  a symbol for it whose type is the aliased namespace.  */
9479               new_symbol (die, type, cu);
9480               return 1;
9481             }
9482         }
9483     }
9484
9485   return 0;
9486 }
9487
9488 /* Return the using directives repository (global or local?) to use in the
9489    current context for LANGUAGE.
9490
9491    For Ada, imported declarations can materialize renamings, which *may* be
9492    global.  However it is impossible (for now?) in DWARF to distinguish
9493    "external" imported declarations and "static" ones.  As all imported
9494    declarations seem to be static in all other languages, make them all CU-wide
9495    global only in Ada.  */
9496
9497 static struct using_direct **
9498 using_directives (enum language language)
9499 {
9500   if (language == language_ada && context_stack_depth == 0)
9501     return &global_using_directives;
9502   else
9503     return &local_using_directives;
9504 }
9505
9506 /* Read the import statement specified by the given die and record it.  */
9507
9508 static void
9509 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9510 {
9511   struct objfile *objfile = cu->objfile;
9512   struct attribute *import_attr;
9513   struct die_info *imported_die, *child_die;
9514   struct dwarf2_cu *imported_cu;
9515   const char *imported_name;
9516   const char *imported_name_prefix;
9517   const char *canonical_name;
9518   const char *import_alias;
9519   const char *imported_declaration = NULL;
9520   const char *import_prefix;
9521   std::vector<const char *> excludes;
9522
9523   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9524   if (import_attr == NULL)
9525     {
9526       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9527                  dwarf_tag_name (die->tag));
9528       return;
9529     }
9530
9531   imported_cu = cu;
9532   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9533   imported_name = dwarf2_name (imported_die, imported_cu);
9534   if (imported_name == NULL)
9535     {
9536       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9537
9538         The import in the following code:
9539         namespace A
9540           {
9541             typedef int B;
9542           }
9543
9544         int main ()
9545           {
9546             using A::B;
9547             B b;
9548             return b;
9549           }
9550
9551         ...
9552          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9553             <52>   DW_AT_decl_file   : 1
9554             <53>   DW_AT_decl_line   : 6
9555             <54>   DW_AT_import      : <0x75>
9556          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9557             <59>   DW_AT_name        : B
9558             <5b>   DW_AT_decl_file   : 1
9559             <5c>   DW_AT_decl_line   : 2
9560             <5d>   DW_AT_type        : <0x6e>
9561         ...
9562          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9563             <76>   DW_AT_byte_size   : 4
9564             <77>   DW_AT_encoding    : 5        (signed)
9565
9566         imports the wrong die ( 0x75 instead of 0x58 ).
9567         This case will be ignored until the gcc bug is fixed.  */
9568       return;
9569     }
9570
9571   /* Figure out the local name after import.  */
9572   import_alias = dwarf2_name (die, cu);
9573
9574   /* Figure out where the statement is being imported to.  */
9575   import_prefix = determine_prefix (die, cu);
9576
9577   /* Figure out what the scope of the imported die is and prepend it
9578      to the name of the imported die.  */
9579   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9580
9581   if (imported_die->tag != DW_TAG_namespace
9582       && imported_die->tag != DW_TAG_module)
9583     {
9584       imported_declaration = imported_name;
9585       canonical_name = imported_name_prefix;
9586     }
9587   else if (strlen (imported_name_prefix) > 0)
9588     canonical_name = obconcat (&objfile->objfile_obstack,
9589                                imported_name_prefix,
9590                                (cu->language == language_d ? "." : "::"),
9591                                imported_name, (char *) NULL);
9592   else
9593     canonical_name = imported_name;
9594
9595   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9596     for (child_die = die->child; child_die && child_die->tag;
9597          child_die = sibling_die (child_die))
9598       {
9599         /* DWARF-4: A Fortran use statement with a “rename list” may be
9600            represented by an imported module entry with an import attribute
9601            referring to the module and owned entries corresponding to those
9602            entities that are renamed as part of being imported.  */
9603
9604         if (child_die->tag != DW_TAG_imported_declaration)
9605           {
9606             complaint (&symfile_complaints,
9607                        _("child DW_TAG_imported_declaration expected "
9608                          "- DIE at 0x%x [in module %s]"),
9609                        to_underlying (child_die->sect_off), objfile_name (objfile));
9610             continue;
9611           }
9612
9613         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9614         if (import_attr == NULL)
9615           {
9616             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9617                        dwarf_tag_name (child_die->tag));
9618             continue;
9619           }
9620
9621         imported_cu = cu;
9622         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9623                                               &imported_cu);
9624         imported_name = dwarf2_name (imported_die, imported_cu);
9625         if (imported_name == NULL)
9626           {
9627             complaint (&symfile_complaints,
9628                        _("child DW_TAG_imported_declaration has unknown "
9629                          "imported name - DIE at 0x%x [in module %s]"),
9630                        to_underlying (child_die->sect_off), objfile_name (objfile));
9631             continue;
9632           }
9633
9634         excludes.push_back (imported_name);
9635
9636         process_die (child_die, cu);
9637       }
9638
9639   add_using_directive (using_directives (cu->language),
9640                        import_prefix,
9641                        canonical_name,
9642                        import_alias,
9643                        imported_declaration,
9644                        excludes,
9645                        0,
9646                        &objfile->objfile_obstack);
9647 }
9648
9649 /* ICC<14 does not output the required DW_AT_declaration on incomplete
9650    types, but gives them a size of zero.  Starting with version 14,
9651    ICC is compatible with GCC.  */
9652
9653 static int
9654 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
9655 {
9656   if (!cu->checked_producer)
9657     check_producer (cu);
9658
9659   return cu->producer_is_icc_lt_14;
9660 }
9661
9662 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9663    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9664    this, it was first present in GCC release 4.3.0.  */
9665
9666 static int
9667 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9668 {
9669   if (!cu->checked_producer)
9670     check_producer (cu);
9671
9672   return cu->producer_is_gcc_lt_4_3;
9673 }
9674
9675 static file_and_directory
9676 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9677 {
9678   file_and_directory res;
9679
9680   /* Find the filename.  Do not use dwarf2_name here, since the filename
9681      is not a source language identifier.  */
9682   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9683   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9684
9685   if (res.comp_dir == NULL
9686       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9687       && IS_ABSOLUTE_PATH (res.name))
9688     {
9689       res.comp_dir_storage = ldirname (res.name);
9690       if (!res.comp_dir_storage.empty ())
9691         res.comp_dir = res.comp_dir_storage.c_str ();
9692     }
9693   if (res.comp_dir != NULL)
9694     {
9695       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9696          directory, get rid of it.  */
9697       const char *cp = strchr (res.comp_dir, ':');
9698
9699       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9700         res.comp_dir = cp + 1;
9701     }
9702
9703   if (res.name == NULL)
9704     res.name = "<unknown>";
9705
9706   return res;
9707 }
9708
9709 /* Handle DW_AT_stmt_list for a compilation unit.
9710    DIE is the DW_TAG_compile_unit die for CU.
9711    COMP_DIR is the compilation directory.  LOWPC is passed to
9712    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9713
9714 static void
9715 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9716                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9717 {
9718   struct objfile *objfile = dwarf2_per_objfile->objfile;
9719   struct attribute *attr;
9720   struct line_header line_header_local;
9721   hashval_t line_header_local_hash;
9722   unsigned u;
9723   void **slot;
9724   int decode_mapping;
9725
9726   gdb_assert (! cu->per_cu->is_debug_types);
9727
9728   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9729   if (attr == NULL)
9730     return;
9731
9732   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9733
9734   /* The line header hash table is only created if needed (it exists to
9735      prevent redundant reading of the line table for partial_units).
9736      If we're given a partial_unit, we'll need it.  If we're given a
9737      compile_unit, then use the line header hash table if it's already
9738      created, but don't create one just yet.  */
9739
9740   if (dwarf2_per_objfile->line_header_hash == NULL
9741       && die->tag == DW_TAG_partial_unit)
9742     {
9743       dwarf2_per_objfile->line_header_hash
9744         = htab_create_alloc_ex (127, line_header_hash_voidp,
9745                                 line_header_eq_voidp,
9746                                 free_line_header_voidp,
9747                                 &objfile->objfile_obstack,
9748                                 hashtab_obstack_allocate,
9749                                 dummy_obstack_deallocate);
9750     }
9751
9752   line_header_local.sect_off = line_offset;
9753   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9754   line_header_local_hash = line_header_hash (&line_header_local);
9755   if (dwarf2_per_objfile->line_header_hash != NULL)
9756     {
9757       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9758                                        &line_header_local,
9759                                        line_header_local_hash, NO_INSERT);
9760
9761       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9762          is not present in *SLOT (since if there is something in *SLOT then
9763          it will be for a partial_unit).  */
9764       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9765         {
9766           gdb_assert (*slot != NULL);
9767           cu->line_header = (struct line_header *) *slot;
9768           return;
9769         }
9770     }
9771
9772   /* dwarf_decode_line_header does not yet provide sufficient information.
9773      We always have to call also dwarf_decode_lines for it.  */
9774   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9775   if (lh == NULL)
9776     return;
9777
9778   cu->line_header = lh.release ();
9779   cu->line_header_die_owner = die;
9780
9781   if (dwarf2_per_objfile->line_header_hash == NULL)
9782     slot = NULL;
9783   else
9784     {
9785       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9786                                        &line_header_local,
9787                                        line_header_local_hash, INSERT);
9788       gdb_assert (slot != NULL);
9789     }
9790   if (slot != NULL && *slot == NULL)
9791     {
9792       /* This newly decoded line number information unit will be owned
9793          by line_header_hash hash table.  */
9794       *slot = cu->line_header;
9795       cu->line_header_die_owner = NULL;
9796     }
9797   else
9798     {
9799       /* We cannot free any current entry in (*slot) as that struct line_header
9800          may be already used by multiple CUs.  Create only temporary decoded
9801          line_header for this CU - it may happen at most once for each line
9802          number information unit.  And if we're not using line_header_hash
9803          then this is what we want as well.  */
9804       gdb_assert (die->tag != DW_TAG_partial_unit);
9805     }
9806   decode_mapping = (die->tag != DW_TAG_partial_unit);
9807   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9808                       decode_mapping);
9809
9810 }
9811
9812 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9813
9814 static void
9815 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9816 {
9817   struct objfile *objfile = dwarf2_per_objfile->objfile;
9818   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9819   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9820   CORE_ADDR highpc = ((CORE_ADDR) 0);
9821   struct attribute *attr;
9822   struct die_info *child_die;
9823   CORE_ADDR baseaddr;
9824
9825   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9826
9827   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9828
9829   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9830      from finish_block.  */
9831   if (lowpc == ((CORE_ADDR) -1))
9832     lowpc = highpc;
9833   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9834
9835   file_and_directory fnd = find_file_and_directory (die, cu);
9836
9837   prepare_one_comp_unit (cu, die, cu->language);
9838
9839   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9840      standardised yet.  As a workaround for the language detection we fall
9841      back to the DW_AT_producer string.  */
9842   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9843     cu->language = language_opencl;
9844
9845   /* Similar hack for Go.  */
9846   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9847     set_cu_language (DW_LANG_Go, cu);
9848
9849   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9850
9851   /* Decode line number information if present.  We do this before
9852      processing child DIEs, so that the line header table is available
9853      for DW_AT_decl_file.  */
9854   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9855
9856   /* Process all dies in compilation unit.  */
9857   if (die->child != NULL)
9858     {
9859       child_die = die->child;
9860       while (child_die && child_die->tag)
9861         {
9862           process_die (child_die, cu);
9863           child_die = sibling_die (child_die);
9864         }
9865     }
9866
9867   /* Decode macro information, if present.  Dwarf 2 macro information
9868      refers to information in the line number info statement program
9869      header, so we can only read it if we've read the header
9870      successfully.  */
9871   attr = dwarf2_attr (die, DW_AT_macros, cu);
9872   if (attr == NULL)
9873     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9874   if (attr && cu->line_header)
9875     {
9876       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9877         complaint (&symfile_complaints,
9878                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9879
9880       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9881     }
9882   else
9883     {
9884       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9885       if (attr && cu->line_header)
9886         {
9887           unsigned int macro_offset = DW_UNSND (attr);
9888
9889           dwarf_decode_macros (cu, macro_offset, 0);
9890         }
9891     }
9892 }
9893
9894 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9895    Create the set of symtabs used by this TU, or if this TU is sharing
9896    symtabs with another TU and the symtabs have already been created
9897    then restore those symtabs in the line header.
9898    We don't need the pc/line-number mapping for type units.  */
9899
9900 static void
9901 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9902 {
9903   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9904   struct type_unit_group *tu_group;
9905   int first_time;
9906   struct attribute *attr;
9907   unsigned int i;
9908   struct signatured_type *sig_type;
9909
9910   gdb_assert (per_cu->is_debug_types);
9911   sig_type = (struct signatured_type *) per_cu;
9912
9913   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9914
9915   /* If we're using .gdb_index (includes -readnow) then
9916      per_cu->type_unit_group may not have been set up yet.  */
9917   if (sig_type->type_unit_group == NULL)
9918     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9919   tu_group = sig_type->type_unit_group;
9920
9921   /* If we've already processed this stmt_list there's no real need to
9922      do it again, we could fake it and just recreate the part we need
9923      (file name,index -> symtab mapping).  If data shows this optimization
9924      is useful we can do it then.  */
9925   first_time = tu_group->compunit_symtab == NULL;
9926
9927   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9928      debug info.  */
9929   line_header_up lh;
9930   if (attr != NULL)
9931     {
9932       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9933       lh = dwarf_decode_line_header (line_offset, cu);
9934     }
9935   if (lh == NULL)
9936     {
9937       if (first_time)
9938         dwarf2_start_symtab (cu, "", NULL, 0);
9939       else
9940         {
9941           gdb_assert (tu_group->symtabs == NULL);
9942           restart_symtab (tu_group->compunit_symtab, "", 0);
9943         }
9944       return;
9945     }
9946
9947   cu->line_header = lh.release ();
9948   cu->line_header_die_owner = die;
9949
9950   if (first_time)
9951     {
9952       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9953
9954       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9955          still initializing it, and our caller (a few levels up)
9956          process_full_type_unit still needs to know if this is the first
9957          time.  */
9958
9959       tu_group->num_symtabs = cu->line_header->file_names.size ();
9960       tu_group->symtabs = XNEWVEC (struct symtab *,
9961                                    cu->line_header->file_names.size ());
9962
9963       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9964         {
9965           file_entry &fe = cu->line_header->file_names[i];
9966
9967           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9968
9969           if (current_subfile->symtab == NULL)
9970             {
9971               /* NOTE: start_subfile will recognize when it's been
9972                  passed a file it has already seen.  So we can't
9973                  assume there's a simple mapping from
9974                  cu->line_header->file_names to subfiles, plus
9975                  cu->line_header->file_names may contain dups.  */
9976               current_subfile->symtab
9977                 = allocate_symtab (cust, current_subfile->name);
9978             }
9979
9980           fe.symtab = current_subfile->symtab;
9981           tu_group->symtabs[i] = fe.symtab;
9982         }
9983     }
9984   else
9985     {
9986       restart_symtab (tu_group->compunit_symtab, "", 0);
9987
9988       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9989         {
9990           file_entry &fe = cu->line_header->file_names[i];
9991
9992           fe.symtab = tu_group->symtabs[i];
9993         }
9994     }
9995
9996   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9997      so they don't have a "real" (so to speak) symtab anyway.
9998      There is later code that will assign the main symtab to all symbols
9999      that don't have one.  We need to handle the case of a symbol with a
10000      missing symtab (DW_AT_decl_file) anyway.  */
10001 }
10002
10003 /* Process DW_TAG_type_unit.
10004    For TUs we want to skip the first top level sibling if it's not the
10005    actual type being defined by this TU.  In this case the first top
10006    level sibling is there to provide context only.  */
10007
10008 static void
10009 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10010 {
10011   struct die_info *child_die;
10012
10013   prepare_one_comp_unit (cu, die, language_minimal);
10014
10015   /* Initialize (or reinitialize) the machinery for building symtabs.
10016      We do this before processing child DIEs, so that the line header table
10017      is available for DW_AT_decl_file.  */
10018   setup_type_unit_groups (die, cu);
10019
10020   if (die->child != NULL)
10021     {
10022       child_die = die->child;
10023       while (child_die && child_die->tag)
10024         {
10025           process_die (child_die, cu);
10026           child_die = sibling_die (child_die);
10027         }
10028     }
10029 }
10030 \f
10031 /* DWO/DWP files.
10032
10033    http://gcc.gnu.org/wiki/DebugFission
10034    http://gcc.gnu.org/wiki/DebugFissionDWP
10035
10036    To simplify handling of both DWO files ("object" files with the DWARF info)
10037    and DWP files (a file with the DWOs packaged up into one file), we treat
10038    DWP files as having a collection of virtual DWO files.  */
10039
10040 static hashval_t
10041 hash_dwo_file (const void *item)
10042 {
10043   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10044   hashval_t hash;
10045
10046   hash = htab_hash_string (dwo_file->dwo_name);
10047   if (dwo_file->comp_dir != NULL)
10048     hash += htab_hash_string (dwo_file->comp_dir);
10049   return hash;
10050 }
10051
10052 static int
10053 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10054 {
10055   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10056   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10057
10058   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10059     return 0;
10060   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10061     return lhs->comp_dir == rhs->comp_dir;
10062   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10063 }
10064
10065 /* Allocate a hash table for DWO files.  */
10066
10067 static htab_t
10068 allocate_dwo_file_hash_table (void)
10069 {
10070   struct objfile *objfile = dwarf2_per_objfile->objfile;
10071
10072   return htab_create_alloc_ex (41,
10073                                hash_dwo_file,
10074                                eq_dwo_file,
10075                                NULL,
10076                                &objfile->objfile_obstack,
10077                                hashtab_obstack_allocate,
10078                                dummy_obstack_deallocate);
10079 }
10080
10081 /* Lookup DWO file DWO_NAME.  */
10082
10083 static void **
10084 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10085 {
10086   struct dwo_file find_entry;
10087   void **slot;
10088
10089   if (dwarf2_per_objfile->dwo_files == NULL)
10090     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10091
10092   memset (&find_entry, 0, sizeof (find_entry));
10093   find_entry.dwo_name = dwo_name;
10094   find_entry.comp_dir = comp_dir;
10095   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10096
10097   return slot;
10098 }
10099
10100 static hashval_t
10101 hash_dwo_unit (const void *item)
10102 {
10103   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10104
10105   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10106   return dwo_unit->signature;
10107 }
10108
10109 static int
10110 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10111 {
10112   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10113   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10114
10115   /* The signature is assumed to be unique within the DWO file.
10116      So while object file CU dwo_id's always have the value zero,
10117      that's OK, assuming each object file DWO file has only one CU,
10118      and that's the rule for now.  */
10119   return lhs->signature == rhs->signature;
10120 }
10121
10122 /* Allocate a hash table for DWO CUs,TUs.
10123    There is one of these tables for each of CUs,TUs for each DWO file.  */
10124
10125 static htab_t
10126 allocate_dwo_unit_table (struct objfile *objfile)
10127 {
10128   /* Start out with a pretty small number.
10129      Generally DWO files contain only one CU and maybe some TUs.  */
10130   return htab_create_alloc_ex (3,
10131                                hash_dwo_unit,
10132                                eq_dwo_unit,
10133                                NULL,
10134                                &objfile->objfile_obstack,
10135                                hashtab_obstack_allocate,
10136                                dummy_obstack_deallocate);
10137 }
10138
10139 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10140
10141 struct create_dwo_cu_data
10142 {
10143   struct dwo_file *dwo_file;
10144   struct dwo_unit dwo_unit;
10145 };
10146
10147 /* die_reader_func for create_dwo_cu.  */
10148
10149 static void
10150 create_dwo_cu_reader (const struct die_reader_specs *reader,
10151                       const gdb_byte *info_ptr,
10152                       struct die_info *comp_unit_die,
10153                       int has_children,
10154                       void *datap)
10155 {
10156   struct dwarf2_cu *cu = reader->cu;
10157   sect_offset sect_off = cu->per_cu->sect_off;
10158   struct dwarf2_section_info *section = cu->per_cu->section;
10159   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10160   struct dwo_file *dwo_file = data->dwo_file;
10161   struct dwo_unit *dwo_unit = &data->dwo_unit;
10162   struct attribute *attr;
10163
10164   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10165   if (attr == NULL)
10166     {
10167       complaint (&symfile_complaints,
10168                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10169                    " its dwo_id [in module %s]"),
10170                  to_underlying (sect_off), dwo_file->dwo_name);
10171       return;
10172     }
10173
10174   dwo_unit->dwo_file = dwo_file;
10175   dwo_unit->signature = DW_UNSND (attr);
10176   dwo_unit->section = section;
10177   dwo_unit->sect_off = sect_off;
10178   dwo_unit->length = cu->per_cu->length;
10179
10180   if (dwarf_read_debug)
10181     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10182                         to_underlying (sect_off),
10183                         hex_string (dwo_unit->signature));
10184 }
10185
10186 /* Create the dwo_units for the CUs in a DWO_FILE.
10187    Note: This function processes DWO files only, not DWP files.  */
10188
10189 static void
10190 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10191                        htab_t &cus_htab)
10192 {
10193   struct objfile *objfile = dwarf2_per_objfile->objfile;
10194   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
10195   const gdb_byte *info_ptr, *end_ptr;
10196
10197   dwarf2_read_section (objfile, &section);
10198   info_ptr = section.buffer;
10199
10200   if (info_ptr == NULL)
10201     return;
10202
10203   if (dwarf_read_debug)
10204     {
10205       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10206                           get_section_name (&section),
10207                           get_section_file_name (&section));
10208     }
10209
10210   end_ptr = info_ptr + section.size;
10211   while (info_ptr < end_ptr)
10212     {
10213       struct dwarf2_per_cu_data per_cu;
10214       struct create_dwo_cu_data create_dwo_cu_data;
10215       struct dwo_unit *dwo_unit;
10216       void **slot;
10217       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10218
10219       memset (&create_dwo_cu_data.dwo_unit, 0,
10220               sizeof (create_dwo_cu_data.dwo_unit));
10221       memset (&per_cu, 0, sizeof (per_cu));
10222       per_cu.objfile = objfile;
10223       per_cu.is_debug_types = 0;
10224       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10225       per_cu.section = &section;
10226       create_dwo_cu_data.dwo_file = &dwo_file;
10227
10228       init_cutu_and_read_dies_no_follow (
10229           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10230       info_ptr += per_cu.length;
10231
10232       // If the unit could not be parsed, skip it.
10233       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10234         continue;
10235
10236       if (cus_htab == NULL)
10237         cus_htab = allocate_dwo_unit_table (objfile);
10238
10239       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10240       *dwo_unit = create_dwo_cu_data.dwo_unit;
10241       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10242       gdb_assert (slot != NULL);
10243       if (*slot != NULL)
10244         {
10245           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10246           sect_offset dup_sect_off = dup_cu->sect_off;
10247
10248           complaint (&symfile_complaints,
10249                      _("debug cu entry at offset 0x%x is duplicate to"
10250                        " the entry at offset 0x%x, signature %s"),
10251                      to_underlying (sect_off), to_underlying (dup_sect_off),
10252                      hex_string (dwo_unit->signature));
10253         }
10254       *slot = (void *)dwo_unit;
10255     }
10256 }
10257
10258 /* DWP file .debug_{cu,tu}_index section format:
10259    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10260
10261    DWP Version 1:
10262
10263    Both index sections have the same format, and serve to map a 64-bit
10264    signature to a set of section numbers.  Each section begins with a header,
10265    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10266    indexes, and a pool of 32-bit section numbers.  The index sections will be
10267    aligned at 8-byte boundaries in the file.
10268
10269    The index section header consists of:
10270
10271     V, 32 bit version number
10272     -, 32 bits unused
10273     N, 32 bit number of compilation units or type units in the index
10274     M, 32 bit number of slots in the hash table
10275
10276    Numbers are recorded using the byte order of the application binary.
10277
10278    The hash table begins at offset 16 in the section, and consists of an array
10279    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10280    order of the application binary).  Unused slots in the hash table are 0.
10281    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10282
10283    The parallel table begins immediately after the hash table
10284    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10285    array of 32-bit indexes (using the byte order of the application binary),
10286    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10287    table contains a 32-bit index into the pool of section numbers.  For unused
10288    hash table slots, the corresponding entry in the parallel table will be 0.
10289
10290    The pool of section numbers begins immediately following the hash table
10291    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10292    section numbers consists of an array of 32-bit words (using the byte order
10293    of the application binary).  Each item in the array is indexed starting
10294    from 0.  The hash table entry provides the index of the first section
10295    number in the set.  Additional section numbers in the set follow, and the
10296    set is terminated by a 0 entry (section number 0 is not used in ELF).
10297
10298    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10299    section must be the first entry in the set, and the .debug_abbrev.dwo must
10300    be the second entry. Other members of the set may follow in any order.
10301
10302    ---
10303
10304    DWP Version 2:
10305
10306    DWP Version 2 combines all the .debug_info, etc. sections into one,
10307    and the entries in the index tables are now offsets into these sections.
10308    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10309    section.
10310
10311    Index Section Contents:
10312     Header
10313     Hash Table of Signatures   dwp_hash_table.hash_table
10314     Parallel Table of Indices  dwp_hash_table.unit_table
10315     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10316     Table of Section Sizes     dwp_hash_table.v2.sizes
10317
10318    The index section header consists of:
10319
10320     V, 32 bit version number
10321     L, 32 bit number of columns in the table of section offsets
10322     N, 32 bit number of compilation units or type units in the index
10323     M, 32 bit number of slots in the hash table
10324
10325    Numbers are recorded using the byte order of the application binary.
10326
10327    The hash table has the same format as version 1.
10328    The parallel table of indices has the same format as version 1,
10329    except that the entries are origin-1 indices into the table of sections
10330    offsets and the table of section sizes.
10331
10332    The table of offsets begins immediately following the parallel table
10333    (at offset 16 + 12 * M from the beginning of the section).  The table is
10334    a two-dimensional array of 32-bit words (using the byte order of the
10335    application binary), with L columns and N+1 rows, in row-major order.
10336    Each row in the array is indexed starting from 0.  The first row provides
10337    a key to the remaining rows: each column in this row provides an identifier
10338    for a debug section, and the offsets in the same column of subsequent rows
10339    refer to that section.  The section identifiers are:
10340
10341     DW_SECT_INFO         1  .debug_info.dwo
10342     DW_SECT_TYPES        2  .debug_types.dwo
10343     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10344     DW_SECT_LINE         4  .debug_line.dwo
10345     DW_SECT_LOC          5  .debug_loc.dwo
10346     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10347     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10348     DW_SECT_MACRO        8  .debug_macro.dwo
10349
10350    The offsets provided by the CU and TU index sections are the base offsets
10351    for the contributions made by each CU or TU to the corresponding section
10352    in the package file.  Each CU and TU header contains an abbrev_offset
10353    field, used to find the abbreviations table for that CU or TU within the
10354    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10355    be interpreted as relative to the base offset given in the index section.
10356    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10357    should be interpreted as relative to the base offset for .debug_line.dwo,
10358    and offsets into other debug sections obtained from DWARF attributes should
10359    also be interpreted as relative to the corresponding base offset.
10360
10361    The table of sizes begins immediately following the table of offsets.
10362    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10363    with L columns and N rows, in row-major order.  Each row in the array is
10364    indexed starting from 1 (row 0 is shared by the two tables).
10365
10366    ---
10367
10368    Hash table lookup is handled the same in version 1 and 2:
10369
10370    We assume that N and M will not exceed 2^32 - 1.
10371    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10372
10373    Given a 64-bit compilation unit signature or a type signature S, an entry
10374    in the hash table is located as follows:
10375
10376    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10377       the low-order k bits all set to 1.
10378
10379    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10380
10381    3) If the hash table entry at index H matches the signature, use that
10382       entry.  If the hash table entry at index H is unused (all zeroes),
10383       terminate the search: the signature is not present in the table.
10384
10385    4) Let H = (H + H') modulo M. Repeat at Step 3.
10386
10387    Because M > N and H' and M are relatively prime, the search is guaranteed
10388    to stop at an unused slot or find the match.  */
10389
10390 /* Create a hash table to map DWO IDs to their CU/TU entry in
10391    .debug_{info,types}.dwo in DWP_FILE.
10392    Returns NULL if there isn't one.
10393    Note: This function processes DWP files only, not DWO files.  */
10394
10395 static struct dwp_hash_table *
10396 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10397 {
10398   struct objfile *objfile = dwarf2_per_objfile->objfile;
10399   bfd *dbfd = dwp_file->dbfd;
10400   const gdb_byte *index_ptr, *index_end;
10401   struct dwarf2_section_info *index;
10402   uint32_t version, nr_columns, nr_units, nr_slots;
10403   struct dwp_hash_table *htab;
10404
10405   if (is_debug_types)
10406     index = &dwp_file->sections.tu_index;
10407   else
10408     index = &dwp_file->sections.cu_index;
10409
10410   if (dwarf2_section_empty_p (index))
10411     return NULL;
10412   dwarf2_read_section (objfile, index);
10413
10414   index_ptr = index->buffer;
10415   index_end = index_ptr + index->size;
10416
10417   version = read_4_bytes (dbfd, index_ptr);
10418   index_ptr += 4;
10419   if (version == 2)
10420     nr_columns = read_4_bytes (dbfd, index_ptr);
10421   else
10422     nr_columns = 0;
10423   index_ptr += 4;
10424   nr_units = read_4_bytes (dbfd, index_ptr);
10425   index_ptr += 4;
10426   nr_slots = read_4_bytes (dbfd, index_ptr);
10427   index_ptr += 4;
10428
10429   if (version != 1 && version != 2)
10430     {
10431       error (_("Dwarf Error: unsupported DWP file version (%s)"
10432                " [in module %s]"),
10433              pulongest (version), dwp_file->name);
10434     }
10435   if (nr_slots != (nr_slots & -nr_slots))
10436     {
10437       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10438                " is not power of 2 [in module %s]"),
10439              pulongest (nr_slots), dwp_file->name);
10440     }
10441
10442   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10443   htab->version = version;
10444   htab->nr_columns = nr_columns;
10445   htab->nr_units = nr_units;
10446   htab->nr_slots = nr_slots;
10447   htab->hash_table = index_ptr;
10448   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10449
10450   /* Exit early if the table is empty.  */
10451   if (nr_slots == 0 || nr_units == 0
10452       || (version == 2 && nr_columns == 0))
10453     {
10454       /* All must be zero.  */
10455       if (nr_slots != 0 || nr_units != 0
10456           || (version == 2 && nr_columns != 0))
10457         {
10458           complaint (&symfile_complaints,
10459                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10460                        " all zero [in modules %s]"),
10461                      dwp_file->name);
10462         }
10463       return htab;
10464     }
10465
10466   if (version == 1)
10467     {
10468       htab->section_pool.v1.indices =
10469         htab->unit_table + sizeof (uint32_t) * nr_slots;
10470       /* It's harder to decide whether the section is too small in v1.
10471          V1 is deprecated anyway so we punt.  */
10472     }
10473   else
10474     {
10475       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10476       int *ids = htab->section_pool.v2.section_ids;
10477       /* Reverse map for error checking.  */
10478       int ids_seen[DW_SECT_MAX + 1];
10479       int i;
10480
10481       if (nr_columns < 2)
10482         {
10483           error (_("Dwarf Error: bad DWP hash table, too few columns"
10484                    " in section table [in module %s]"),
10485                  dwp_file->name);
10486         }
10487       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10488         {
10489           error (_("Dwarf Error: bad DWP hash table, too many columns"
10490                    " in section table [in module %s]"),
10491                  dwp_file->name);
10492         }
10493       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10494       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10495       for (i = 0; i < nr_columns; ++i)
10496         {
10497           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10498
10499           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10500             {
10501               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10502                        " in section table [in module %s]"),
10503                      id, dwp_file->name);
10504             }
10505           if (ids_seen[id] != -1)
10506             {
10507               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10508                        " id %d in section table [in module %s]"),
10509                      id, dwp_file->name);
10510             }
10511           ids_seen[id] = i;
10512           ids[i] = id;
10513         }
10514       /* Must have exactly one info or types section.  */
10515       if (((ids_seen[DW_SECT_INFO] != -1)
10516            + (ids_seen[DW_SECT_TYPES] != -1))
10517           != 1)
10518         {
10519           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10520                    " DWO info/types section [in module %s]"),
10521                  dwp_file->name);
10522         }
10523       /* Must have an abbrev section.  */
10524       if (ids_seen[DW_SECT_ABBREV] == -1)
10525         {
10526           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10527                    " section [in module %s]"),
10528                  dwp_file->name);
10529         }
10530       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10531       htab->section_pool.v2.sizes =
10532         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10533                                          * nr_units * nr_columns);
10534       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10535                                           * nr_units * nr_columns))
10536           > index_end)
10537         {
10538           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10539                    " [in module %s]"),
10540                  dwp_file->name);
10541         }
10542     }
10543
10544   return htab;
10545 }
10546
10547 /* Update SECTIONS with the data from SECTP.
10548
10549    This function is like the other "locate" section routines that are
10550    passed to bfd_map_over_sections, but in this context the sections to
10551    read comes from the DWP V1 hash table, not the full ELF section table.
10552
10553    The result is non-zero for success, or zero if an error was found.  */
10554
10555 static int
10556 locate_v1_virtual_dwo_sections (asection *sectp,
10557                                 struct virtual_v1_dwo_sections *sections)
10558 {
10559   const struct dwop_section_names *names = &dwop_section_names;
10560
10561   if (section_is_p (sectp->name, &names->abbrev_dwo))
10562     {
10563       /* There can be only one.  */
10564       if (sections->abbrev.s.section != NULL)
10565         return 0;
10566       sections->abbrev.s.section = sectp;
10567       sections->abbrev.size = bfd_get_section_size (sectp);
10568     }
10569   else if (section_is_p (sectp->name, &names->info_dwo)
10570            || section_is_p (sectp->name, &names->types_dwo))
10571     {
10572       /* There can be only one.  */
10573       if (sections->info_or_types.s.section != NULL)
10574         return 0;
10575       sections->info_or_types.s.section = sectp;
10576       sections->info_or_types.size = bfd_get_section_size (sectp);
10577     }
10578   else if (section_is_p (sectp->name, &names->line_dwo))
10579     {
10580       /* There can be only one.  */
10581       if (sections->line.s.section != NULL)
10582         return 0;
10583       sections->line.s.section = sectp;
10584       sections->line.size = bfd_get_section_size (sectp);
10585     }
10586   else if (section_is_p (sectp->name, &names->loc_dwo))
10587     {
10588       /* There can be only one.  */
10589       if (sections->loc.s.section != NULL)
10590         return 0;
10591       sections->loc.s.section = sectp;
10592       sections->loc.size = bfd_get_section_size (sectp);
10593     }
10594   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10595     {
10596       /* There can be only one.  */
10597       if (sections->macinfo.s.section != NULL)
10598         return 0;
10599       sections->macinfo.s.section = sectp;
10600       sections->macinfo.size = bfd_get_section_size (sectp);
10601     }
10602   else if (section_is_p (sectp->name, &names->macro_dwo))
10603     {
10604       /* There can be only one.  */
10605       if (sections->macro.s.section != NULL)
10606         return 0;
10607       sections->macro.s.section = sectp;
10608       sections->macro.size = bfd_get_section_size (sectp);
10609     }
10610   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10611     {
10612       /* There can be only one.  */
10613       if (sections->str_offsets.s.section != NULL)
10614         return 0;
10615       sections->str_offsets.s.section = sectp;
10616       sections->str_offsets.size = bfd_get_section_size (sectp);
10617     }
10618   else
10619     {
10620       /* No other kind of section is valid.  */
10621       return 0;
10622     }
10623
10624   return 1;
10625 }
10626
10627 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10628    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10629    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10630    This is for DWP version 1 files.  */
10631
10632 static struct dwo_unit *
10633 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10634                            uint32_t unit_index,
10635                            const char *comp_dir,
10636                            ULONGEST signature, int is_debug_types)
10637 {
10638   struct objfile *objfile = dwarf2_per_objfile->objfile;
10639   const struct dwp_hash_table *dwp_htab =
10640     is_debug_types ? dwp_file->tus : dwp_file->cus;
10641   bfd *dbfd = dwp_file->dbfd;
10642   const char *kind = is_debug_types ? "TU" : "CU";
10643   struct dwo_file *dwo_file;
10644   struct dwo_unit *dwo_unit;
10645   struct virtual_v1_dwo_sections sections;
10646   void **dwo_file_slot;
10647   int i;
10648
10649   gdb_assert (dwp_file->version == 1);
10650
10651   if (dwarf_read_debug)
10652     {
10653       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10654                           kind,
10655                           pulongest (unit_index), hex_string (signature),
10656                           dwp_file->name);
10657     }
10658
10659   /* Fetch the sections of this DWO unit.
10660      Put a limit on the number of sections we look for so that bad data
10661      doesn't cause us to loop forever.  */
10662
10663 #define MAX_NR_V1_DWO_SECTIONS \
10664   (1 /* .debug_info or .debug_types */ \
10665    + 1 /* .debug_abbrev */ \
10666    + 1 /* .debug_line */ \
10667    + 1 /* .debug_loc */ \
10668    + 1 /* .debug_str_offsets */ \
10669    + 1 /* .debug_macro or .debug_macinfo */ \
10670    + 1 /* trailing zero */)
10671
10672   memset (&sections, 0, sizeof (sections));
10673
10674   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10675     {
10676       asection *sectp;
10677       uint32_t section_nr =
10678         read_4_bytes (dbfd,
10679                       dwp_htab->section_pool.v1.indices
10680                       + (unit_index + i) * sizeof (uint32_t));
10681
10682       if (section_nr == 0)
10683         break;
10684       if (section_nr >= dwp_file->num_sections)
10685         {
10686           error (_("Dwarf Error: bad DWP hash table, section number too large"
10687                    " [in module %s]"),
10688                  dwp_file->name);
10689         }
10690
10691       sectp = dwp_file->elf_sections[section_nr];
10692       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10693         {
10694           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10695                    " [in module %s]"),
10696                  dwp_file->name);
10697         }
10698     }
10699
10700   if (i < 2
10701       || dwarf2_section_empty_p (&sections.info_or_types)
10702       || dwarf2_section_empty_p (&sections.abbrev))
10703     {
10704       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10705                " [in module %s]"),
10706              dwp_file->name);
10707     }
10708   if (i == MAX_NR_V1_DWO_SECTIONS)
10709     {
10710       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10711                " [in module %s]"),
10712              dwp_file->name);
10713     }
10714
10715   /* It's easier for the rest of the code if we fake a struct dwo_file and
10716      have dwo_unit "live" in that.  At least for now.
10717
10718      The DWP file can be made up of a random collection of CUs and TUs.
10719      However, for each CU + set of TUs that came from the same original DWO
10720      file, we can combine them back into a virtual DWO file to save space
10721      (fewer struct dwo_file objects to allocate).  Remember that for really
10722      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10723
10724   std::string virtual_dwo_name =
10725     string_printf ("virtual-dwo/%d-%d-%d-%d",
10726                    get_section_id (&sections.abbrev),
10727                    get_section_id (&sections.line),
10728                    get_section_id (&sections.loc),
10729                    get_section_id (&sections.str_offsets));
10730   /* Can we use an existing virtual DWO file?  */
10731   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10732   /* Create one if necessary.  */
10733   if (*dwo_file_slot == NULL)
10734     {
10735       if (dwarf_read_debug)
10736         {
10737           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10738                               virtual_dwo_name.c_str ());
10739         }
10740       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10741       dwo_file->dwo_name
10742         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10743                                         virtual_dwo_name.c_str (),
10744                                         virtual_dwo_name.size ());
10745       dwo_file->comp_dir = comp_dir;
10746       dwo_file->sections.abbrev = sections.abbrev;
10747       dwo_file->sections.line = sections.line;
10748       dwo_file->sections.loc = sections.loc;
10749       dwo_file->sections.macinfo = sections.macinfo;
10750       dwo_file->sections.macro = sections.macro;
10751       dwo_file->sections.str_offsets = sections.str_offsets;
10752       /* The "str" section is global to the entire DWP file.  */
10753       dwo_file->sections.str = dwp_file->sections.str;
10754       /* The info or types section is assigned below to dwo_unit,
10755          there's no need to record it in dwo_file.
10756          Also, we can't simply record type sections in dwo_file because
10757          we record a pointer into the vector in dwo_unit.  As we collect more
10758          types we'll grow the vector and eventually have to reallocate space
10759          for it, invalidating all copies of pointers into the previous
10760          contents.  */
10761       *dwo_file_slot = dwo_file;
10762     }
10763   else
10764     {
10765       if (dwarf_read_debug)
10766         {
10767           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10768                               virtual_dwo_name.c_str ());
10769         }
10770       dwo_file = (struct dwo_file *) *dwo_file_slot;
10771     }
10772
10773   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10774   dwo_unit->dwo_file = dwo_file;
10775   dwo_unit->signature = signature;
10776   dwo_unit->section =
10777     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10778   *dwo_unit->section = sections.info_or_types;
10779   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10780
10781   return dwo_unit;
10782 }
10783
10784 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10785    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10786    piece within that section used by a TU/CU, return a virtual section
10787    of just that piece.  */
10788
10789 static struct dwarf2_section_info
10790 create_dwp_v2_section (struct dwarf2_section_info *section,
10791                        bfd_size_type offset, bfd_size_type size)
10792 {
10793   struct dwarf2_section_info result;
10794   asection *sectp;
10795
10796   gdb_assert (section != NULL);
10797   gdb_assert (!section->is_virtual);
10798
10799   memset (&result, 0, sizeof (result));
10800   result.s.containing_section = section;
10801   result.is_virtual = 1;
10802
10803   if (size == 0)
10804     return result;
10805
10806   sectp = get_section_bfd_section (section);
10807
10808   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10809      bounds of the real section.  This is a pretty-rare event, so just
10810      flag an error (easier) instead of a warning and trying to cope.  */
10811   if (sectp == NULL
10812       || offset + size > bfd_get_section_size (sectp))
10813     {
10814       bfd *abfd = sectp->owner;
10815
10816       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10817                " in section %s [in module %s]"),
10818              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10819              objfile_name (dwarf2_per_objfile->objfile));
10820     }
10821
10822   result.virtual_offset = offset;
10823   result.size = size;
10824   return result;
10825 }
10826
10827 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10828    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10829    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10830    This is for DWP version 2 files.  */
10831
10832 static struct dwo_unit *
10833 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10834                            uint32_t unit_index,
10835                            const char *comp_dir,
10836                            ULONGEST signature, int is_debug_types)
10837 {
10838   struct objfile *objfile = dwarf2_per_objfile->objfile;
10839   const struct dwp_hash_table *dwp_htab =
10840     is_debug_types ? dwp_file->tus : dwp_file->cus;
10841   bfd *dbfd = dwp_file->dbfd;
10842   const char *kind = is_debug_types ? "TU" : "CU";
10843   struct dwo_file *dwo_file;
10844   struct dwo_unit *dwo_unit;
10845   struct virtual_v2_dwo_sections sections;
10846   void **dwo_file_slot;
10847   int i;
10848
10849   gdb_assert (dwp_file->version == 2);
10850
10851   if (dwarf_read_debug)
10852     {
10853       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10854                           kind,
10855                           pulongest (unit_index), hex_string (signature),
10856                           dwp_file->name);
10857     }
10858
10859   /* Fetch the section offsets of this DWO unit.  */
10860
10861   memset (&sections, 0, sizeof (sections));
10862
10863   for (i = 0; i < dwp_htab->nr_columns; ++i)
10864     {
10865       uint32_t offset = read_4_bytes (dbfd,
10866                                       dwp_htab->section_pool.v2.offsets
10867                                       + (((unit_index - 1) * dwp_htab->nr_columns
10868                                           + i)
10869                                          * sizeof (uint32_t)));
10870       uint32_t size = read_4_bytes (dbfd,
10871                                     dwp_htab->section_pool.v2.sizes
10872                                     + (((unit_index - 1) * dwp_htab->nr_columns
10873                                         + i)
10874                                        * sizeof (uint32_t)));
10875
10876       switch (dwp_htab->section_pool.v2.section_ids[i])
10877         {
10878         case DW_SECT_INFO:
10879         case DW_SECT_TYPES:
10880           sections.info_or_types_offset = offset;
10881           sections.info_or_types_size = size;
10882           break;
10883         case DW_SECT_ABBREV:
10884           sections.abbrev_offset = offset;
10885           sections.abbrev_size = size;
10886           break;
10887         case DW_SECT_LINE:
10888           sections.line_offset = offset;
10889           sections.line_size = size;
10890           break;
10891         case DW_SECT_LOC:
10892           sections.loc_offset = offset;
10893           sections.loc_size = size;
10894           break;
10895         case DW_SECT_STR_OFFSETS:
10896           sections.str_offsets_offset = offset;
10897           sections.str_offsets_size = size;
10898           break;
10899         case DW_SECT_MACINFO:
10900           sections.macinfo_offset = offset;
10901           sections.macinfo_size = size;
10902           break;
10903         case DW_SECT_MACRO:
10904           sections.macro_offset = offset;
10905           sections.macro_size = size;
10906           break;
10907         }
10908     }
10909
10910   /* It's easier for the rest of the code if we fake a struct dwo_file and
10911      have dwo_unit "live" in that.  At least for now.
10912
10913      The DWP file can be made up of a random collection of CUs and TUs.
10914      However, for each CU + set of TUs that came from the same original DWO
10915      file, we can combine them back into a virtual DWO file to save space
10916      (fewer struct dwo_file objects to allocate).  Remember that for really
10917      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10918
10919   std::string virtual_dwo_name =
10920     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
10921                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10922                    (long) (sections.line_size ? sections.line_offset : 0),
10923                    (long) (sections.loc_size ? sections.loc_offset : 0),
10924                    (long) (sections.str_offsets_size
10925                            ? sections.str_offsets_offset : 0));
10926   /* Can we use an existing virtual DWO file?  */
10927   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10928   /* Create one if necessary.  */
10929   if (*dwo_file_slot == NULL)
10930     {
10931       if (dwarf_read_debug)
10932         {
10933           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10934                               virtual_dwo_name.c_str ());
10935         }
10936       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10937       dwo_file->dwo_name
10938         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10939                                         virtual_dwo_name.c_str (),
10940                                         virtual_dwo_name.size ());
10941       dwo_file->comp_dir = comp_dir;
10942       dwo_file->sections.abbrev =
10943         create_dwp_v2_section (&dwp_file->sections.abbrev,
10944                                sections.abbrev_offset, sections.abbrev_size);
10945       dwo_file->sections.line =
10946         create_dwp_v2_section (&dwp_file->sections.line,
10947                                sections.line_offset, sections.line_size);
10948       dwo_file->sections.loc =
10949         create_dwp_v2_section (&dwp_file->sections.loc,
10950                                sections.loc_offset, sections.loc_size);
10951       dwo_file->sections.macinfo =
10952         create_dwp_v2_section (&dwp_file->sections.macinfo,
10953                                sections.macinfo_offset, sections.macinfo_size);
10954       dwo_file->sections.macro =
10955         create_dwp_v2_section (&dwp_file->sections.macro,
10956                                sections.macro_offset, sections.macro_size);
10957       dwo_file->sections.str_offsets =
10958         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10959                                sections.str_offsets_offset,
10960                                sections.str_offsets_size);
10961       /* The "str" section is global to the entire DWP file.  */
10962       dwo_file->sections.str = dwp_file->sections.str;
10963       /* The info or types section is assigned below to dwo_unit,
10964          there's no need to record it in dwo_file.
10965          Also, we can't simply record type sections in dwo_file because
10966          we record a pointer into the vector in dwo_unit.  As we collect more
10967          types we'll grow the vector and eventually have to reallocate space
10968          for it, invalidating all copies of pointers into the previous
10969          contents.  */
10970       *dwo_file_slot = dwo_file;
10971     }
10972   else
10973     {
10974       if (dwarf_read_debug)
10975         {
10976           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10977                               virtual_dwo_name.c_str ());
10978         }
10979       dwo_file = (struct dwo_file *) *dwo_file_slot;
10980     }
10981
10982   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10983   dwo_unit->dwo_file = dwo_file;
10984   dwo_unit->signature = signature;
10985   dwo_unit->section =
10986     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10987   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10988                                               ? &dwp_file->sections.types
10989                                               : &dwp_file->sections.info,
10990                                               sections.info_or_types_offset,
10991                                               sections.info_or_types_size);
10992   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10993
10994   return dwo_unit;
10995 }
10996
10997 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10998    Returns NULL if the signature isn't found.  */
10999
11000 static struct dwo_unit *
11001 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
11002                         ULONGEST signature, int is_debug_types)
11003 {
11004   const struct dwp_hash_table *dwp_htab =
11005     is_debug_types ? dwp_file->tus : dwp_file->cus;
11006   bfd *dbfd = dwp_file->dbfd;
11007   uint32_t mask = dwp_htab->nr_slots - 1;
11008   uint32_t hash = signature & mask;
11009   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11010   unsigned int i;
11011   void **slot;
11012   struct dwo_unit find_dwo_cu;
11013
11014   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11015   find_dwo_cu.signature = signature;
11016   slot = htab_find_slot (is_debug_types
11017                          ? dwp_file->loaded_tus
11018                          : dwp_file->loaded_cus,
11019                          &find_dwo_cu, INSERT);
11020
11021   if (*slot != NULL)
11022     return (struct dwo_unit *) *slot;
11023
11024   /* Use a for loop so that we don't loop forever on bad debug info.  */
11025   for (i = 0; i < dwp_htab->nr_slots; ++i)
11026     {
11027       ULONGEST signature_in_table;
11028
11029       signature_in_table =
11030         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11031       if (signature_in_table == signature)
11032         {
11033           uint32_t unit_index =
11034             read_4_bytes (dbfd,
11035                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11036
11037           if (dwp_file->version == 1)
11038             {
11039               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11040                                                  comp_dir, signature,
11041                                                  is_debug_types);
11042             }
11043           else
11044             {
11045               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11046                                                  comp_dir, signature,
11047                                                  is_debug_types);
11048             }
11049           return (struct dwo_unit *) *slot;
11050         }
11051       if (signature_in_table == 0)
11052         return NULL;
11053       hash = (hash + hash2) & mask;
11054     }
11055
11056   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11057            " [in module %s]"),
11058          dwp_file->name);
11059 }
11060
11061 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11062    Open the file specified by FILE_NAME and hand it off to BFD for
11063    preliminary analysis.  Return a newly initialized bfd *, which
11064    includes a canonicalized copy of FILE_NAME.
11065    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11066    SEARCH_CWD is true if the current directory is to be searched.
11067    It will be searched before debug-file-directory.
11068    If successful, the file is added to the bfd include table of the
11069    objfile's bfd (see gdb_bfd_record_inclusion).
11070    If unable to find/open the file, return NULL.
11071    NOTE: This function is derived from symfile_bfd_open.  */
11072
11073 static gdb_bfd_ref_ptr
11074 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11075 {
11076   int desc, flags;
11077   char *absolute_name;
11078   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11079      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11080      to debug_file_directory.  */
11081   char *search_path;
11082   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11083
11084   if (search_cwd)
11085     {
11086       if (*debug_file_directory != '\0')
11087         search_path = concat (".", dirname_separator_string,
11088                               debug_file_directory, (char *) NULL);
11089       else
11090         search_path = xstrdup (".");
11091     }
11092   else
11093     search_path = xstrdup (debug_file_directory);
11094
11095   flags = OPF_RETURN_REALPATH;
11096   if (is_dwp)
11097     flags |= OPF_SEARCH_IN_PATH;
11098   desc = openp (search_path, flags, file_name,
11099                 O_RDONLY | O_BINARY, &absolute_name);
11100   xfree (search_path);
11101   if (desc < 0)
11102     return NULL;
11103
11104   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11105   xfree (absolute_name);
11106   if (sym_bfd == NULL)
11107     return NULL;
11108   bfd_set_cacheable (sym_bfd.get (), 1);
11109
11110   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11111     return NULL;
11112
11113   /* Success.  Record the bfd as having been included by the objfile's bfd.
11114      This is important because things like demangled_names_hash lives in the
11115      objfile's per_bfd space and may have references to things like symbol
11116      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11117   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11118
11119   return sym_bfd;
11120 }
11121
11122 /* Try to open DWO file FILE_NAME.
11123    COMP_DIR is the DW_AT_comp_dir attribute.
11124    The result is the bfd handle of the file.
11125    If there is a problem finding or opening the file, return NULL.
11126    Upon success, the canonicalized path of the file is stored in the bfd,
11127    same as symfile_bfd_open.  */
11128
11129 static gdb_bfd_ref_ptr
11130 open_dwo_file (const char *file_name, const char *comp_dir)
11131 {
11132   if (IS_ABSOLUTE_PATH (file_name))
11133     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11134
11135   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11136
11137   if (comp_dir != NULL)
11138     {
11139       char *path_to_try = concat (comp_dir, SLASH_STRING,
11140                                   file_name, (char *) NULL);
11141
11142       /* NOTE: If comp_dir is a relative path, this will also try the
11143          search path, which seems useful.  */
11144       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11145                                                 1 /*search_cwd*/));
11146       xfree (path_to_try);
11147       if (abfd != NULL)
11148         return abfd;
11149     }
11150
11151   /* That didn't work, try debug-file-directory, which, despite its name,
11152      is a list of paths.  */
11153
11154   if (*debug_file_directory == '\0')
11155     return NULL;
11156
11157   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11158 }
11159
11160 /* This function is mapped across the sections and remembers the offset and
11161    size of each of the DWO debugging sections we are interested in.  */
11162
11163 static void
11164 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11165 {
11166   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11167   const struct dwop_section_names *names = &dwop_section_names;
11168
11169   if (section_is_p (sectp->name, &names->abbrev_dwo))
11170     {
11171       dwo_sections->abbrev.s.section = sectp;
11172       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11173     }
11174   else if (section_is_p (sectp->name, &names->info_dwo))
11175     {
11176       dwo_sections->info.s.section = sectp;
11177       dwo_sections->info.size = bfd_get_section_size (sectp);
11178     }
11179   else if (section_is_p (sectp->name, &names->line_dwo))
11180     {
11181       dwo_sections->line.s.section = sectp;
11182       dwo_sections->line.size = bfd_get_section_size (sectp);
11183     }
11184   else if (section_is_p (sectp->name, &names->loc_dwo))
11185     {
11186       dwo_sections->loc.s.section = sectp;
11187       dwo_sections->loc.size = bfd_get_section_size (sectp);
11188     }
11189   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11190     {
11191       dwo_sections->macinfo.s.section = sectp;
11192       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11193     }
11194   else if (section_is_p (sectp->name, &names->macro_dwo))
11195     {
11196       dwo_sections->macro.s.section = sectp;
11197       dwo_sections->macro.size = bfd_get_section_size (sectp);
11198     }
11199   else if (section_is_p (sectp->name, &names->str_dwo))
11200     {
11201       dwo_sections->str.s.section = sectp;
11202       dwo_sections->str.size = bfd_get_section_size (sectp);
11203     }
11204   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11205     {
11206       dwo_sections->str_offsets.s.section = sectp;
11207       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11208     }
11209   else if (section_is_p (sectp->name, &names->types_dwo))
11210     {
11211       struct dwarf2_section_info type_section;
11212
11213       memset (&type_section, 0, sizeof (type_section));
11214       type_section.s.section = sectp;
11215       type_section.size = bfd_get_section_size (sectp);
11216       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11217                      &type_section);
11218     }
11219 }
11220
11221 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11222    by PER_CU.  This is for the non-DWP case.
11223    The result is NULL if DWO_NAME can't be found.  */
11224
11225 static struct dwo_file *
11226 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11227                         const char *dwo_name, const char *comp_dir)
11228 {
11229   struct objfile *objfile = dwarf2_per_objfile->objfile;
11230   struct dwo_file *dwo_file;
11231   struct cleanup *cleanups;
11232
11233   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11234   if (dbfd == NULL)
11235     {
11236       if (dwarf_read_debug)
11237         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11238       return NULL;
11239     }
11240   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11241   dwo_file->dwo_name = dwo_name;
11242   dwo_file->comp_dir = comp_dir;
11243   dwo_file->dbfd = dbfd.release ();
11244
11245   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11246
11247   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11248                          &dwo_file->sections);
11249
11250   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11251
11252   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11253                                  dwo_file->tus);
11254
11255   discard_cleanups (cleanups);
11256
11257   if (dwarf_read_debug)
11258     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11259
11260   return dwo_file;
11261 }
11262
11263 /* This function is mapped across the sections and remembers the offset and
11264    size of each of the DWP debugging sections common to version 1 and 2 that
11265    we are interested in.  */
11266
11267 static void
11268 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11269                                    void *dwp_file_ptr)
11270 {
11271   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11272   const struct dwop_section_names *names = &dwop_section_names;
11273   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11274
11275   /* Record the ELF section number for later lookup: this is what the
11276      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11277   gdb_assert (elf_section_nr < dwp_file->num_sections);
11278   dwp_file->elf_sections[elf_section_nr] = sectp;
11279
11280   /* Look for specific sections that we need.  */
11281   if (section_is_p (sectp->name, &names->str_dwo))
11282     {
11283       dwp_file->sections.str.s.section = sectp;
11284       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11285     }
11286   else if (section_is_p (sectp->name, &names->cu_index))
11287     {
11288       dwp_file->sections.cu_index.s.section = sectp;
11289       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11290     }
11291   else if (section_is_p (sectp->name, &names->tu_index))
11292     {
11293       dwp_file->sections.tu_index.s.section = sectp;
11294       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11295     }
11296 }
11297
11298 /* This function is mapped across the sections and remembers the offset and
11299    size of each of the DWP version 2 debugging sections that we are interested
11300    in.  This is split into a separate function because we don't know if we
11301    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11302
11303 static void
11304 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11305 {
11306   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11307   const struct dwop_section_names *names = &dwop_section_names;
11308   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11309
11310   /* Record the ELF section number for later lookup: this is what the
11311      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11312   gdb_assert (elf_section_nr < dwp_file->num_sections);
11313   dwp_file->elf_sections[elf_section_nr] = sectp;
11314
11315   /* Look for specific sections that we need.  */
11316   if (section_is_p (sectp->name, &names->abbrev_dwo))
11317     {
11318       dwp_file->sections.abbrev.s.section = sectp;
11319       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11320     }
11321   else if (section_is_p (sectp->name, &names->info_dwo))
11322     {
11323       dwp_file->sections.info.s.section = sectp;
11324       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11325     }
11326   else if (section_is_p (sectp->name, &names->line_dwo))
11327     {
11328       dwp_file->sections.line.s.section = sectp;
11329       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11330     }
11331   else if (section_is_p (sectp->name, &names->loc_dwo))
11332     {
11333       dwp_file->sections.loc.s.section = sectp;
11334       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11335     }
11336   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11337     {
11338       dwp_file->sections.macinfo.s.section = sectp;
11339       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11340     }
11341   else if (section_is_p (sectp->name, &names->macro_dwo))
11342     {
11343       dwp_file->sections.macro.s.section = sectp;
11344       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11345     }
11346   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11347     {
11348       dwp_file->sections.str_offsets.s.section = sectp;
11349       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11350     }
11351   else if (section_is_p (sectp->name, &names->types_dwo))
11352     {
11353       dwp_file->sections.types.s.section = sectp;
11354       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11355     }
11356 }
11357
11358 /* Hash function for dwp_file loaded CUs/TUs.  */
11359
11360 static hashval_t
11361 hash_dwp_loaded_cutus (const void *item)
11362 {
11363   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11364
11365   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11366   return dwo_unit->signature;
11367 }
11368
11369 /* Equality function for dwp_file loaded CUs/TUs.  */
11370
11371 static int
11372 eq_dwp_loaded_cutus (const void *a, const void *b)
11373 {
11374   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11375   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11376
11377   return dua->signature == dub->signature;
11378 }
11379
11380 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11381
11382 static htab_t
11383 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11384 {
11385   return htab_create_alloc_ex (3,
11386                                hash_dwp_loaded_cutus,
11387                                eq_dwp_loaded_cutus,
11388                                NULL,
11389                                &objfile->objfile_obstack,
11390                                hashtab_obstack_allocate,
11391                                dummy_obstack_deallocate);
11392 }
11393
11394 /* Try to open DWP file FILE_NAME.
11395    The result is the bfd handle of the file.
11396    If there is a problem finding or opening the file, return NULL.
11397    Upon success, the canonicalized path of the file is stored in the bfd,
11398    same as symfile_bfd_open.  */
11399
11400 static gdb_bfd_ref_ptr
11401 open_dwp_file (const char *file_name)
11402 {
11403   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11404                                             1 /*search_cwd*/));
11405   if (abfd != NULL)
11406     return abfd;
11407
11408   /* Work around upstream bug 15652.
11409      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11410      [Whether that's a "bug" is debatable, but it is getting in our way.]
11411      We have no real idea where the dwp file is, because gdb's realpath-ing
11412      of the executable's path may have discarded the needed info.
11413      [IWBN if the dwp file name was recorded in the executable, akin to
11414      .gnu_debuglink, but that doesn't exist yet.]
11415      Strip the directory from FILE_NAME and search again.  */
11416   if (*debug_file_directory != '\0')
11417     {
11418       /* Don't implicitly search the current directory here.
11419          If the user wants to search "." to handle this case,
11420          it must be added to debug-file-directory.  */
11421       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11422                                  0 /*search_cwd*/);
11423     }
11424
11425   return NULL;
11426 }
11427
11428 /* Initialize the use of the DWP file for the current objfile.
11429    By convention the name of the DWP file is ${objfile}.dwp.
11430    The result is NULL if it can't be found.  */
11431
11432 static struct dwp_file *
11433 open_and_init_dwp_file (void)
11434 {
11435   struct objfile *objfile = dwarf2_per_objfile->objfile;
11436   struct dwp_file *dwp_file;
11437
11438   /* Try to find first .dwp for the binary file before any symbolic links
11439      resolving.  */
11440
11441   /* If the objfile is a debug file, find the name of the real binary
11442      file and get the name of dwp file from there.  */
11443   std::string dwp_name;
11444   if (objfile->separate_debug_objfile_backlink != NULL)
11445     {
11446       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11447       const char *backlink_basename = lbasename (backlink->original_name);
11448
11449       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11450     }
11451   else
11452     dwp_name = objfile->original_name;
11453
11454   dwp_name += ".dwp";
11455
11456   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11457   if (dbfd == NULL
11458       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11459     {
11460       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11461       dwp_name = objfile_name (objfile);
11462       dwp_name += ".dwp";
11463       dbfd = open_dwp_file (dwp_name.c_str ());
11464     }
11465
11466   if (dbfd == NULL)
11467     {
11468       if (dwarf_read_debug)
11469         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11470       return NULL;
11471     }
11472   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11473   dwp_file->name = bfd_get_filename (dbfd.get ());
11474   dwp_file->dbfd = dbfd.release ();
11475
11476   /* +1: section 0 is unused */
11477   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11478   dwp_file->elf_sections =
11479     OBSTACK_CALLOC (&objfile->objfile_obstack,
11480                     dwp_file->num_sections, asection *);
11481
11482   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11483                          dwp_file);
11484
11485   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11486
11487   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11488
11489   /* The DWP file version is stored in the hash table.  Oh well.  */
11490   if (dwp_file->cus && dwp_file->tus
11491       && dwp_file->cus->version != dwp_file->tus->version)
11492     {
11493       /* Technically speaking, we should try to limp along, but this is
11494          pretty bizarre.  We use pulongest here because that's the established
11495          portability solution (e.g, we cannot use %u for uint32_t).  */
11496       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11497                " TU version %s [in DWP file %s]"),
11498              pulongest (dwp_file->cus->version),
11499              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11500     }
11501
11502   if (dwp_file->cus)
11503     dwp_file->version = dwp_file->cus->version;
11504   else if (dwp_file->tus)
11505     dwp_file->version = dwp_file->tus->version;
11506   else
11507     dwp_file->version = 2;
11508
11509   if (dwp_file->version == 2)
11510     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11511                            dwp_file);
11512
11513   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11514   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11515
11516   if (dwarf_read_debug)
11517     {
11518       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11519       fprintf_unfiltered (gdb_stdlog,
11520                           "    %s CUs, %s TUs\n",
11521                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11522                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11523     }
11524
11525   return dwp_file;
11526 }
11527
11528 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11529
11530 static struct dwp_file *
11531 get_dwp_file (void)
11532 {
11533   if (! dwarf2_per_objfile->dwp_checked)
11534     {
11535       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11536       dwarf2_per_objfile->dwp_checked = 1;
11537     }
11538   return dwarf2_per_objfile->dwp_file;
11539 }
11540
11541 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11542    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11543    or in the DWP file for the objfile, referenced by THIS_UNIT.
11544    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11545    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11546
11547    This is called, for example, when wanting to read a variable with a
11548    complex location.  Therefore we don't want to do file i/o for every call.
11549    Therefore we don't want to look for a DWO file on every call.
11550    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11551    then we check if we've already seen DWO_NAME, and only THEN do we check
11552    for a DWO file.
11553
11554    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11555    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11556
11557 static struct dwo_unit *
11558 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11559                  const char *dwo_name, const char *comp_dir,
11560                  ULONGEST signature, int is_debug_types)
11561 {
11562   struct objfile *objfile = dwarf2_per_objfile->objfile;
11563   const char *kind = is_debug_types ? "TU" : "CU";
11564   void **dwo_file_slot;
11565   struct dwo_file *dwo_file;
11566   struct dwp_file *dwp_file;
11567
11568   /* First see if there's a DWP file.
11569      If we have a DWP file but didn't find the DWO inside it, don't
11570      look for the original DWO file.  It makes gdb behave differently
11571      depending on whether one is debugging in the build tree.  */
11572
11573   dwp_file = get_dwp_file ();
11574   if (dwp_file != NULL)
11575     {
11576       const struct dwp_hash_table *dwp_htab =
11577         is_debug_types ? dwp_file->tus : dwp_file->cus;
11578
11579       if (dwp_htab != NULL)
11580         {
11581           struct dwo_unit *dwo_cutu =
11582             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11583                                     signature, is_debug_types);
11584
11585           if (dwo_cutu != NULL)
11586             {
11587               if (dwarf_read_debug)
11588                 {
11589                   fprintf_unfiltered (gdb_stdlog,
11590                                       "Virtual DWO %s %s found: @%s\n",
11591                                       kind, hex_string (signature),
11592                                       host_address_to_string (dwo_cutu));
11593                 }
11594               return dwo_cutu;
11595             }
11596         }
11597     }
11598   else
11599     {
11600       /* No DWP file, look for the DWO file.  */
11601
11602       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11603       if (*dwo_file_slot == NULL)
11604         {
11605           /* Read in the file and build a table of the CUs/TUs it contains.  */
11606           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11607         }
11608       /* NOTE: This will be NULL if unable to open the file.  */
11609       dwo_file = (struct dwo_file *) *dwo_file_slot;
11610
11611       if (dwo_file != NULL)
11612         {
11613           struct dwo_unit *dwo_cutu = NULL;
11614
11615           if (is_debug_types && dwo_file->tus)
11616             {
11617               struct dwo_unit find_dwo_cutu;
11618
11619               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11620               find_dwo_cutu.signature = signature;
11621               dwo_cutu
11622                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11623             }
11624           else if (!is_debug_types && dwo_file->cus)
11625             {
11626               struct dwo_unit find_dwo_cutu;
11627
11628               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11629               find_dwo_cutu.signature = signature;
11630               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11631                                                        &find_dwo_cutu);
11632             }
11633
11634           if (dwo_cutu != NULL)
11635             {
11636               if (dwarf_read_debug)
11637                 {
11638                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11639                                       kind, dwo_name, hex_string (signature),
11640                                       host_address_to_string (dwo_cutu));
11641                 }
11642               return dwo_cutu;
11643             }
11644         }
11645     }
11646
11647   /* We didn't find it.  This could mean a dwo_id mismatch, or
11648      someone deleted the DWO/DWP file, or the search path isn't set up
11649      correctly to find the file.  */
11650
11651   if (dwarf_read_debug)
11652     {
11653       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11654                           kind, dwo_name, hex_string (signature));
11655     }
11656
11657   /* This is a warning and not a complaint because it can be caused by
11658      pilot error (e.g., user accidentally deleting the DWO).  */
11659   {
11660     /* Print the name of the DWP file if we looked there, helps the user
11661        better diagnose the problem.  */
11662     std::string dwp_text;
11663
11664     if (dwp_file != NULL)
11665       dwp_text = string_printf (" [in DWP file %s]",
11666                                 lbasename (dwp_file->name));
11667
11668     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11669                " [in module %s]"),
11670              kind, dwo_name, hex_string (signature),
11671              dwp_text.c_str (),
11672              this_unit->is_debug_types ? "TU" : "CU",
11673              to_underlying (this_unit->sect_off), objfile_name (objfile));
11674   }
11675   return NULL;
11676 }
11677
11678 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11679    See lookup_dwo_cutu_unit for details.  */
11680
11681 static struct dwo_unit *
11682 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11683                       const char *dwo_name, const char *comp_dir,
11684                       ULONGEST signature)
11685 {
11686   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11687 }
11688
11689 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11690    See lookup_dwo_cutu_unit for details.  */
11691
11692 static struct dwo_unit *
11693 lookup_dwo_type_unit (struct signatured_type *this_tu,
11694                       const char *dwo_name, const char *comp_dir)
11695 {
11696   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11697 }
11698
11699 /* Traversal function for queue_and_load_all_dwo_tus.  */
11700
11701 static int
11702 queue_and_load_dwo_tu (void **slot, void *info)
11703 {
11704   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11705   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11706   ULONGEST signature = dwo_unit->signature;
11707   struct signatured_type *sig_type =
11708     lookup_dwo_signatured_type (per_cu->cu, signature);
11709
11710   if (sig_type != NULL)
11711     {
11712       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11713
11714       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11715          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11716          while processing PER_CU.  */
11717       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11718         load_full_type_unit (sig_cu);
11719       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11720     }
11721
11722   return 1;
11723 }
11724
11725 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11726    The DWO may have the only definition of the type, though it may not be
11727    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11728    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11729
11730 static void
11731 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11732 {
11733   struct dwo_unit *dwo_unit;
11734   struct dwo_file *dwo_file;
11735
11736   gdb_assert (!per_cu->is_debug_types);
11737   gdb_assert (get_dwp_file () == NULL);
11738   gdb_assert (per_cu->cu != NULL);
11739
11740   dwo_unit = per_cu->cu->dwo_unit;
11741   gdb_assert (dwo_unit != NULL);
11742
11743   dwo_file = dwo_unit->dwo_file;
11744   if (dwo_file->tus != NULL)
11745     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11746 }
11747
11748 /* Free all resources associated with DWO_FILE.
11749    Close the DWO file and munmap the sections.
11750    All memory should be on the objfile obstack.  */
11751
11752 static void
11753 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11754 {
11755
11756   /* Note: dbfd is NULL for virtual DWO files.  */
11757   gdb_bfd_unref (dwo_file->dbfd);
11758
11759   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11760 }
11761
11762 /* Wrapper for free_dwo_file for use in cleanups.  */
11763
11764 static void
11765 free_dwo_file_cleanup (void *arg)
11766 {
11767   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11768   struct objfile *objfile = dwarf2_per_objfile->objfile;
11769
11770   free_dwo_file (dwo_file, objfile);
11771 }
11772
11773 /* Traversal function for free_dwo_files.  */
11774
11775 static int
11776 free_dwo_file_from_slot (void **slot, void *info)
11777 {
11778   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11779   struct objfile *objfile = (struct objfile *) info;
11780
11781   free_dwo_file (dwo_file, objfile);
11782
11783   return 1;
11784 }
11785
11786 /* Free all resources associated with DWO_FILES.  */
11787
11788 static void
11789 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11790 {
11791   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11792 }
11793 \f
11794 /* Read in various DIEs.  */
11795
11796 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11797    Inherit only the children of the DW_AT_abstract_origin DIE not being
11798    already referenced by DW_AT_abstract_origin from the children of the
11799    current DIE.  */
11800
11801 static void
11802 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11803 {
11804   struct die_info *child_die;
11805   sect_offset *offsetp;
11806   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11807   struct die_info *origin_die;
11808   /* Iterator of the ORIGIN_DIE children.  */
11809   struct die_info *origin_child_die;
11810   struct attribute *attr;
11811   struct dwarf2_cu *origin_cu;
11812   struct pending **origin_previous_list_in_scope;
11813
11814   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11815   if (!attr)
11816     return;
11817
11818   /* Note that following die references may follow to a die in a
11819      different cu.  */
11820
11821   origin_cu = cu;
11822   origin_die = follow_die_ref (die, attr, &origin_cu);
11823
11824   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11825      symbols in.  */
11826   origin_previous_list_in_scope = origin_cu->list_in_scope;
11827   origin_cu->list_in_scope = cu->list_in_scope;
11828
11829   if (die->tag != origin_die->tag
11830       && !(die->tag == DW_TAG_inlined_subroutine
11831            && origin_die->tag == DW_TAG_subprogram))
11832     complaint (&symfile_complaints,
11833                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11834                to_underlying (die->sect_off),
11835                to_underlying (origin_die->sect_off));
11836
11837   std::vector<sect_offset> offsets;
11838
11839   for (child_die = die->child;
11840        child_die && child_die->tag;
11841        child_die = sibling_die (child_die))
11842     {
11843       struct die_info *child_origin_die;
11844       struct dwarf2_cu *child_origin_cu;
11845
11846       /* We are trying to process concrete instance entries:
11847          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11848          it's not relevant to our analysis here. i.e. detecting DIEs that are
11849          present in the abstract instance but not referenced in the concrete
11850          one.  */
11851       if (child_die->tag == DW_TAG_call_site
11852           || child_die->tag == DW_TAG_GNU_call_site)
11853         continue;
11854
11855       /* For each CHILD_DIE, find the corresponding child of
11856          ORIGIN_DIE.  If there is more than one layer of
11857          DW_AT_abstract_origin, follow them all; there shouldn't be,
11858          but GCC versions at least through 4.4 generate this (GCC PR
11859          40573).  */
11860       child_origin_die = child_die;
11861       child_origin_cu = cu;
11862       while (1)
11863         {
11864           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11865                               child_origin_cu);
11866           if (attr == NULL)
11867             break;
11868           child_origin_die = follow_die_ref (child_origin_die, attr,
11869                                              &child_origin_cu);
11870         }
11871
11872       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11873          counterpart may exist.  */
11874       if (child_origin_die != child_die)
11875         {
11876           if (child_die->tag != child_origin_die->tag
11877               && !(child_die->tag == DW_TAG_inlined_subroutine
11878                    && child_origin_die->tag == DW_TAG_subprogram))
11879             complaint (&symfile_complaints,
11880                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11881                          "different tags"),
11882                        to_underlying (child_die->sect_off),
11883                        to_underlying (child_origin_die->sect_off));
11884           if (child_origin_die->parent != origin_die)
11885             complaint (&symfile_complaints,
11886                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11887                          "different parents"),
11888                        to_underlying (child_die->sect_off),
11889                        to_underlying (child_origin_die->sect_off));
11890           else
11891             offsets.push_back (child_origin_die->sect_off);
11892         }
11893     }
11894   std::sort (offsets.begin (), offsets.end ());
11895   sect_offset *offsets_end = offsets.data () + offsets.size ();
11896   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
11897     if (offsetp[-1] == *offsetp)
11898       complaint (&symfile_complaints,
11899                  _("Multiple children of DIE 0x%x refer "
11900                    "to DIE 0x%x as their abstract origin"),
11901                  to_underlying (die->sect_off), to_underlying (*offsetp));
11902
11903   offsetp = offsets.data ();
11904   origin_child_die = origin_die->child;
11905   while (origin_child_die && origin_child_die->tag)
11906     {
11907       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11908       while (offsetp < offsets_end
11909              && *offsetp < origin_child_die->sect_off)
11910         offsetp++;
11911       if (offsetp >= offsets_end
11912           || *offsetp > origin_child_die->sect_off)
11913         {
11914           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11915              Check whether we're already processing ORIGIN_CHILD_DIE.
11916              This can happen with mutually referenced abstract_origins.
11917              PR 16581.  */
11918           if (!origin_child_die->in_process)
11919             process_die (origin_child_die, origin_cu);
11920         }
11921       origin_child_die = sibling_die (origin_child_die);
11922     }
11923   origin_cu->list_in_scope = origin_previous_list_in_scope;
11924 }
11925
11926 static void
11927 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11928 {
11929   struct objfile *objfile = cu->objfile;
11930   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11931   struct context_stack *newobj;
11932   CORE_ADDR lowpc;
11933   CORE_ADDR highpc;
11934   struct die_info *child_die;
11935   struct attribute *attr, *call_line, *call_file;
11936   const char *name;
11937   CORE_ADDR baseaddr;
11938   struct block *block;
11939   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11940   VEC (symbolp) *template_args = NULL;
11941   struct template_symbol *templ_func = NULL;
11942
11943   if (inlined_func)
11944     {
11945       /* If we do not have call site information, we can't show the
11946          caller of this inlined function.  That's too confusing, so
11947          only use the scope for local variables.  */
11948       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11949       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11950       if (call_line == NULL || call_file == NULL)
11951         {
11952           read_lexical_block_scope (die, cu);
11953           return;
11954         }
11955     }
11956
11957   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11958
11959   name = dwarf2_name (die, cu);
11960
11961   /* Ignore functions with missing or empty names.  These are actually
11962      illegal according to the DWARF standard.  */
11963   if (name == NULL)
11964     {
11965       complaint (&symfile_complaints,
11966                  _("missing name for subprogram DIE at %d"),
11967                  to_underlying (die->sect_off));
11968       return;
11969     }
11970
11971   /* Ignore functions with missing or invalid low and high pc attributes.  */
11972   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11973       <= PC_BOUNDS_INVALID)
11974     {
11975       attr = dwarf2_attr (die, DW_AT_external, cu);
11976       if (!attr || !DW_UNSND (attr))
11977         complaint (&symfile_complaints,
11978                    _("cannot get low and high bounds "
11979                      "for subprogram DIE at %d"),
11980                    to_underlying (die->sect_off));
11981       return;
11982     }
11983
11984   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11985   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11986
11987   /* If we have any template arguments, then we must allocate a
11988      different sort of symbol.  */
11989   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11990     {
11991       if (child_die->tag == DW_TAG_template_type_param
11992           || child_die->tag == DW_TAG_template_value_param)
11993         {
11994           templ_func = allocate_template_symbol (objfile);
11995           templ_func->base.is_cplus_template_function = 1;
11996           break;
11997         }
11998     }
11999
12000   newobj = push_context (0, lowpc);
12001   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
12002                                (struct symbol *) templ_func);
12003
12004   /* If there is a location expression for DW_AT_frame_base, record
12005      it.  */
12006   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12007   if (attr)
12008     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12009
12010   /* If there is a location for the static link, record it.  */
12011   newobj->static_link = NULL;
12012   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12013   if (attr)
12014     {
12015       newobj->static_link
12016         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12017       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12018     }
12019
12020   cu->list_in_scope = &local_symbols;
12021
12022   if (die->child != NULL)
12023     {
12024       child_die = die->child;
12025       while (child_die && child_die->tag)
12026         {
12027           if (child_die->tag == DW_TAG_template_type_param
12028               || child_die->tag == DW_TAG_template_value_param)
12029             {
12030               struct symbol *arg = new_symbol (child_die, NULL, cu);
12031
12032               if (arg != NULL)
12033                 VEC_safe_push (symbolp, template_args, arg);
12034             }
12035           else
12036             process_die (child_die, cu);
12037           child_die = sibling_die (child_die);
12038         }
12039     }
12040
12041   inherit_abstract_dies (die, cu);
12042
12043   /* If we have a DW_AT_specification, we might need to import using
12044      directives from the context of the specification DIE.  See the
12045      comment in determine_prefix.  */
12046   if (cu->language == language_cplus
12047       && dwarf2_attr (die, DW_AT_specification, cu))
12048     {
12049       struct dwarf2_cu *spec_cu = cu;
12050       struct die_info *spec_die = die_specification (die, &spec_cu);
12051
12052       while (spec_die)
12053         {
12054           child_die = spec_die->child;
12055           while (child_die && child_die->tag)
12056             {
12057               if (child_die->tag == DW_TAG_imported_module)
12058                 process_die (child_die, spec_cu);
12059               child_die = sibling_die (child_die);
12060             }
12061
12062           /* In some cases, GCC generates specification DIEs that
12063              themselves contain DW_AT_specification attributes.  */
12064           spec_die = die_specification (spec_die, &spec_cu);
12065         }
12066     }
12067
12068   newobj = pop_context ();
12069   /* Make a block for the local symbols within.  */
12070   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12071                         newobj->static_link, lowpc, highpc);
12072
12073   /* For C++, set the block's scope.  */
12074   if ((cu->language == language_cplus
12075        || cu->language == language_fortran
12076        || cu->language == language_d
12077        || cu->language == language_rust)
12078       && cu->processing_has_namespace_info)
12079     block_set_scope (block, determine_prefix (die, cu),
12080                      &objfile->objfile_obstack);
12081
12082   /* If we have address ranges, record them.  */
12083   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12084
12085   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12086
12087   /* Attach template arguments to function.  */
12088   if (! VEC_empty (symbolp, template_args))
12089     {
12090       gdb_assert (templ_func != NULL);
12091
12092       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
12093       templ_func->template_arguments
12094         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12095                      templ_func->n_template_arguments);
12096       memcpy (templ_func->template_arguments,
12097               VEC_address (symbolp, template_args),
12098               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12099       VEC_free (symbolp, template_args);
12100     }
12101
12102   /* In C++, we can have functions nested inside functions (e.g., when
12103      a function declares a class that has methods).  This means that
12104      when we finish processing a function scope, we may need to go
12105      back to building a containing block's symbol lists.  */
12106   local_symbols = newobj->locals;
12107   local_using_directives = newobj->local_using_directives;
12108
12109   /* If we've finished processing a top-level function, subsequent
12110      symbols go in the file symbol list.  */
12111   if (outermost_context_p ())
12112     cu->list_in_scope = &file_symbols;
12113 }
12114
12115 /* Process all the DIES contained within a lexical block scope.  Start
12116    a new scope, process the dies, and then close the scope.  */
12117
12118 static void
12119 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12120 {
12121   struct objfile *objfile = cu->objfile;
12122   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12123   struct context_stack *newobj;
12124   CORE_ADDR lowpc, highpc;
12125   struct die_info *child_die;
12126   CORE_ADDR baseaddr;
12127
12128   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12129
12130   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12131   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12132      as multiple lexical blocks?  Handling children in a sane way would
12133      be nasty.  Might be easier to properly extend generic blocks to
12134      describe ranges.  */
12135   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12136     {
12137     case PC_BOUNDS_NOT_PRESENT:
12138       /* DW_TAG_lexical_block has no attributes, process its children as if
12139          there was no wrapping by that DW_TAG_lexical_block.
12140          GCC does no longer produces such DWARF since GCC r224161.  */
12141       for (child_die = die->child;
12142            child_die != NULL && child_die->tag;
12143            child_die = sibling_die (child_die))
12144         process_die (child_die, cu);
12145       return;
12146     case PC_BOUNDS_INVALID:
12147       return;
12148     }
12149   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12150   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12151
12152   push_context (0, lowpc);
12153   if (die->child != NULL)
12154     {
12155       child_die = die->child;
12156       while (child_die && child_die->tag)
12157         {
12158           process_die (child_die, cu);
12159           child_die = sibling_die (child_die);
12160         }
12161     }
12162   inherit_abstract_dies (die, cu);
12163   newobj = pop_context ();
12164
12165   if (local_symbols != NULL || local_using_directives != NULL)
12166     {
12167       struct block *block
12168         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12169                         newobj->start_addr, highpc);
12170
12171       /* Note that recording ranges after traversing children, as we
12172          do here, means that recording a parent's ranges entails
12173          walking across all its children's ranges as they appear in
12174          the address map, which is quadratic behavior.
12175
12176          It would be nicer to record the parent's ranges before
12177          traversing its children, simply overriding whatever you find
12178          there.  But since we don't even decide whether to create a
12179          block until after we've traversed its children, that's hard
12180          to do.  */
12181       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12182     }
12183   local_symbols = newobj->locals;
12184   local_using_directives = newobj->local_using_directives;
12185 }
12186
12187 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12188
12189 static void
12190 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12191 {
12192   struct objfile *objfile = cu->objfile;
12193   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12194   CORE_ADDR pc, baseaddr;
12195   struct attribute *attr;
12196   struct call_site *call_site, call_site_local;
12197   void **slot;
12198   int nparams;
12199   struct die_info *child_die;
12200
12201   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12202
12203   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12204   if (attr == NULL)
12205     {
12206       /* This was a pre-DWARF-5 GNU extension alias
12207          for DW_AT_call_return_pc.  */
12208       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12209     }
12210   if (!attr)
12211     {
12212       complaint (&symfile_complaints,
12213                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12214                    "DIE 0x%x [in module %s]"),
12215                  to_underlying (die->sect_off), objfile_name (objfile));
12216       return;
12217     }
12218   pc = attr_value_as_address (attr) + baseaddr;
12219   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12220
12221   if (cu->call_site_htab == NULL)
12222     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12223                                                NULL, &objfile->objfile_obstack,
12224                                                hashtab_obstack_allocate, NULL);
12225   call_site_local.pc = pc;
12226   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12227   if (*slot != NULL)
12228     {
12229       complaint (&symfile_complaints,
12230                  _("Duplicate PC %s for DW_TAG_call_site "
12231                    "DIE 0x%x [in module %s]"),
12232                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12233                  objfile_name (objfile));
12234       return;
12235     }
12236
12237   /* Count parameters at the caller.  */
12238
12239   nparams = 0;
12240   for (child_die = die->child; child_die && child_die->tag;
12241        child_die = sibling_die (child_die))
12242     {
12243       if (child_die->tag != DW_TAG_call_site_parameter
12244           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12245         {
12246           complaint (&symfile_complaints,
12247                      _("Tag %d is not DW_TAG_call_site_parameter in "
12248                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12249                      child_die->tag, to_underlying (child_die->sect_off),
12250                      objfile_name (objfile));
12251           continue;
12252         }
12253
12254       nparams++;
12255     }
12256
12257   call_site
12258     = ((struct call_site *)
12259        obstack_alloc (&objfile->objfile_obstack,
12260                       sizeof (*call_site)
12261                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12262   *slot = call_site;
12263   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12264   call_site->pc = pc;
12265
12266   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12267       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12268     {
12269       struct die_info *func_die;
12270
12271       /* Skip also over DW_TAG_inlined_subroutine.  */
12272       for (func_die = die->parent;
12273            func_die && func_die->tag != DW_TAG_subprogram
12274            && func_die->tag != DW_TAG_subroutine_type;
12275            func_die = func_die->parent);
12276
12277       /* DW_AT_call_all_calls is a superset
12278          of DW_AT_call_all_tail_calls.  */
12279       if (func_die
12280           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12281           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12282           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12283           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12284         {
12285           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12286              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12287              both the initial caller containing the real return address PC and
12288              the final callee containing the current PC of a chain of tail
12289              calls do not need to have the tail call list complete.  But any
12290              function candidate for a virtual tail call frame searched via
12291              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12292              determined unambiguously.  */
12293         }
12294       else
12295         {
12296           struct type *func_type = NULL;
12297
12298           if (func_die)
12299             func_type = get_die_type (func_die, cu);
12300           if (func_type != NULL)
12301             {
12302               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12303
12304               /* Enlist this call site to the function.  */
12305               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12306               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12307             }
12308           else
12309             complaint (&symfile_complaints,
12310                        _("Cannot find function owning DW_TAG_call_site "
12311                          "DIE 0x%x [in module %s]"),
12312                        to_underlying (die->sect_off), objfile_name (objfile));
12313         }
12314     }
12315
12316   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12317   if (attr == NULL)
12318     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12319   if (attr == NULL)
12320     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12321   if (attr == NULL)
12322     {
12323       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12324       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12325     }
12326   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12327   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12328     /* Keep NULL DWARF_BLOCK.  */;
12329   else if (attr_form_is_block (attr))
12330     {
12331       struct dwarf2_locexpr_baton *dlbaton;
12332
12333       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12334       dlbaton->data = DW_BLOCK (attr)->data;
12335       dlbaton->size = DW_BLOCK (attr)->size;
12336       dlbaton->per_cu = cu->per_cu;
12337
12338       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12339     }
12340   else if (attr_form_is_ref (attr))
12341     {
12342       struct dwarf2_cu *target_cu = cu;
12343       struct die_info *target_die;
12344
12345       target_die = follow_die_ref (die, attr, &target_cu);
12346       gdb_assert (target_cu->objfile == objfile);
12347       if (die_is_declaration (target_die, target_cu))
12348         {
12349           const char *target_physname;
12350
12351           /* Prefer the mangled name; otherwise compute the demangled one.  */
12352           target_physname = dw2_linkage_name (target_die, target_cu);
12353           if (target_physname == NULL)
12354             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12355           if (target_physname == NULL)
12356             complaint (&symfile_complaints,
12357                        _("DW_AT_call_target target DIE has invalid "
12358                          "physname, for referencing DIE 0x%x [in module %s]"),
12359                        to_underlying (die->sect_off), objfile_name (objfile));
12360           else
12361             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12362         }
12363       else
12364         {
12365           CORE_ADDR lowpc;
12366
12367           /* DW_AT_entry_pc should be preferred.  */
12368           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12369               <= PC_BOUNDS_INVALID)
12370             complaint (&symfile_complaints,
12371                        _("DW_AT_call_target target DIE has invalid "
12372                          "low pc, for referencing DIE 0x%x [in module %s]"),
12373                        to_underlying (die->sect_off), objfile_name (objfile));
12374           else
12375             {
12376               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12377               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12378             }
12379         }
12380     }
12381   else
12382     complaint (&symfile_complaints,
12383                _("DW_TAG_call_site DW_AT_call_target is neither "
12384                  "block nor reference, for DIE 0x%x [in module %s]"),
12385                to_underlying (die->sect_off), objfile_name (objfile));
12386
12387   call_site->per_cu = cu->per_cu;
12388
12389   for (child_die = die->child;
12390        child_die && child_die->tag;
12391        child_die = sibling_die (child_die))
12392     {
12393       struct call_site_parameter *parameter;
12394       struct attribute *loc, *origin;
12395
12396       if (child_die->tag != DW_TAG_call_site_parameter
12397           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12398         {
12399           /* Already printed the complaint above.  */
12400           continue;
12401         }
12402
12403       gdb_assert (call_site->parameter_count < nparams);
12404       parameter = &call_site->parameter[call_site->parameter_count];
12405
12406       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12407          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12408          register is contained in DW_AT_call_value.  */
12409
12410       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12411       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12412       if (origin == NULL)
12413         {
12414           /* This was a pre-DWARF-5 GNU extension alias
12415              for DW_AT_call_parameter.  */
12416           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12417         }
12418       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12419         {
12420           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12421
12422           sect_offset sect_off
12423             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12424           if (!offset_in_cu_p (&cu->header, sect_off))
12425             {
12426               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12427                  binding can be done only inside one CU.  Such referenced DIE
12428                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12429               complaint (&symfile_complaints,
12430                          _("DW_AT_call_parameter offset is not in CU for "
12431                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12432                          to_underlying (child_die->sect_off),
12433                          objfile_name (objfile));
12434               continue;
12435             }
12436           parameter->u.param_cu_off
12437             = (cu_offset) (sect_off - cu->header.sect_off);
12438         }
12439       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12440         {
12441           complaint (&symfile_complaints,
12442                      _("No DW_FORM_block* DW_AT_location for "
12443                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12444                      to_underlying (child_die->sect_off), objfile_name (objfile));
12445           continue;
12446         }
12447       else
12448         {
12449           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12450             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12451           if (parameter->u.dwarf_reg != -1)
12452             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12453           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12454                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12455                                              &parameter->u.fb_offset))
12456             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12457           else
12458             {
12459               complaint (&symfile_complaints,
12460                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12461                            "for DW_FORM_block* DW_AT_location is supported for "
12462                            "DW_TAG_call_site child DIE 0x%x "
12463                            "[in module %s]"),
12464                          to_underlying (child_die->sect_off),
12465                          objfile_name (objfile));
12466               continue;
12467             }
12468         }
12469
12470       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12471       if (attr == NULL)
12472         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12473       if (!attr_form_is_block (attr))
12474         {
12475           complaint (&symfile_complaints,
12476                      _("No DW_FORM_block* DW_AT_call_value for "
12477                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12478                      to_underlying (child_die->sect_off),
12479                      objfile_name (objfile));
12480           continue;
12481         }
12482       parameter->value = DW_BLOCK (attr)->data;
12483       parameter->value_size = DW_BLOCK (attr)->size;
12484
12485       /* Parameters are not pre-cleared by memset above.  */
12486       parameter->data_value = NULL;
12487       parameter->data_value_size = 0;
12488       call_site->parameter_count++;
12489
12490       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12491       if (attr == NULL)
12492         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12493       if (attr)
12494         {
12495           if (!attr_form_is_block (attr))
12496             complaint (&symfile_complaints,
12497                        _("No DW_FORM_block* DW_AT_call_data_value for "
12498                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12499                        to_underlying (child_die->sect_off),
12500                        objfile_name (objfile));
12501           else
12502             {
12503               parameter->data_value = DW_BLOCK (attr)->data;
12504               parameter->data_value_size = DW_BLOCK (attr)->size;
12505             }
12506         }
12507     }
12508 }
12509
12510 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12511    reading .debug_rnglists.
12512    Callback's type should be:
12513     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12514    Return true if the attributes are present and valid, otherwise,
12515    return false.  */
12516
12517 template <typename Callback>
12518 static bool
12519 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12520                          Callback &&callback)
12521 {
12522   struct objfile *objfile = cu->objfile;
12523   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12524   struct comp_unit_head *cu_header = &cu->header;
12525   bfd *obfd = objfile->obfd;
12526   unsigned int addr_size = cu_header->addr_size;
12527   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12528   /* Base address selection entry.  */
12529   CORE_ADDR base;
12530   int found_base;
12531   unsigned int dummy;
12532   const gdb_byte *buffer;
12533   CORE_ADDR low = 0;
12534   CORE_ADDR high = 0;
12535   CORE_ADDR baseaddr;
12536   bool overflow = false;
12537
12538   found_base = cu->base_known;
12539   base = cu->base_address;
12540
12541   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12542   if (offset >= dwarf2_per_objfile->rnglists.size)
12543     {
12544       complaint (&symfile_complaints,
12545                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12546                  offset);
12547       return false;
12548     }
12549   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12550
12551   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12552
12553   while (1)
12554     {
12555       /* Initialize it due to a false compiler warning.  */
12556       CORE_ADDR range_beginning = 0, range_end = 0;
12557       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12558                                  + dwarf2_per_objfile->rnglists.size);
12559       unsigned int bytes_read;
12560
12561       if (buffer == buf_end)
12562         {
12563           overflow = true;
12564           break;
12565         }
12566       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12567       switch (rlet)
12568         {
12569         case DW_RLE_end_of_list:
12570           break;
12571         case DW_RLE_base_address:
12572           if (buffer + cu->header.addr_size > buf_end)
12573             {
12574               overflow = true;
12575               break;
12576             }
12577           base = read_address (obfd, buffer, cu, &bytes_read);
12578           found_base = 1;
12579           buffer += bytes_read;
12580           break;
12581         case DW_RLE_start_length:
12582           if (buffer + cu->header.addr_size > buf_end)
12583             {
12584               overflow = true;
12585               break;
12586             }
12587           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12588           buffer += bytes_read;
12589           range_end = (range_beginning
12590                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12591           buffer += bytes_read;
12592           if (buffer > buf_end)
12593             {
12594               overflow = true;
12595               break;
12596             }
12597           break;
12598         case DW_RLE_offset_pair:
12599           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12600           buffer += bytes_read;
12601           if (buffer > buf_end)
12602             {
12603               overflow = true;
12604               break;
12605             }
12606           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12607           buffer += bytes_read;
12608           if (buffer > buf_end)
12609             {
12610               overflow = true;
12611               break;
12612             }
12613           break;
12614         case DW_RLE_start_end:
12615           if (buffer + 2 * cu->header.addr_size > buf_end)
12616             {
12617               overflow = true;
12618               break;
12619             }
12620           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12621           buffer += bytes_read;
12622           range_end = read_address (obfd, buffer, cu, &bytes_read);
12623           buffer += bytes_read;
12624           break;
12625         default:
12626           complaint (&symfile_complaints,
12627                      _("Invalid .debug_rnglists data (no base address)"));
12628           return false;
12629         }
12630       if (rlet == DW_RLE_end_of_list || overflow)
12631         break;
12632       if (rlet == DW_RLE_base_address)
12633         continue;
12634
12635       if (!found_base)
12636         {
12637           /* We have no valid base address for the ranges
12638              data.  */
12639           complaint (&symfile_complaints,
12640                      _("Invalid .debug_rnglists data (no base address)"));
12641           return false;
12642         }
12643
12644       if (range_beginning > range_end)
12645         {
12646           /* Inverted range entries are invalid.  */
12647           complaint (&symfile_complaints,
12648                      _("Invalid .debug_rnglists data (inverted range)"));
12649           return false;
12650         }
12651
12652       /* Empty range entries have no effect.  */
12653       if (range_beginning == range_end)
12654         continue;
12655
12656       range_beginning += base;
12657       range_end += base;
12658
12659       /* A not-uncommon case of bad debug info.
12660          Don't pollute the addrmap with bad data.  */
12661       if (range_beginning + baseaddr == 0
12662           && !dwarf2_per_objfile->has_section_at_zero)
12663         {
12664           complaint (&symfile_complaints,
12665                      _(".debug_rnglists entry has start address of zero"
12666                        " [in module %s]"), objfile_name (objfile));
12667           continue;
12668         }
12669
12670       callback (range_beginning, range_end);
12671     }
12672
12673   if (overflow)
12674     {
12675       complaint (&symfile_complaints,
12676                  _("Offset %d is not terminated "
12677                    "for DW_AT_ranges attribute"),
12678                  offset);
12679       return false;
12680     }
12681
12682   return true;
12683 }
12684
12685 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12686    Callback's type should be:
12687     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12688    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12689
12690 template <typename Callback>
12691 static int
12692 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12693                        Callback &&callback)
12694 {
12695   struct objfile *objfile = cu->objfile;
12696   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12697   struct comp_unit_head *cu_header = &cu->header;
12698   bfd *obfd = objfile->obfd;
12699   unsigned int addr_size = cu_header->addr_size;
12700   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12701   /* Base address selection entry.  */
12702   CORE_ADDR base;
12703   int found_base;
12704   unsigned int dummy;
12705   const gdb_byte *buffer;
12706   CORE_ADDR baseaddr;
12707
12708   if (cu_header->version >= 5)
12709     return dwarf2_rnglists_process (offset, cu, callback);
12710
12711   found_base = cu->base_known;
12712   base = cu->base_address;
12713
12714   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12715   if (offset >= dwarf2_per_objfile->ranges.size)
12716     {
12717       complaint (&symfile_complaints,
12718                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12719                  offset);
12720       return 0;
12721     }
12722   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12723
12724   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12725
12726   while (1)
12727     {
12728       CORE_ADDR range_beginning, range_end;
12729
12730       range_beginning = read_address (obfd, buffer, cu, &dummy);
12731       buffer += addr_size;
12732       range_end = read_address (obfd, buffer, cu, &dummy);
12733       buffer += addr_size;
12734       offset += 2 * addr_size;
12735
12736       /* An end of list marker is a pair of zero addresses.  */
12737       if (range_beginning == 0 && range_end == 0)
12738         /* Found the end of list entry.  */
12739         break;
12740
12741       /* Each base address selection entry is a pair of 2 values.
12742          The first is the largest possible address, the second is
12743          the base address.  Check for a base address here.  */
12744       if ((range_beginning & mask) == mask)
12745         {
12746           /* If we found the largest possible address, then we already
12747              have the base address in range_end.  */
12748           base = range_end;
12749           found_base = 1;
12750           continue;
12751         }
12752
12753       if (!found_base)
12754         {
12755           /* We have no valid base address for the ranges
12756              data.  */
12757           complaint (&symfile_complaints,
12758                      _("Invalid .debug_ranges data (no base address)"));
12759           return 0;
12760         }
12761
12762       if (range_beginning > range_end)
12763         {
12764           /* Inverted range entries are invalid.  */
12765           complaint (&symfile_complaints,
12766                      _("Invalid .debug_ranges data (inverted range)"));
12767           return 0;
12768         }
12769
12770       /* Empty range entries have no effect.  */
12771       if (range_beginning == range_end)
12772         continue;
12773
12774       range_beginning += base;
12775       range_end += base;
12776
12777       /* A not-uncommon case of bad debug info.
12778          Don't pollute the addrmap with bad data.  */
12779       if (range_beginning + baseaddr == 0
12780           && !dwarf2_per_objfile->has_section_at_zero)
12781         {
12782           complaint (&symfile_complaints,
12783                      _(".debug_ranges entry has start address of zero"
12784                        " [in module %s]"), objfile_name (objfile));
12785           continue;
12786         }
12787
12788       callback (range_beginning, range_end);
12789     }
12790
12791   return 1;
12792 }
12793
12794 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12795    Return 1 if the attributes are present and valid, otherwise, return 0.
12796    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12797
12798 static int
12799 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12800                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12801                     struct partial_symtab *ranges_pst)
12802 {
12803   struct objfile *objfile = cu->objfile;
12804   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12805   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12806                                        SECT_OFF_TEXT (objfile));
12807   int low_set = 0;
12808   CORE_ADDR low = 0;
12809   CORE_ADDR high = 0;
12810   int retval;
12811
12812   retval = dwarf2_ranges_process (offset, cu,
12813     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12814     {
12815       if (ranges_pst != NULL)
12816         {
12817           CORE_ADDR lowpc;
12818           CORE_ADDR highpc;
12819
12820           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12821                                               range_beginning + baseaddr);
12822           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12823                                                range_end + baseaddr);
12824           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12825                              ranges_pst);
12826         }
12827
12828       /* FIXME: This is recording everything as a low-high
12829          segment of consecutive addresses.  We should have a
12830          data structure for discontiguous block ranges
12831          instead.  */
12832       if (! low_set)
12833         {
12834           low = range_beginning;
12835           high = range_end;
12836           low_set = 1;
12837         }
12838       else
12839         {
12840           if (range_beginning < low)
12841             low = range_beginning;
12842           if (range_end > high)
12843             high = range_end;
12844         }
12845     });
12846   if (!retval)
12847     return 0;
12848
12849   if (! low_set)
12850     /* If the first entry is an end-of-list marker, the range
12851        describes an empty scope, i.e. no instructions.  */
12852     return 0;
12853
12854   if (low_return)
12855     *low_return = low;
12856   if (high_return)
12857     *high_return = high;
12858   return 1;
12859 }
12860
12861 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12862    definition for the return value.  *LOWPC and *HIGHPC are set iff
12863    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12864
12865 static enum pc_bounds_kind
12866 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12867                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12868                       struct partial_symtab *pst)
12869 {
12870   struct attribute *attr;
12871   struct attribute *attr_high;
12872   CORE_ADDR low = 0;
12873   CORE_ADDR high = 0;
12874   enum pc_bounds_kind ret;
12875
12876   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12877   if (attr_high)
12878     {
12879       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12880       if (attr)
12881         {
12882           low = attr_value_as_address (attr);
12883           high = attr_value_as_address (attr_high);
12884           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12885             high += low;
12886         }
12887       else
12888         /* Found high w/o low attribute.  */
12889         return PC_BOUNDS_INVALID;
12890
12891       /* Found consecutive range of addresses.  */
12892       ret = PC_BOUNDS_HIGH_LOW;
12893     }
12894   else
12895     {
12896       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12897       if (attr != NULL)
12898         {
12899           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12900              We take advantage of the fact that DW_AT_ranges does not appear
12901              in DW_TAG_compile_unit of DWO files.  */
12902           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12903           unsigned int ranges_offset = (DW_UNSND (attr)
12904                                         + (need_ranges_base
12905                                            ? cu->ranges_base
12906                                            : 0));
12907
12908           /* Value of the DW_AT_ranges attribute is the offset in the
12909              .debug_ranges section.  */
12910           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12911             return PC_BOUNDS_INVALID;
12912           /* Found discontinuous range of addresses.  */
12913           ret = PC_BOUNDS_RANGES;
12914         }
12915       else
12916         return PC_BOUNDS_NOT_PRESENT;
12917     }
12918
12919   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12920   if (high <= low)
12921     return PC_BOUNDS_INVALID;
12922
12923   /* When using the GNU linker, .gnu.linkonce. sections are used to
12924      eliminate duplicate copies of functions and vtables and such.
12925      The linker will arbitrarily choose one and discard the others.
12926      The AT_*_pc values for such functions refer to local labels in
12927      these sections.  If the section from that file was discarded, the
12928      labels are not in the output, so the relocs get a value of 0.
12929      If this is a discarded function, mark the pc bounds as invalid,
12930      so that GDB will ignore it.  */
12931   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12932     return PC_BOUNDS_INVALID;
12933
12934   *lowpc = low;
12935   if (highpc)
12936     *highpc = high;
12937   return ret;
12938 }
12939
12940 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12941    its low and high PC addresses.  Do nothing if these addresses could not
12942    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12943    and HIGHPC to the high address if greater than HIGHPC.  */
12944
12945 static void
12946 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12947                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12948                                  struct dwarf2_cu *cu)
12949 {
12950   CORE_ADDR low, high;
12951   struct die_info *child = die->child;
12952
12953   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12954     {
12955       *lowpc = std::min (*lowpc, low);
12956       *highpc = std::max (*highpc, high);
12957     }
12958
12959   /* If the language does not allow nested subprograms (either inside
12960      subprograms or lexical blocks), we're done.  */
12961   if (cu->language != language_ada)
12962     return;
12963
12964   /* Check all the children of the given DIE.  If it contains nested
12965      subprograms, then check their pc bounds.  Likewise, we need to
12966      check lexical blocks as well, as they may also contain subprogram
12967      definitions.  */
12968   while (child && child->tag)
12969     {
12970       if (child->tag == DW_TAG_subprogram
12971           || child->tag == DW_TAG_lexical_block)
12972         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12973       child = sibling_die (child);
12974     }
12975 }
12976
12977 /* Get the low and high pc's represented by the scope DIE, and store
12978    them in *LOWPC and *HIGHPC.  If the correct values can't be
12979    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12980
12981 static void
12982 get_scope_pc_bounds (struct die_info *die,
12983                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12984                      struct dwarf2_cu *cu)
12985 {
12986   CORE_ADDR best_low = (CORE_ADDR) -1;
12987   CORE_ADDR best_high = (CORE_ADDR) 0;
12988   CORE_ADDR current_low, current_high;
12989
12990   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12991       >= PC_BOUNDS_RANGES)
12992     {
12993       best_low = current_low;
12994       best_high = current_high;
12995     }
12996   else
12997     {
12998       struct die_info *child = die->child;
12999
13000       while (child && child->tag)
13001         {
13002           switch (child->tag) {
13003           case DW_TAG_subprogram:
13004             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13005             break;
13006           case DW_TAG_namespace:
13007           case DW_TAG_module:
13008             /* FIXME: carlton/2004-01-16: Should we do this for
13009                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13010                that current GCC's always emit the DIEs corresponding
13011                to definitions of methods of classes as children of a
13012                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13013                the DIEs giving the declarations, which could be
13014                anywhere).  But I don't see any reason why the
13015                standards says that they have to be there.  */
13016             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13017
13018             if (current_low != ((CORE_ADDR) -1))
13019               {
13020                 best_low = std::min (best_low, current_low);
13021                 best_high = std::max (best_high, current_high);
13022               }
13023             break;
13024           default:
13025             /* Ignore.  */
13026             break;
13027           }
13028
13029           child = sibling_die (child);
13030         }
13031     }
13032
13033   *lowpc = best_low;
13034   *highpc = best_high;
13035 }
13036
13037 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13038    in DIE.  */
13039
13040 static void
13041 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13042                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13043 {
13044   struct objfile *objfile = cu->objfile;
13045   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13046   struct attribute *attr;
13047   struct attribute *attr_high;
13048
13049   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13050   if (attr_high)
13051     {
13052       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13053       if (attr)
13054         {
13055           CORE_ADDR low = attr_value_as_address (attr);
13056           CORE_ADDR high = attr_value_as_address (attr_high);
13057
13058           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13059             high += low;
13060
13061           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13062           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13063           record_block_range (block, low, high - 1);
13064         }
13065     }
13066
13067   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13068   if (attr)
13069     {
13070       bfd *obfd = objfile->obfd;
13071       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13072          We take advantage of the fact that DW_AT_ranges does not appear
13073          in DW_TAG_compile_unit of DWO files.  */
13074       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13075
13076       /* The value of the DW_AT_ranges attribute is the offset of the
13077          address range list in the .debug_ranges section.  */
13078       unsigned long offset = (DW_UNSND (attr)
13079                               + (need_ranges_base ? cu->ranges_base : 0));
13080       const gdb_byte *buffer;
13081
13082       /* For some target architectures, but not others, the
13083          read_address function sign-extends the addresses it returns.
13084          To recognize base address selection entries, we need a
13085          mask.  */
13086       unsigned int addr_size = cu->header.addr_size;
13087       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13088
13089       /* The base address, to which the next pair is relative.  Note
13090          that this 'base' is a DWARF concept: most entries in a range
13091          list are relative, to reduce the number of relocs against the
13092          debugging information.  This is separate from this function's
13093          'baseaddr' argument, which GDB uses to relocate debugging
13094          information from a shared library based on the address at
13095          which the library was loaded.  */
13096       CORE_ADDR base = cu->base_address;
13097       int base_known = cu->base_known;
13098
13099       dwarf2_ranges_process (offset, cu,
13100         [&] (CORE_ADDR start, CORE_ADDR end)
13101         {
13102           start += baseaddr;
13103           end += baseaddr;
13104           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13105           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13106           record_block_range (block, start, end - 1);
13107         });
13108     }
13109 }
13110
13111 /* Check whether the producer field indicates either of GCC < 4.6, or the
13112    Intel C/C++ compiler, and cache the result in CU.  */
13113
13114 static void
13115 check_producer (struct dwarf2_cu *cu)
13116 {
13117   int major, minor;
13118
13119   if (cu->producer == NULL)
13120     {
13121       /* For unknown compilers expect their behavior is DWARF version
13122          compliant.
13123
13124          GCC started to support .debug_types sections by -gdwarf-4 since
13125          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13126          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13127          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13128          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13129     }
13130   else if (producer_is_gcc (cu->producer, &major, &minor))
13131     {
13132       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13133       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13134     }
13135   else if (producer_is_icc (cu->producer, &major, &minor))
13136     cu->producer_is_icc_lt_14 = major < 14;
13137   else
13138     {
13139       /* For other non-GCC compilers, expect their behavior is DWARF version
13140          compliant.  */
13141     }
13142
13143   cu->checked_producer = 1;
13144 }
13145
13146 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13147    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13148    during 4.6.0 experimental.  */
13149
13150 static int
13151 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13152 {
13153   if (!cu->checked_producer)
13154     check_producer (cu);
13155
13156   return cu->producer_is_gxx_lt_4_6;
13157 }
13158
13159 /* Return the default accessibility type if it is not overriden by
13160    DW_AT_accessibility.  */
13161
13162 static enum dwarf_access_attribute
13163 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13164 {
13165   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13166     {
13167       /* The default DWARF 2 accessibility for members is public, the default
13168          accessibility for inheritance is private.  */
13169
13170       if (die->tag != DW_TAG_inheritance)
13171         return DW_ACCESS_public;
13172       else
13173         return DW_ACCESS_private;
13174     }
13175   else
13176     {
13177       /* DWARF 3+ defines the default accessibility a different way.  The same
13178          rules apply now for DW_TAG_inheritance as for the members and it only
13179          depends on the container kind.  */
13180
13181       if (die->parent->tag == DW_TAG_class_type)
13182         return DW_ACCESS_private;
13183       else
13184         return DW_ACCESS_public;
13185     }
13186 }
13187
13188 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13189    offset.  If the attribute was not found return 0, otherwise return
13190    1.  If it was found but could not properly be handled, set *OFFSET
13191    to 0.  */
13192
13193 static int
13194 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13195                              LONGEST *offset)
13196 {
13197   struct attribute *attr;
13198
13199   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13200   if (attr != NULL)
13201     {
13202       *offset = 0;
13203
13204       /* Note that we do not check for a section offset first here.
13205          This is because DW_AT_data_member_location is new in DWARF 4,
13206          so if we see it, we can assume that a constant form is really
13207          a constant and not a section offset.  */
13208       if (attr_form_is_constant (attr))
13209         *offset = dwarf2_get_attr_constant_value (attr, 0);
13210       else if (attr_form_is_section_offset (attr))
13211         dwarf2_complex_location_expr_complaint ();
13212       else if (attr_form_is_block (attr))
13213         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13214       else
13215         dwarf2_complex_location_expr_complaint ();
13216
13217       return 1;
13218     }
13219
13220   return 0;
13221 }
13222
13223 /* Add an aggregate field to the field list.  */
13224
13225 static void
13226 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13227                   struct dwarf2_cu *cu)
13228 {
13229   struct objfile *objfile = cu->objfile;
13230   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13231   struct nextfield *new_field;
13232   struct attribute *attr;
13233   struct field *fp;
13234   const char *fieldname = "";
13235
13236   /* Allocate a new field list entry and link it in.  */
13237   new_field = XNEW (struct nextfield);
13238   make_cleanup (xfree, new_field);
13239   memset (new_field, 0, sizeof (struct nextfield));
13240
13241   if (die->tag == DW_TAG_inheritance)
13242     {
13243       new_field->next = fip->baseclasses;
13244       fip->baseclasses = new_field;
13245     }
13246   else
13247     {
13248       new_field->next = fip->fields;
13249       fip->fields = new_field;
13250     }
13251   fip->nfields++;
13252
13253   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13254   if (attr)
13255     new_field->accessibility = DW_UNSND (attr);
13256   else
13257     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13258   if (new_field->accessibility != DW_ACCESS_public)
13259     fip->non_public_fields = 1;
13260
13261   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13262   if (attr)
13263     new_field->virtuality = DW_UNSND (attr);
13264   else
13265     new_field->virtuality = DW_VIRTUALITY_none;
13266
13267   fp = &new_field->field;
13268
13269   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13270     {
13271       LONGEST offset;
13272
13273       /* Data member other than a C++ static data member.  */
13274
13275       /* Get type of field.  */
13276       fp->type = die_type (die, cu);
13277
13278       SET_FIELD_BITPOS (*fp, 0);
13279
13280       /* Get bit size of field (zero if none).  */
13281       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13282       if (attr)
13283         {
13284           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13285         }
13286       else
13287         {
13288           FIELD_BITSIZE (*fp) = 0;
13289         }
13290
13291       /* Get bit offset of field.  */
13292       if (handle_data_member_location (die, cu, &offset))
13293         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13294       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13295       if (attr)
13296         {
13297           if (gdbarch_bits_big_endian (gdbarch))
13298             {
13299               /* For big endian bits, the DW_AT_bit_offset gives the
13300                  additional bit offset from the MSB of the containing
13301                  anonymous object to the MSB of the field.  We don't
13302                  have to do anything special since we don't need to
13303                  know the size of the anonymous object.  */
13304               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13305             }
13306           else
13307             {
13308               /* For little endian bits, compute the bit offset to the
13309                  MSB of the anonymous object, subtract off the number of
13310                  bits from the MSB of the field to the MSB of the
13311                  object, and then subtract off the number of bits of
13312                  the field itself.  The result is the bit offset of
13313                  the LSB of the field.  */
13314               int anonymous_size;
13315               int bit_offset = DW_UNSND (attr);
13316
13317               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13318               if (attr)
13319                 {
13320                   /* The size of the anonymous object containing
13321                      the bit field is explicit, so use the
13322                      indicated size (in bytes).  */
13323                   anonymous_size = DW_UNSND (attr);
13324                 }
13325               else
13326                 {
13327                   /* The size of the anonymous object containing
13328                      the bit field must be inferred from the type
13329                      attribute of the data member containing the
13330                      bit field.  */
13331                   anonymous_size = TYPE_LENGTH (fp->type);
13332                 }
13333               SET_FIELD_BITPOS (*fp,
13334                                 (FIELD_BITPOS (*fp)
13335                                  + anonymous_size * bits_per_byte
13336                                  - bit_offset - FIELD_BITSIZE (*fp)));
13337             }
13338         }
13339       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13340       if (attr != NULL)
13341         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13342                                 + dwarf2_get_attr_constant_value (attr, 0)));
13343
13344       /* Get name of field.  */
13345       fieldname = dwarf2_name (die, cu);
13346       if (fieldname == NULL)
13347         fieldname = "";
13348
13349       /* The name is already allocated along with this objfile, so we don't
13350          need to duplicate it for the type.  */
13351       fp->name = fieldname;
13352
13353       /* Change accessibility for artificial fields (e.g. virtual table
13354          pointer or virtual base class pointer) to private.  */
13355       if (dwarf2_attr (die, DW_AT_artificial, cu))
13356         {
13357           FIELD_ARTIFICIAL (*fp) = 1;
13358           new_field->accessibility = DW_ACCESS_private;
13359           fip->non_public_fields = 1;
13360         }
13361     }
13362   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13363     {
13364       /* C++ static member.  */
13365
13366       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13367          is a declaration, but all versions of G++ as of this writing
13368          (so through at least 3.2.1) incorrectly generate
13369          DW_TAG_variable tags.  */
13370
13371       const char *physname;
13372
13373       /* Get name of field.  */
13374       fieldname = dwarf2_name (die, cu);
13375       if (fieldname == NULL)
13376         return;
13377
13378       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13379       if (attr
13380           /* Only create a symbol if this is an external value.
13381              new_symbol checks this and puts the value in the global symbol
13382              table, which we want.  If it is not external, new_symbol
13383              will try to put the value in cu->list_in_scope which is wrong.  */
13384           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13385         {
13386           /* A static const member, not much different than an enum as far as
13387              we're concerned, except that we can support more types.  */
13388           new_symbol (die, NULL, cu);
13389         }
13390
13391       /* Get physical name.  */
13392       physname = dwarf2_physname (fieldname, die, cu);
13393
13394       /* The name is already allocated along with this objfile, so we don't
13395          need to duplicate it for the type.  */
13396       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13397       FIELD_TYPE (*fp) = die_type (die, cu);
13398       FIELD_NAME (*fp) = fieldname;
13399     }
13400   else if (die->tag == DW_TAG_inheritance)
13401     {
13402       LONGEST offset;
13403
13404       /* C++ base class field.  */
13405       if (handle_data_member_location (die, cu, &offset))
13406         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13407       FIELD_BITSIZE (*fp) = 0;
13408       FIELD_TYPE (*fp) = die_type (die, cu);
13409       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13410       fip->nbaseclasses++;
13411     }
13412 }
13413
13414 /* Add a typedef defined in the scope of the FIP's class.  */
13415
13416 static void
13417 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13418                     struct dwarf2_cu *cu)
13419 {
13420   struct typedef_field_list *new_field;
13421   struct typedef_field *fp;
13422
13423   /* Allocate a new field list entry and link it in.  */
13424   new_field = XCNEW (struct typedef_field_list);
13425   make_cleanup (xfree, new_field);
13426
13427   gdb_assert (die->tag == DW_TAG_typedef);
13428
13429   fp = &new_field->field;
13430
13431   /* Get name of field.  */
13432   fp->name = dwarf2_name (die, cu);
13433   if (fp->name == NULL)
13434     return;
13435
13436   fp->type = read_type_die (die, cu);
13437
13438   /* Save accessibility.  */
13439   enum dwarf_access_attribute accessibility;
13440   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13441   if (attr != NULL)
13442     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13443   else
13444     accessibility = dwarf2_default_access_attribute (die, cu);
13445   switch (accessibility)
13446     {
13447     case DW_ACCESS_public:
13448       /* The assumed value if neither private nor protected.  */
13449       break;
13450     case DW_ACCESS_private:
13451       fp->is_private = 1;
13452       break;
13453     case DW_ACCESS_protected:
13454       fp->is_protected = 1;
13455       break;
13456     default:
13457       complaint (&symfile_complaints,
13458                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
13459     }
13460
13461   new_field->next = fip->typedef_field_list;
13462   fip->typedef_field_list = new_field;
13463   fip->typedef_field_list_count++;
13464 }
13465
13466 /* Create the vector of fields, and attach it to the type.  */
13467
13468 static void
13469 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13470                               struct dwarf2_cu *cu)
13471 {
13472   int nfields = fip->nfields;
13473
13474   /* Record the field count, allocate space for the array of fields,
13475      and create blank accessibility bitfields if necessary.  */
13476   TYPE_NFIELDS (type) = nfields;
13477   TYPE_FIELDS (type) = (struct field *)
13478     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13479   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13480
13481   if (fip->non_public_fields && cu->language != language_ada)
13482     {
13483       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13484
13485       TYPE_FIELD_PRIVATE_BITS (type) =
13486         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13487       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13488
13489       TYPE_FIELD_PROTECTED_BITS (type) =
13490         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13491       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13492
13493       TYPE_FIELD_IGNORE_BITS (type) =
13494         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13495       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13496     }
13497
13498   /* If the type has baseclasses, allocate and clear a bit vector for
13499      TYPE_FIELD_VIRTUAL_BITS.  */
13500   if (fip->nbaseclasses && cu->language != language_ada)
13501     {
13502       int num_bytes = B_BYTES (fip->nbaseclasses);
13503       unsigned char *pointer;
13504
13505       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13506       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13507       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13508       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13509       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13510     }
13511
13512   /* Copy the saved-up fields into the field vector.  Start from the head of
13513      the list, adding to the tail of the field array, so that they end up in
13514      the same order in the array in which they were added to the list.  */
13515   while (nfields-- > 0)
13516     {
13517       struct nextfield *fieldp;
13518
13519       if (fip->fields)
13520         {
13521           fieldp = fip->fields;
13522           fip->fields = fieldp->next;
13523         }
13524       else
13525         {
13526           fieldp = fip->baseclasses;
13527           fip->baseclasses = fieldp->next;
13528         }
13529
13530       TYPE_FIELD (type, nfields) = fieldp->field;
13531       switch (fieldp->accessibility)
13532         {
13533         case DW_ACCESS_private:
13534           if (cu->language != language_ada)
13535             SET_TYPE_FIELD_PRIVATE (type, nfields);
13536           break;
13537
13538         case DW_ACCESS_protected:
13539           if (cu->language != language_ada)
13540             SET_TYPE_FIELD_PROTECTED (type, nfields);
13541           break;
13542
13543         case DW_ACCESS_public:
13544           break;
13545
13546         default:
13547           /* Unknown accessibility.  Complain and treat it as public.  */
13548           {
13549             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13550                        fieldp->accessibility);
13551           }
13552           break;
13553         }
13554       if (nfields < fip->nbaseclasses)
13555         {
13556           switch (fieldp->virtuality)
13557             {
13558             case DW_VIRTUALITY_virtual:
13559             case DW_VIRTUALITY_pure_virtual:
13560               if (cu->language == language_ada)
13561                 error (_("unexpected virtuality in component of Ada type"));
13562               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13563               break;
13564             }
13565         }
13566     }
13567 }
13568
13569 /* Return true if this member function is a constructor, false
13570    otherwise.  */
13571
13572 static int
13573 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13574 {
13575   const char *fieldname;
13576   const char *type_name;
13577   int len;
13578
13579   if (die->parent == NULL)
13580     return 0;
13581
13582   if (die->parent->tag != DW_TAG_structure_type
13583       && die->parent->tag != DW_TAG_union_type
13584       && die->parent->tag != DW_TAG_class_type)
13585     return 0;
13586
13587   fieldname = dwarf2_name (die, cu);
13588   type_name = dwarf2_name (die->parent, cu);
13589   if (fieldname == NULL || type_name == NULL)
13590     return 0;
13591
13592   len = strlen (fieldname);
13593   return (strncmp (fieldname, type_name, len) == 0
13594           && (type_name[len] == '\0' || type_name[len] == '<'));
13595 }
13596
13597 /* Add a member function to the proper fieldlist.  */
13598
13599 static void
13600 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13601                       struct type *type, struct dwarf2_cu *cu)
13602 {
13603   struct objfile *objfile = cu->objfile;
13604   struct attribute *attr;
13605   struct fnfieldlist *flp;
13606   int i;
13607   struct fn_field *fnp;
13608   const char *fieldname;
13609   struct nextfnfield *new_fnfield;
13610   struct type *this_type;
13611   enum dwarf_access_attribute accessibility;
13612
13613   if (cu->language == language_ada)
13614     error (_("unexpected member function in Ada type"));
13615
13616   /* Get name of member function.  */
13617   fieldname = dwarf2_name (die, cu);
13618   if (fieldname == NULL)
13619     return;
13620
13621   /* Look up member function name in fieldlist.  */
13622   for (i = 0; i < fip->nfnfields; i++)
13623     {
13624       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13625         break;
13626     }
13627
13628   /* Create new list element if necessary.  */
13629   if (i < fip->nfnfields)
13630     flp = &fip->fnfieldlists[i];
13631   else
13632     {
13633       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13634         {
13635           fip->fnfieldlists = (struct fnfieldlist *)
13636             xrealloc (fip->fnfieldlists,
13637                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13638                       * sizeof (struct fnfieldlist));
13639           if (fip->nfnfields == 0)
13640             make_cleanup (free_current_contents, &fip->fnfieldlists);
13641         }
13642       flp = &fip->fnfieldlists[fip->nfnfields];
13643       flp->name = fieldname;
13644       flp->length = 0;
13645       flp->head = NULL;
13646       i = fip->nfnfields++;
13647     }
13648
13649   /* Create a new member function field and chain it to the field list
13650      entry.  */
13651   new_fnfield = XNEW (struct nextfnfield);
13652   make_cleanup (xfree, new_fnfield);
13653   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13654   new_fnfield->next = flp->head;
13655   flp->head = new_fnfield;
13656   flp->length++;
13657
13658   /* Fill in the member function field info.  */
13659   fnp = &new_fnfield->fnfield;
13660
13661   /* Delay processing of the physname until later.  */
13662   if (cu->language == language_cplus)
13663     {
13664       add_to_method_list (type, i, flp->length - 1, fieldname,
13665                           die, cu);
13666     }
13667   else
13668     {
13669       const char *physname = dwarf2_physname (fieldname, die, cu);
13670       fnp->physname = physname ? physname : "";
13671     }
13672
13673   fnp->type = alloc_type (objfile);
13674   this_type = read_type_die (die, cu);
13675   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13676     {
13677       int nparams = TYPE_NFIELDS (this_type);
13678
13679       /* TYPE is the domain of this method, and THIS_TYPE is the type
13680            of the method itself (TYPE_CODE_METHOD).  */
13681       smash_to_method_type (fnp->type, type,
13682                             TYPE_TARGET_TYPE (this_type),
13683                             TYPE_FIELDS (this_type),
13684                             TYPE_NFIELDS (this_type),
13685                             TYPE_VARARGS (this_type));
13686
13687       /* Handle static member functions.
13688          Dwarf2 has no clean way to discern C++ static and non-static
13689          member functions.  G++ helps GDB by marking the first
13690          parameter for non-static member functions (which is the this
13691          pointer) as artificial.  We obtain this information from
13692          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13693       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13694         fnp->voffset = VOFFSET_STATIC;
13695     }
13696   else
13697     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13698                dwarf2_full_name (fieldname, die, cu));
13699
13700   /* Get fcontext from DW_AT_containing_type if present.  */
13701   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13702     fnp->fcontext = die_containing_type (die, cu);
13703
13704   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13705      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13706
13707   /* Get accessibility.  */
13708   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13709   if (attr)
13710     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13711   else
13712     accessibility = dwarf2_default_access_attribute (die, cu);
13713   switch (accessibility)
13714     {
13715     case DW_ACCESS_private:
13716       fnp->is_private = 1;
13717       break;
13718     case DW_ACCESS_protected:
13719       fnp->is_protected = 1;
13720       break;
13721     }
13722
13723   /* Check for artificial methods.  */
13724   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13725   if (attr && DW_UNSND (attr) != 0)
13726     fnp->is_artificial = 1;
13727
13728   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13729
13730   /* Get index in virtual function table if it is a virtual member
13731      function.  For older versions of GCC, this is an offset in the
13732      appropriate virtual table, as specified by DW_AT_containing_type.
13733      For everyone else, it is an expression to be evaluated relative
13734      to the object address.  */
13735
13736   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13737   if (attr)
13738     {
13739       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13740         {
13741           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13742             {
13743               /* Old-style GCC.  */
13744               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13745             }
13746           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13747                    || (DW_BLOCK (attr)->size > 1
13748                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13749                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13750             {
13751               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13752               if ((fnp->voffset % cu->header.addr_size) != 0)
13753                 dwarf2_complex_location_expr_complaint ();
13754               else
13755                 fnp->voffset /= cu->header.addr_size;
13756               fnp->voffset += 2;
13757             }
13758           else
13759             dwarf2_complex_location_expr_complaint ();
13760
13761           if (!fnp->fcontext)
13762             {
13763               /* If there is no `this' field and no DW_AT_containing_type,
13764                  we cannot actually find a base class context for the
13765                  vtable!  */
13766               if (TYPE_NFIELDS (this_type) == 0
13767                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13768                 {
13769                   complaint (&symfile_complaints,
13770                              _("cannot determine context for virtual member "
13771                                "function \"%s\" (offset %d)"),
13772                              fieldname, to_underlying (die->sect_off));
13773                 }
13774               else
13775                 {
13776                   fnp->fcontext
13777                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13778                 }
13779             }
13780         }
13781       else if (attr_form_is_section_offset (attr))
13782         {
13783           dwarf2_complex_location_expr_complaint ();
13784         }
13785       else
13786         {
13787           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13788                                                  fieldname);
13789         }
13790     }
13791   else
13792     {
13793       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13794       if (attr && DW_UNSND (attr))
13795         {
13796           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13797           complaint (&symfile_complaints,
13798                      _("Member function \"%s\" (offset %d) is virtual "
13799                        "but the vtable offset is not specified"),
13800                      fieldname, to_underlying (die->sect_off));
13801           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13802           TYPE_CPLUS_DYNAMIC (type) = 1;
13803         }
13804     }
13805 }
13806
13807 /* Create the vector of member function fields, and attach it to the type.  */
13808
13809 static void
13810 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13811                                  struct dwarf2_cu *cu)
13812 {
13813   struct fnfieldlist *flp;
13814   int i;
13815
13816   if (cu->language == language_ada)
13817     error (_("unexpected member functions in Ada type"));
13818
13819   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13820   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13821     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13822
13823   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13824     {
13825       struct nextfnfield *nfp = flp->head;
13826       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13827       int k;
13828
13829       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13830       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13831       fn_flp->fn_fields = (struct fn_field *)
13832         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13833       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13834         fn_flp->fn_fields[k] = nfp->fnfield;
13835     }
13836
13837   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13838 }
13839
13840 /* Returns non-zero if NAME is the name of a vtable member in CU's
13841    language, zero otherwise.  */
13842 static int
13843 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13844 {
13845   static const char vptr[] = "_vptr";
13846   static const char vtable[] = "vtable";
13847
13848   /* Look for the C++ form of the vtable.  */
13849   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13850     return 1;
13851
13852   return 0;
13853 }
13854
13855 /* GCC outputs unnamed structures that are really pointers to member
13856    functions, with the ABI-specified layout.  If TYPE describes
13857    such a structure, smash it into a member function type.
13858
13859    GCC shouldn't do this; it should just output pointer to member DIEs.
13860    This is GCC PR debug/28767.  */
13861
13862 static void
13863 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13864 {
13865   struct type *pfn_type, *self_type, *new_type;
13866
13867   /* Check for a structure with no name and two children.  */
13868   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13869     return;
13870
13871   /* Check for __pfn and __delta members.  */
13872   if (TYPE_FIELD_NAME (type, 0) == NULL
13873       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13874       || TYPE_FIELD_NAME (type, 1) == NULL
13875       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13876     return;
13877
13878   /* Find the type of the method.  */
13879   pfn_type = TYPE_FIELD_TYPE (type, 0);
13880   if (pfn_type == NULL
13881       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13882       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13883     return;
13884
13885   /* Look for the "this" argument.  */
13886   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13887   if (TYPE_NFIELDS (pfn_type) == 0
13888       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13889       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13890     return;
13891
13892   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13893   new_type = alloc_type (objfile);
13894   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13895                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13896                         TYPE_VARARGS (pfn_type));
13897   smash_to_methodptr_type (type, new_type);
13898 }
13899
13900
13901 /* Called when we find the DIE that starts a structure or union scope
13902    (definition) to create a type for the structure or union.  Fill in
13903    the type's name and general properties; the members will not be
13904    processed until process_structure_scope.  A symbol table entry for
13905    the type will also not be done until process_structure_scope (assuming
13906    the type has a name).
13907
13908    NOTE: we need to call these functions regardless of whether or not the
13909    DIE has a DW_AT_name attribute, since it might be an anonymous
13910    structure or union.  This gets the type entered into our set of
13911    user defined types.  */
13912
13913 static struct type *
13914 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13915 {
13916   struct objfile *objfile = cu->objfile;
13917   struct type *type;
13918   struct attribute *attr;
13919   const char *name;
13920
13921   /* If the definition of this type lives in .debug_types, read that type.
13922      Don't follow DW_AT_specification though, that will take us back up
13923      the chain and we want to go down.  */
13924   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13925   if (attr)
13926     {
13927       type = get_DW_AT_signature_type (die, attr, cu);
13928
13929       /* The type's CU may not be the same as CU.
13930          Ensure TYPE is recorded with CU in die_type_hash.  */
13931       return set_die_type (die, type, cu);
13932     }
13933
13934   type = alloc_type (objfile);
13935   INIT_CPLUS_SPECIFIC (type);
13936
13937   name = dwarf2_name (die, cu);
13938   if (name != NULL)
13939     {
13940       if (cu->language == language_cplus
13941           || cu->language == language_d
13942           || cu->language == language_rust)
13943         {
13944           const char *full_name = dwarf2_full_name (name, die, cu);
13945
13946           /* dwarf2_full_name might have already finished building the DIE's
13947              type.  If so, there is no need to continue.  */
13948           if (get_die_type (die, cu) != NULL)
13949             return get_die_type (die, cu);
13950
13951           TYPE_TAG_NAME (type) = full_name;
13952           if (die->tag == DW_TAG_structure_type
13953               || die->tag == DW_TAG_class_type)
13954             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13955         }
13956       else
13957         {
13958           /* The name is already allocated along with this objfile, so
13959              we don't need to duplicate it for the type.  */
13960           TYPE_TAG_NAME (type) = name;
13961           if (die->tag == DW_TAG_class_type)
13962             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13963         }
13964     }
13965
13966   if (die->tag == DW_TAG_structure_type)
13967     {
13968       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13969     }
13970   else if (die->tag == DW_TAG_union_type)
13971     {
13972       TYPE_CODE (type) = TYPE_CODE_UNION;
13973     }
13974   else
13975     {
13976       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13977     }
13978
13979   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13980     TYPE_DECLARED_CLASS (type) = 1;
13981
13982   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13983   if (attr)
13984     {
13985       if (attr_form_is_constant (attr))
13986         TYPE_LENGTH (type) = DW_UNSND (attr);
13987       else
13988         {
13989           /* For the moment, dynamic type sizes are not supported
13990              by GDB's struct type.  The actual size is determined
13991              on-demand when resolving the type of a given object,
13992              so set the type's length to zero for now.  Otherwise,
13993              we record an expression as the length, and that expression
13994              could lead to a very large value, which could eventually
13995              lead to us trying to allocate that much memory when creating
13996              a value of that type.  */
13997           TYPE_LENGTH (type) = 0;
13998         }
13999     }
14000   else
14001     {
14002       TYPE_LENGTH (type) = 0;
14003     }
14004
14005   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
14006     {
14007       /* ICC<14 does not output the required DW_AT_declaration on
14008          incomplete types, but gives them a size of zero.  */
14009       TYPE_STUB (type) = 1;
14010     }
14011   else
14012     TYPE_STUB_SUPPORTED (type) = 1;
14013
14014   if (die_is_declaration (die, cu))
14015     TYPE_STUB (type) = 1;
14016   else if (attr == NULL && die->child == NULL
14017            && producer_is_realview (cu->producer))
14018     /* RealView does not output the required DW_AT_declaration
14019        on incomplete types.  */
14020     TYPE_STUB (type) = 1;
14021
14022   /* We need to add the type field to the die immediately so we don't
14023      infinitely recurse when dealing with pointers to the structure
14024      type within the structure itself.  */
14025   set_die_type (die, type, cu);
14026
14027   /* set_die_type should be already done.  */
14028   set_descriptive_type (type, die, cu);
14029
14030   return type;
14031 }
14032
14033 /* Finish creating a structure or union type, including filling in
14034    its members and creating a symbol for it.  */
14035
14036 static void
14037 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14038 {
14039   struct objfile *objfile = cu->objfile;
14040   struct die_info *child_die;
14041   struct type *type;
14042
14043   type = get_die_type (die, cu);
14044   if (type == NULL)
14045     type = read_structure_type (die, cu);
14046
14047   if (die->child != NULL && ! die_is_declaration (die, cu))
14048     {
14049       struct field_info fi;
14050       VEC (symbolp) *template_args = NULL;
14051       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14052
14053       memset (&fi, 0, sizeof (struct field_info));
14054
14055       child_die = die->child;
14056
14057       while (child_die && child_die->tag)
14058         {
14059           if (child_die->tag == DW_TAG_member
14060               || child_die->tag == DW_TAG_variable)
14061             {
14062               /* NOTE: carlton/2002-11-05: A C++ static data member
14063                  should be a DW_TAG_member that is a declaration, but
14064                  all versions of G++ as of this writing (so through at
14065                  least 3.2.1) incorrectly generate DW_TAG_variable
14066                  tags for them instead.  */
14067               dwarf2_add_field (&fi, child_die, cu);
14068             }
14069           else if (child_die->tag == DW_TAG_subprogram)
14070             {
14071               /* Rust doesn't have member functions in the C++ sense.
14072                  However, it does emit ordinary functions as children
14073                  of a struct DIE.  */
14074               if (cu->language == language_rust)
14075                 read_func_scope (child_die, cu);
14076               else
14077                 {
14078                   /* C++ member function.  */
14079                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14080                 }
14081             }
14082           else if (child_die->tag == DW_TAG_inheritance)
14083             {
14084               /* C++ base class field.  */
14085               dwarf2_add_field (&fi, child_die, cu);
14086             }
14087           else if (child_die->tag == DW_TAG_typedef)
14088             dwarf2_add_typedef (&fi, child_die, cu);
14089           else if (child_die->tag == DW_TAG_template_type_param
14090                    || child_die->tag == DW_TAG_template_value_param)
14091             {
14092               struct symbol *arg = new_symbol (child_die, NULL, cu);
14093
14094               if (arg != NULL)
14095                 VEC_safe_push (symbolp, template_args, arg);
14096             }
14097
14098           child_die = sibling_die (child_die);
14099         }
14100
14101       /* Attach template arguments to type.  */
14102       if (! VEC_empty (symbolp, template_args))
14103         {
14104           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14105           TYPE_N_TEMPLATE_ARGUMENTS (type)
14106             = VEC_length (symbolp, template_args);
14107           TYPE_TEMPLATE_ARGUMENTS (type)
14108             = XOBNEWVEC (&objfile->objfile_obstack,
14109                          struct symbol *,
14110                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14111           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14112                   VEC_address (symbolp, template_args),
14113                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14114                    * sizeof (struct symbol *)));
14115           VEC_free (symbolp, template_args);
14116         }
14117
14118       /* Attach fields and member functions to the type.  */
14119       if (fi.nfields)
14120         dwarf2_attach_fields_to_type (&fi, type, cu);
14121       if (fi.nfnfields)
14122         {
14123           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14124
14125           /* Get the type which refers to the base class (possibly this
14126              class itself) which contains the vtable pointer for the current
14127              class from the DW_AT_containing_type attribute.  This use of
14128              DW_AT_containing_type is a GNU extension.  */
14129
14130           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14131             {
14132               struct type *t = die_containing_type (die, cu);
14133
14134               set_type_vptr_basetype (type, t);
14135               if (type == t)
14136                 {
14137                   int i;
14138
14139                   /* Our own class provides vtbl ptr.  */
14140                   for (i = TYPE_NFIELDS (t) - 1;
14141                        i >= TYPE_N_BASECLASSES (t);
14142                        --i)
14143                     {
14144                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14145
14146                       if (is_vtable_name (fieldname, cu))
14147                         {
14148                           set_type_vptr_fieldno (type, i);
14149                           break;
14150                         }
14151                     }
14152
14153                   /* Complain if virtual function table field not found.  */
14154                   if (i < TYPE_N_BASECLASSES (t))
14155                     complaint (&symfile_complaints,
14156                                _("virtual function table pointer "
14157                                  "not found when defining class '%s'"),
14158                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14159                                "");
14160                 }
14161               else
14162                 {
14163                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14164                 }
14165             }
14166           else if (cu->producer
14167                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14168             {
14169               /* The IBM XLC compiler does not provide direct indication
14170                  of the containing type, but the vtable pointer is
14171                  always named __vfp.  */
14172
14173               int i;
14174
14175               for (i = TYPE_NFIELDS (type) - 1;
14176                    i >= TYPE_N_BASECLASSES (type);
14177                    --i)
14178                 {
14179                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14180                     {
14181                       set_type_vptr_fieldno (type, i);
14182                       set_type_vptr_basetype (type, type);
14183                       break;
14184                     }
14185                 }
14186             }
14187         }
14188
14189       /* Copy fi.typedef_field_list linked list elements content into the
14190          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14191       if (fi.typedef_field_list)
14192         {
14193           int i = fi.typedef_field_list_count;
14194
14195           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14196           TYPE_TYPEDEF_FIELD_ARRAY (type)
14197             = ((struct typedef_field *)
14198                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14199           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14200
14201           /* Reverse the list order to keep the debug info elements order.  */
14202           while (--i >= 0)
14203             {
14204               struct typedef_field *dest, *src;
14205
14206               dest = &TYPE_TYPEDEF_FIELD (type, i);
14207               src = &fi.typedef_field_list->field;
14208               fi.typedef_field_list = fi.typedef_field_list->next;
14209               *dest = *src;
14210             }
14211         }
14212
14213       do_cleanups (back_to);
14214     }
14215
14216   quirk_gcc_member_function_pointer (type, objfile);
14217
14218   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14219      snapshots) has been known to create a die giving a declaration
14220      for a class that has, as a child, a die giving a definition for a
14221      nested class.  So we have to process our children even if the
14222      current die is a declaration.  Normally, of course, a declaration
14223      won't have any children at all.  */
14224
14225   child_die = die->child;
14226
14227   while (child_die != NULL && child_die->tag)
14228     {
14229       if (child_die->tag == DW_TAG_member
14230           || child_die->tag == DW_TAG_variable
14231           || child_die->tag == DW_TAG_inheritance
14232           || child_die->tag == DW_TAG_template_value_param
14233           || child_die->tag == DW_TAG_template_type_param)
14234         {
14235           /* Do nothing.  */
14236         }
14237       else
14238         process_die (child_die, cu);
14239
14240       child_die = sibling_die (child_die);
14241     }
14242
14243   /* Do not consider external references.  According to the DWARF standard,
14244      these DIEs are identified by the fact that they have no byte_size
14245      attribute, and a declaration attribute.  */
14246   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14247       || !die_is_declaration (die, cu))
14248     new_symbol (die, type, cu);
14249 }
14250
14251 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14252    update TYPE using some information only available in DIE's children.  */
14253
14254 static void
14255 update_enumeration_type_from_children (struct die_info *die,
14256                                        struct type *type,
14257                                        struct dwarf2_cu *cu)
14258 {
14259   struct die_info *child_die;
14260   int unsigned_enum = 1;
14261   int flag_enum = 1;
14262   ULONGEST mask = 0;
14263
14264   auto_obstack obstack;
14265
14266   for (child_die = die->child;
14267        child_die != NULL && child_die->tag;
14268        child_die = sibling_die (child_die))
14269     {
14270       struct attribute *attr;
14271       LONGEST value;
14272       const gdb_byte *bytes;
14273       struct dwarf2_locexpr_baton *baton;
14274       const char *name;
14275
14276       if (child_die->tag != DW_TAG_enumerator)
14277         continue;
14278
14279       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14280       if (attr == NULL)
14281         continue;
14282
14283       name = dwarf2_name (child_die, cu);
14284       if (name == NULL)
14285         name = "<anonymous enumerator>";
14286
14287       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14288                                &value, &bytes, &baton);
14289       if (value < 0)
14290         {
14291           unsigned_enum = 0;
14292           flag_enum = 0;
14293         }
14294       else if ((mask & value) != 0)
14295         flag_enum = 0;
14296       else
14297         mask |= value;
14298
14299       /* If we already know that the enum type is neither unsigned, nor
14300          a flag type, no need to look at the rest of the enumerates.  */
14301       if (!unsigned_enum && !flag_enum)
14302         break;
14303     }
14304
14305   if (unsigned_enum)
14306     TYPE_UNSIGNED (type) = 1;
14307   if (flag_enum)
14308     TYPE_FLAG_ENUM (type) = 1;
14309 }
14310
14311 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14312    complete the type's fields yet, or create any symbols.  */
14313
14314 static struct type *
14315 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14316 {
14317   struct objfile *objfile = cu->objfile;
14318   struct type *type;
14319   struct attribute *attr;
14320   const char *name;
14321
14322   /* If the definition of this type lives in .debug_types, read that type.
14323      Don't follow DW_AT_specification though, that will take us back up
14324      the chain and we want to go down.  */
14325   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14326   if (attr)
14327     {
14328       type = get_DW_AT_signature_type (die, attr, cu);
14329
14330       /* The type's CU may not be the same as CU.
14331          Ensure TYPE is recorded with CU in die_type_hash.  */
14332       return set_die_type (die, type, cu);
14333     }
14334
14335   type = alloc_type (objfile);
14336
14337   TYPE_CODE (type) = TYPE_CODE_ENUM;
14338   name = dwarf2_full_name (NULL, die, cu);
14339   if (name != NULL)
14340     TYPE_TAG_NAME (type) = name;
14341
14342   attr = dwarf2_attr (die, DW_AT_type, cu);
14343   if (attr != NULL)
14344     {
14345       struct type *underlying_type = die_type (die, cu);
14346
14347       TYPE_TARGET_TYPE (type) = underlying_type;
14348     }
14349
14350   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14351   if (attr)
14352     {
14353       TYPE_LENGTH (type) = DW_UNSND (attr);
14354     }
14355   else
14356     {
14357       TYPE_LENGTH (type) = 0;
14358     }
14359
14360   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14361      declared as private in the package spec, and then defined only
14362      inside the package body.  Such types are known as Taft Amendment
14363      Types.  When another package uses such a type, an incomplete DIE
14364      may be generated by the compiler.  */
14365   if (die_is_declaration (die, cu))
14366     TYPE_STUB (type) = 1;
14367
14368   /* Finish the creation of this type by using the enum's children.
14369      We must call this even when the underlying type has been provided
14370      so that we can determine if we're looking at a "flag" enum.  */
14371   update_enumeration_type_from_children (die, type, cu);
14372
14373   /* If this type has an underlying type that is not a stub, then we
14374      may use its attributes.  We always use the "unsigned" attribute
14375      in this situation, because ordinarily we guess whether the type
14376      is unsigned -- but the guess can be wrong and the underlying type
14377      can tell us the reality.  However, we defer to a local size
14378      attribute if one exists, because this lets the compiler override
14379      the underlying type if needed.  */
14380   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14381     {
14382       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14383       if (TYPE_LENGTH (type) == 0)
14384         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14385     }
14386
14387   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14388
14389   return set_die_type (die, type, cu);
14390 }
14391
14392 /* Given a pointer to a die which begins an enumeration, process all
14393    the dies that define the members of the enumeration, and create the
14394    symbol for the enumeration type.
14395
14396    NOTE: We reverse the order of the element list.  */
14397
14398 static void
14399 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14400 {
14401   struct type *this_type;
14402
14403   this_type = get_die_type (die, cu);
14404   if (this_type == NULL)
14405     this_type = read_enumeration_type (die, cu);
14406
14407   if (die->child != NULL)
14408     {
14409       struct die_info *child_die;
14410       struct symbol *sym;
14411       struct field *fields = NULL;
14412       int num_fields = 0;
14413       const char *name;
14414
14415       child_die = die->child;
14416       while (child_die && child_die->tag)
14417         {
14418           if (child_die->tag != DW_TAG_enumerator)
14419             {
14420               process_die (child_die, cu);
14421             }
14422           else
14423             {
14424               name = dwarf2_name (child_die, cu);
14425               if (name)
14426                 {
14427                   sym = new_symbol (child_die, this_type, cu);
14428
14429                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14430                     {
14431                       fields = (struct field *)
14432                         xrealloc (fields,
14433                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14434                                   * sizeof (struct field));
14435                     }
14436
14437                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14438                   FIELD_TYPE (fields[num_fields]) = NULL;
14439                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14440                   FIELD_BITSIZE (fields[num_fields]) = 0;
14441
14442                   num_fields++;
14443                 }
14444             }
14445
14446           child_die = sibling_die (child_die);
14447         }
14448
14449       if (num_fields)
14450         {
14451           TYPE_NFIELDS (this_type) = num_fields;
14452           TYPE_FIELDS (this_type) = (struct field *)
14453             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14454           memcpy (TYPE_FIELDS (this_type), fields,
14455                   sizeof (struct field) * num_fields);
14456           xfree (fields);
14457         }
14458     }
14459
14460   /* If we are reading an enum from a .debug_types unit, and the enum
14461      is a declaration, and the enum is not the signatured type in the
14462      unit, then we do not want to add a symbol for it.  Adding a
14463      symbol would in some cases obscure the true definition of the
14464      enum, giving users an incomplete type when the definition is
14465      actually available.  Note that we do not want to do this for all
14466      enums which are just declarations, because C++0x allows forward
14467      enum declarations.  */
14468   if (cu->per_cu->is_debug_types
14469       && die_is_declaration (die, cu))
14470     {
14471       struct signatured_type *sig_type;
14472
14473       sig_type = (struct signatured_type *) cu->per_cu;
14474       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14475       if (sig_type->type_offset_in_section != die->sect_off)
14476         return;
14477     }
14478
14479   new_symbol (die, this_type, cu);
14480 }
14481
14482 /* Extract all information from a DW_TAG_array_type DIE and put it in
14483    the DIE's type field.  For now, this only handles one dimensional
14484    arrays.  */
14485
14486 static struct type *
14487 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14488 {
14489   struct objfile *objfile = cu->objfile;
14490   struct die_info *child_die;
14491   struct type *type;
14492   struct type *element_type, *range_type, *index_type;
14493   struct attribute *attr;
14494   const char *name;
14495   unsigned int bit_stride = 0;
14496
14497   element_type = die_type (die, cu);
14498
14499   /* The die_type call above may have already set the type for this DIE.  */
14500   type = get_die_type (die, cu);
14501   if (type)
14502     return type;
14503
14504   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14505   if (attr != NULL)
14506     bit_stride = DW_UNSND (attr) * 8;
14507
14508   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14509   if (attr != NULL)
14510     bit_stride = DW_UNSND (attr);
14511
14512   /* Irix 6.2 native cc creates array types without children for
14513      arrays with unspecified length.  */
14514   if (die->child == NULL)
14515     {
14516       index_type = objfile_type (objfile)->builtin_int;
14517       range_type = create_static_range_type (NULL, index_type, 0, -1);
14518       type = create_array_type_with_stride (NULL, element_type, range_type,
14519                                             bit_stride);
14520       return set_die_type (die, type, cu);
14521     }
14522
14523   std::vector<struct type *> range_types;
14524   child_die = die->child;
14525   while (child_die && child_die->tag)
14526     {
14527       if (child_die->tag == DW_TAG_subrange_type)
14528         {
14529           struct type *child_type = read_type_die (child_die, cu);
14530
14531           if (child_type != NULL)
14532             {
14533               /* The range type was succesfully read.  Save it for the
14534                  array type creation.  */
14535               range_types.push_back (child_type);
14536             }
14537         }
14538       child_die = sibling_die (child_die);
14539     }
14540
14541   /* Dwarf2 dimensions are output from left to right, create the
14542      necessary array types in backwards order.  */
14543
14544   type = element_type;
14545
14546   if (read_array_order (die, cu) == DW_ORD_col_major)
14547     {
14548       int i = 0;
14549
14550       while (i < range_types.size ())
14551         type = create_array_type_with_stride (NULL, type, range_types[i++],
14552                                               bit_stride);
14553     }
14554   else
14555     {
14556       size_t ndim = range_types.size ();
14557       while (ndim-- > 0)
14558         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14559                                               bit_stride);
14560     }
14561
14562   /* Understand Dwarf2 support for vector types (like they occur on
14563      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14564      array type.  This is not part of the Dwarf2/3 standard yet, but a
14565      custom vendor extension.  The main difference between a regular
14566      array and the vector variant is that vectors are passed by value
14567      to functions.  */
14568   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14569   if (attr)
14570     make_vector_type (type);
14571
14572   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14573      implementation may choose to implement triple vectors using this
14574      attribute.  */
14575   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14576   if (attr)
14577     {
14578       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14579         TYPE_LENGTH (type) = DW_UNSND (attr);
14580       else
14581         complaint (&symfile_complaints,
14582                    _("DW_AT_byte_size for array type smaller "
14583                      "than the total size of elements"));
14584     }
14585
14586   name = dwarf2_name (die, cu);
14587   if (name)
14588     TYPE_NAME (type) = name;
14589
14590   /* Install the type in the die.  */
14591   set_die_type (die, type, cu);
14592
14593   /* set_die_type should be already done.  */
14594   set_descriptive_type (type, die, cu);
14595
14596   return type;
14597 }
14598
14599 static enum dwarf_array_dim_ordering
14600 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14601 {
14602   struct attribute *attr;
14603
14604   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14605
14606   if (attr)
14607     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14608
14609   /* GNU F77 is a special case, as at 08/2004 array type info is the
14610      opposite order to the dwarf2 specification, but data is still
14611      laid out as per normal fortran.
14612
14613      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14614      version checking.  */
14615
14616   if (cu->language == language_fortran
14617       && cu->producer && strstr (cu->producer, "GNU F77"))
14618     {
14619       return DW_ORD_row_major;
14620     }
14621
14622   switch (cu->language_defn->la_array_ordering)
14623     {
14624     case array_column_major:
14625       return DW_ORD_col_major;
14626     case array_row_major:
14627     default:
14628       return DW_ORD_row_major;
14629     };
14630 }
14631
14632 /* Extract all information from a DW_TAG_set_type DIE and put it in
14633    the DIE's type field.  */
14634
14635 static struct type *
14636 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14637 {
14638   struct type *domain_type, *set_type;
14639   struct attribute *attr;
14640
14641   domain_type = die_type (die, cu);
14642
14643   /* The die_type call above may have already set the type for this DIE.  */
14644   set_type = get_die_type (die, cu);
14645   if (set_type)
14646     return set_type;
14647
14648   set_type = create_set_type (NULL, domain_type);
14649
14650   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14651   if (attr)
14652     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14653
14654   return set_die_type (die, set_type, cu);
14655 }
14656
14657 /* A helper for read_common_block that creates a locexpr baton.
14658    SYM is the symbol which we are marking as computed.
14659    COMMON_DIE is the DIE for the common block.
14660    COMMON_LOC is the location expression attribute for the common
14661    block itself.
14662    MEMBER_LOC is the location expression attribute for the particular
14663    member of the common block that we are processing.
14664    CU is the CU from which the above come.  */
14665
14666 static void
14667 mark_common_block_symbol_computed (struct symbol *sym,
14668                                    struct die_info *common_die,
14669                                    struct attribute *common_loc,
14670                                    struct attribute *member_loc,
14671                                    struct dwarf2_cu *cu)
14672 {
14673   struct objfile *objfile = dwarf2_per_objfile->objfile;
14674   struct dwarf2_locexpr_baton *baton;
14675   gdb_byte *ptr;
14676   unsigned int cu_off;
14677   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14678   LONGEST offset = 0;
14679
14680   gdb_assert (common_loc && member_loc);
14681   gdb_assert (attr_form_is_block (common_loc));
14682   gdb_assert (attr_form_is_block (member_loc)
14683               || attr_form_is_constant (member_loc));
14684
14685   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14686   baton->per_cu = cu->per_cu;
14687   gdb_assert (baton->per_cu);
14688
14689   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14690
14691   if (attr_form_is_constant (member_loc))
14692     {
14693       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14694       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14695     }
14696   else
14697     baton->size += DW_BLOCK (member_loc)->size;
14698
14699   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14700   baton->data = ptr;
14701
14702   *ptr++ = DW_OP_call4;
14703   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14704   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14705   ptr += 4;
14706
14707   if (attr_form_is_constant (member_loc))
14708     {
14709       *ptr++ = DW_OP_addr;
14710       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14711       ptr += cu->header.addr_size;
14712     }
14713   else
14714     {
14715       /* We have to copy the data here, because DW_OP_call4 will only
14716          use a DW_AT_location attribute.  */
14717       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14718       ptr += DW_BLOCK (member_loc)->size;
14719     }
14720
14721   *ptr++ = DW_OP_plus;
14722   gdb_assert (ptr - baton->data == baton->size);
14723
14724   SYMBOL_LOCATION_BATON (sym) = baton;
14725   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14726 }
14727
14728 /* Create appropriate locally-scoped variables for all the
14729    DW_TAG_common_block entries.  Also create a struct common_block
14730    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14731    is used to sepate the common blocks name namespace from regular
14732    variable names.  */
14733
14734 static void
14735 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14736 {
14737   struct attribute *attr;
14738
14739   attr = dwarf2_attr (die, DW_AT_location, cu);
14740   if (attr)
14741     {
14742       /* Support the .debug_loc offsets.  */
14743       if (attr_form_is_block (attr))
14744         {
14745           /* Ok.  */
14746         }
14747       else if (attr_form_is_section_offset (attr))
14748         {
14749           dwarf2_complex_location_expr_complaint ();
14750           attr = NULL;
14751         }
14752       else
14753         {
14754           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14755                                                  "common block member");
14756           attr = NULL;
14757         }
14758     }
14759
14760   if (die->child != NULL)
14761     {
14762       struct objfile *objfile = cu->objfile;
14763       struct die_info *child_die;
14764       size_t n_entries = 0, size;
14765       struct common_block *common_block;
14766       struct symbol *sym;
14767
14768       for (child_die = die->child;
14769            child_die && child_die->tag;
14770            child_die = sibling_die (child_die))
14771         ++n_entries;
14772
14773       size = (sizeof (struct common_block)
14774               + (n_entries - 1) * sizeof (struct symbol *));
14775       common_block
14776         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14777                                                  size);
14778       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14779       common_block->n_entries = 0;
14780
14781       for (child_die = die->child;
14782            child_die && child_die->tag;
14783            child_die = sibling_die (child_die))
14784         {
14785           /* Create the symbol in the DW_TAG_common_block block in the current
14786              symbol scope.  */
14787           sym = new_symbol (child_die, NULL, cu);
14788           if (sym != NULL)
14789             {
14790               struct attribute *member_loc;
14791
14792               common_block->contents[common_block->n_entries++] = sym;
14793
14794               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14795                                         cu);
14796               if (member_loc)
14797                 {
14798                   /* GDB has handled this for a long time, but it is
14799                      not specified by DWARF.  It seems to have been
14800                      emitted by gfortran at least as recently as:
14801                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14802                   complaint (&symfile_complaints,
14803                              _("Variable in common block has "
14804                                "DW_AT_data_member_location "
14805                                "- DIE at 0x%x [in module %s]"),
14806                              to_underlying (child_die->sect_off),
14807                              objfile_name (cu->objfile));
14808
14809                   if (attr_form_is_section_offset (member_loc))
14810                     dwarf2_complex_location_expr_complaint ();
14811                   else if (attr_form_is_constant (member_loc)
14812                            || attr_form_is_block (member_loc))
14813                     {
14814                       if (attr)
14815                         mark_common_block_symbol_computed (sym, die, attr,
14816                                                            member_loc, cu);
14817                     }
14818                   else
14819                     dwarf2_complex_location_expr_complaint ();
14820                 }
14821             }
14822         }
14823
14824       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14825       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14826     }
14827 }
14828
14829 /* Create a type for a C++ namespace.  */
14830
14831 static struct type *
14832 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14833 {
14834   struct objfile *objfile = cu->objfile;
14835   const char *previous_prefix, *name;
14836   int is_anonymous;
14837   struct type *type;
14838
14839   /* For extensions, reuse the type of the original namespace.  */
14840   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14841     {
14842       struct die_info *ext_die;
14843       struct dwarf2_cu *ext_cu = cu;
14844
14845       ext_die = dwarf2_extension (die, &ext_cu);
14846       type = read_type_die (ext_die, ext_cu);
14847
14848       /* EXT_CU may not be the same as CU.
14849          Ensure TYPE is recorded with CU in die_type_hash.  */
14850       return set_die_type (die, type, cu);
14851     }
14852
14853   name = namespace_name (die, &is_anonymous, cu);
14854
14855   /* Now build the name of the current namespace.  */
14856
14857   previous_prefix = determine_prefix (die, cu);
14858   if (previous_prefix[0] != '\0')
14859     name = typename_concat (&objfile->objfile_obstack,
14860                             previous_prefix, name, 0, cu);
14861
14862   /* Create the type.  */
14863   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14864   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14865
14866   return set_die_type (die, type, cu);
14867 }
14868
14869 /* Read a namespace scope.  */
14870
14871 static void
14872 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14873 {
14874   struct objfile *objfile = cu->objfile;
14875   int is_anonymous;
14876
14877   /* Add a symbol associated to this if we haven't seen the namespace
14878      before.  Also, add a using directive if it's an anonymous
14879      namespace.  */
14880
14881   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14882     {
14883       struct type *type;
14884
14885       type = read_type_die (die, cu);
14886       new_symbol (die, type, cu);
14887
14888       namespace_name (die, &is_anonymous, cu);
14889       if (is_anonymous)
14890         {
14891           const char *previous_prefix = determine_prefix (die, cu);
14892
14893           std::vector<const char *> excludes;
14894           add_using_directive (using_directives (cu->language),
14895                                previous_prefix, TYPE_NAME (type), NULL,
14896                                NULL, excludes, 0, &objfile->objfile_obstack);
14897         }
14898     }
14899
14900   if (die->child != NULL)
14901     {
14902       struct die_info *child_die = die->child;
14903
14904       while (child_die && child_die->tag)
14905         {
14906           process_die (child_die, cu);
14907           child_die = sibling_die (child_die);
14908         }
14909     }
14910 }
14911
14912 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14913    imported module.  Still we need that type as local Fortran "use ... only"
14914    declaration imports depend on the created type in determine_prefix.  */
14915
14916 static struct type *
14917 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14918 {
14919   struct objfile *objfile = cu->objfile;
14920   const char *module_name;
14921   struct type *type;
14922
14923   module_name = dwarf2_name (die, cu);
14924   if (!module_name)
14925     complaint (&symfile_complaints,
14926                _("DW_TAG_module has no name, offset 0x%x"),
14927                to_underlying (die->sect_off));
14928   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14929
14930   /* determine_prefix uses TYPE_TAG_NAME.  */
14931   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14932
14933   return set_die_type (die, type, cu);
14934 }
14935
14936 /* Read a Fortran module.  */
14937
14938 static void
14939 read_module (struct die_info *die, struct dwarf2_cu *cu)
14940 {
14941   struct die_info *child_die = die->child;
14942   struct type *type;
14943
14944   type = read_type_die (die, cu);
14945   new_symbol (die, type, cu);
14946
14947   while (child_die && child_die->tag)
14948     {
14949       process_die (child_die, cu);
14950       child_die = sibling_die (child_die);
14951     }
14952 }
14953
14954 /* Return the name of the namespace represented by DIE.  Set
14955    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14956    namespace.  */
14957
14958 static const char *
14959 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14960 {
14961   struct die_info *current_die;
14962   const char *name = NULL;
14963
14964   /* Loop through the extensions until we find a name.  */
14965
14966   for (current_die = die;
14967        current_die != NULL;
14968        current_die = dwarf2_extension (die, &cu))
14969     {
14970       /* We don't use dwarf2_name here so that we can detect the absence
14971          of a name -> anonymous namespace.  */
14972       name = dwarf2_string_attr (die, DW_AT_name, cu);
14973
14974       if (name != NULL)
14975         break;
14976     }
14977
14978   /* Is it an anonymous namespace?  */
14979
14980   *is_anonymous = (name == NULL);
14981   if (*is_anonymous)
14982     name = CP_ANONYMOUS_NAMESPACE_STR;
14983
14984   return name;
14985 }
14986
14987 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14988    the user defined type vector.  */
14989
14990 static struct type *
14991 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14992 {
14993   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14994   struct comp_unit_head *cu_header = &cu->header;
14995   struct type *type;
14996   struct attribute *attr_byte_size;
14997   struct attribute *attr_address_class;
14998   int byte_size, addr_class;
14999   struct type *target_type;
15000
15001   target_type = die_type (die, cu);
15002
15003   /* The die_type call above may have already set the type for this DIE.  */
15004   type = get_die_type (die, cu);
15005   if (type)
15006     return type;
15007
15008   type = lookup_pointer_type (target_type);
15009
15010   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
15011   if (attr_byte_size)
15012     byte_size = DW_UNSND (attr_byte_size);
15013   else
15014     byte_size = cu_header->addr_size;
15015
15016   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
15017   if (attr_address_class)
15018     addr_class = DW_UNSND (attr_address_class);
15019   else
15020     addr_class = DW_ADDR_none;
15021
15022   /* If the pointer size or address class is different than the
15023      default, create a type variant marked as such and set the
15024      length accordingly.  */
15025   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15026     {
15027       if (gdbarch_address_class_type_flags_p (gdbarch))
15028         {
15029           int type_flags;
15030
15031           type_flags = gdbarch_address_class_type_flags
15032                          (gdbarch, byte_size, addr_class);
15033           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15034                       == 0);
15035           type = make_type_with_address_space (type, type_flags);
15036         }
15037       else if (TYPE_LENGTH (type) != byte_size)
15038         {
15039           complaint (&symfile_complaints,
15040                      _("invalid pointer size %d"), byte_size);
15041         }
15042       else
15043         {
15044           /* Should we also complain about unhandled address classes?  */
15045         }
15046     }
15047
15048   TYPE_LENGTH (type) = byte_size;
15049   return set_die_type (die, type, cu);
15050 }
15051
15052 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15053    the user defined type vector.  */
15054
15055 static struct type *
15056 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15057 {
15058   struct type *type;
15059   struct type *to_type;
15060   struct type *domain;
15061
15062   to_type = die_type (die, cu);
15063   domain = die_containing_type (die, cu);
15064
15065   /* The calls above may have already set the type for this DIE.  */
15066   type = get_die_type (die, cu);
15067   if (type)
15068     return type;
15069
15070   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15071     type = lookup_methodptr_type (to_type);
15072   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15073     {
15074       struct type *new_type = alloc_type (cu->objfile);
15075
15076       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15077                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15078                             TYPE_VARARGS (to_type));
15079       type = lookup_methodptr_type (new_type);
15080     }
15081   else
15082     type = lookup_memberptr_type (to_type, domain);
15083
15084   return set_die_type (die, type, cu);
15085 }
15086
15087 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15088    the user defined type vector.  */
15089
15090 static struct type *
15091 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15092                           enum type_code refcode)
15093 {
15094   struct comp_unit_head *cu_header = &cu->header;
15095   struct type *type, *target_type;
15096   struct attribute *attr;
15097
15098   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15099
15100   target_type = die_type (die, cu);
15101
15102   /* The die_type call above may have already set the type for this DIE.  */
15103   type = get_die_type (die, cu);
15104   if (type)
15105     return type;
15106
15107   type = lookup_reference_type (target_type, refcode);
15108   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15109   if (attr)
15110     {
15111       TYPE_LENGTH (type) = DW_UNSND (attr);
15112     }
15113   else
15114     {
15115       TYPE_LENGTH (type) = cu_header->addr_size;
15116     }
15117   return set_die_type (die, type, cu);
15118 }
15119
15120 /* Add the given cv-qualifiers to the element type of the array.  GCC
15121    outputs DWARF type qualifiers that apply to an array, not the
15122    element type.  But GDB relies on the array element type to carry
15123    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15124    specification.  */
15125
15126 static struct type *
15127 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15128                    struct type *base_type, int cnst, int voltl)
15129 {
15130   struct type *el_type, *inner_array;
15131
15132   base_type = copy_type (base_type);
15133   inner_array = base_type;
15134
15135   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15136     {
15137       TYPE_TARGET_TYPE (inner_array) =
15138         copy_type (TYPE_TARGET_TYPE (inner_array));
15139       inner_array = TYPE_TARGET_TYPE (inner_array);
15140     }
15141
15142   el_type = TYPE_TARGET_TYPE (inner_array);
15143   cnst |= TYPE_CONST (el_type);
15144   voltl |= TYPE_VOLATILE (el_type);
15145   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15146
15147   return set_die_type (die, base_type, cu);
15148 }
15149
15150 static struct type *
15151 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15152 {
15153   struct type *base_type, *cv_type;
15154
15155   base_type = die_type (die, cu);
15156
15157   /* The die_type call above may have already set the type for this DIE.  */
15158   cv_type = get_die_type (die, cu);
15159   if (cv_type)
15160     return cv_type;
15161
15162   /* In case the const qualifier is applied to an array type, the element type
15163      is so qualified, not the array type (section 6.7.3 of C99).  */
15164   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15165     return add_array_cv_type (die, cu, base_type, 1, 0);
15166
15167   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15168   return set_die_type (die, cv_type, cu);
15169 }
15170
15171 static struct type *
15172 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
15173 {
15174   struct type *base_type, *cv_type;
15175
15176   base_type = die_type (die, cu);
15177
15178   /* The die_type call above may have already set the type for this DIE.  */
15179   cv_type = get_die_type (die, cu);
15180   if (cv_type)
15181     return cv_type;
15182
15183   /* In case the volatile qualifier is applied to an array type, the
15184      element type is so qualified, not the array type (section 6.7.3
15185      of C99).  */
15186   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15187     return add_array_cv_type (die, cu, base_type, 0, 1);
15188
15189   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15190   return set_die_type (die, cv_type, cu);
15191 }
15192
15193 /* Handle DW_TAG_restrict_type.  */
15194
15195 static struct type *
15196 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15197 {
15198   struct type *base_type, *cv_type;
15199
15200   base_type = die_type (die, cu);
15201
15202   /* The die_type call above may have already set the type for this DIE.  */
15203   cv_type = get_die_type (die, cu);
15204   if (cv_type)
15205     return cv_type;
15206
15207   cv_type = make_restrict_type (base_type);
15208   return set_die_type (die, cv_type, cu);
15209 }
15210
15211 /* Handle DW_TAG_atomic_type.  */
15212
15213 static struct type *
15214 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15215 {
15216   struct type *base_type, *cv_type;
15217
15218   base_type = die_type (die, cu);
15219
15220   /* The die_type call above may have already set the type for this DIE.  */
15221   cv_type = get_die_type (die, cu);
15222   if (cv_type)
15223     return cv_type;
15224
15225   cv_type = make_atomic_type (base_type);
15226   return set_die_type (die, cv_type, cu);
15227 }
15228
15229 /* Extract all information from a DW_TAG_string_type DIE and add to
15230    the user defined type vector.  It isn't really a user defined type,
15231    but it behaves like one, with other DIE's using an AT_user_def_type
15232    attribute to reference it.  */
15233
15234 static struct type *
15235 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15236 {
15237   struct objfile *objfile = cu->objfile;
15238   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15239   struct type *type, *range_type, *index_type, *char_type;
15240   struct attribute *attr;
15241   unsigned int length;
15242
15243   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15244   if (attr)
15245     {
15246       length = DW_UNSND (attr);
15247     }
15248   else
15249     {
15250       /* Check for the DW_AT_byte_size attribute.  */
15251       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15252       if (attr)
15253         {
15254           length = DW_UNSND (attr);
15255         }
15256       else
15257         {
15258           length = 1;
15259         }
15260     }
15261
15262   index_type = objfile_type (objfile)->builtin_int;
15263   range_type = create_static_range_type (NULL, index_type, 1, length);
15264   char_type = language_string_char_type (cu->language_defn, gdbarch);
15265   type = create_string_type (NULL, char_type, range_type);
15266
15267   return set_die_type (die, type, cu);
15268 }
15269
15270 /* Assuming that DIE corresponds to a function, returns nonzero
15271    if the function is prototyped.  */
15272
15273 static int
15274 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15275 {
15276   struct attribute *attr;
15277
15278   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15279   if (attr && (DW_UNSND (attr) != 0))
15280     return 1;
15281
15282   /* The DWARF standard implies that the DW_AT_prototyped attribute
15283      is only meaninful for C, but the concept also extends to other
15284      languages that allow unprototyped functions (Eg: Objective C).
15285      For all other languages, assume that functions are always
15286      prototyped.  */
15287   if (cu->language != language_c
15288       && cu->language != language_objc
15289       && cu->language != language_opencl)
15290     return 1;
15291
15292   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15293      prototyped and unprototyped functions; default to prototyped,
15294      since that is more common in modern code (and RealView warns
15295      about unprototyped functions).  */
15296   if (producer_is_realview (cu->producer))
15297     return 1;
15298
15299   return 0;
15300 }
15301
15302 /* Handle DIES due to C code like:
15303
15304    struct foo
15305    {
15306    int (*funcp)(int a, long l);
15307    int b;
15308    };
15309
15310    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15311
15312 static struct type *
15313 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15314 {
15315   struct objfile *objfile = cu->objfile;
15316   struct type *type;            /* Type that this function returns.  */
15317   struct type *ftype;           /* Function that returns above type.  */
15318   struct attribute *attr;
15319
15320   type = die_type (die, cu);
15321
15322   /* The die_type call above may have already set the type for this DIE.  */
15323   ftype = get_die_type (die, cu);
15324   if (ftype)
15325     return ftype;
15326
15327   ftype = lookup_function_type (type);
15328
15329   if (prototyped_function_p (die, cu))
15330     TYPE_PROTOTYPED (ftype) = 1;
15331
15332   /* Store the calling convention in the type if it's available in
15333      the subroutine die.  Otherwise set the calling convention to
15334      the default value DW_CC_normal.  */
15335   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15336   if (attr)
15337     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15338   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15339     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15340   else
15341     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15342
15343   /* Record whether the function returns normally to its caller or not
15344      if the DWARF producer set that information.  */
15345   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15346   if (attr && (DW_UNSND (attr) != 0))
15347     TYPE_NO_RETURN (ftype) = 1;
15348
15349   /* We need to add the subroutine type to the die immediately so
15350      we don't infinitely recurse when dealing with parameters
15351      declared as the same subroutine type.  */
15352   set_die_type (die, ftype, cu);
15353
15354   if (die->child != NULL)
15355     {
15356       struct type *void_type = objfile_type (objfile)->builtin_void;
15357       struct die_info *child_die;
15358       int nparams, iparams;
15359
15360       /* Count the number of parameters.
15361          FIXME: GDB currently ignores vararg functions, but knows about
15362          vararg member functions.  */
15363       nparams = 0;
15364       child_die = die->child;
15365       while (child_die && child_die->tag)
15366         {
15367           if (child_die->tag == DW_TAG_formal_parameter)
15368             nparams++;
15369           else if (child_die->tag == DW_TAG_unspecified_parameters)
15370             TYPE_VARARGS (ftype) = 1;
15371           child_die = sibling_die (child_die);
15372         }
15373
15374       /* Allocate storage for parameters and fill them in.  */
15375       TYPE_NFIELDS (ftype) = nparams;
15376       TYPE_FIELDS (ftype) = (struct field *)
15377         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15378
15379       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15380          even if we error out during the parameters reading below.  */
15381       for (iparams = 0; iparams < nparams; iparams++)
15382         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15383
15384       iparams = 0;
15385       child_die = die->child;
15386       while (child_die && child_die->tag)
15387         {
15388           if (child_die->tag == DW_TAG_formal_parameter)
15389             {
15390               struct type *arg_type;
15391
15392               /* DWARF version 2 has no clean way to discern C++
15393                  static and non-static member functions.  G++ helps
15394                  GDB by marking the first parameter for non-static
15395                  member functions (which is the this pointer) as
15396                  artificial.  We pass this information to
15397                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15398
15399                  DWARF version 3 added DW_AT_object_pointer, which GCC
15400                  4.5 does not yet generate.  */
15401               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15402               if (attr)
15403                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15404               else
15405                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15406               arg_type = die_type (child_die, cu);
15407
15408               /* RealView does not mark THIS as const, which the testsuite
15409                  expects.  GCC marks THIS as const in method definitions,
15410                  but not in the class specifications (GCC PR 43053).  */
15411               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15412                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15413                 {
15414                   int is_this = 0;
15415                   struct dwarf2_cu *arg_cu = cu;
15416                   const char *name = dwarf2_name (child_die, cu);
15417
15418                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15419                   if (attr)
15420                     {
15421                       /* If the compiler emits this, use it.  */
15422                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15423                         is_this = 1;
15424                     }
15425                   else if (name && strcmp (name, "this") == 0)
15426                     /* Function definitions will have the argument names.  */
15427                     is_this = 1;
15428                   else if (name == NULL && iparams == 0)
15429                     /* Declarations may not have the names, so like
15430                        elsewhere in GDB, assume an artificial first
15431                        argument is "this".  */
15432                     is_this = 1;
15433
15434                   if (is_this)
15435                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15436                                              arg_type, 0);
15437                 }
15438
15439               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15440               iparams++;
15441             }
15442           child_die = sibling_die (child_die);
15443         }
15444     }
15445
15446   return ftype;
15447 }
15448
15449 static struct type *
15450 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15451 {
15452   struct objfile *objfile = cu->objfile;
15453   const char *name = NULL;
15454   struct type *this_type, *target_type;
15455
15456   name = dwarf2_full_name (NULL, die, cu);
15457   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15458   TYPE_TARGET_STUB (this_type) = 1;
15459   set_die_type (die, this_type, cu);
15460   target_type = die_type (die, cu);
15461   if (target_type != this_type)
15462     TYPE_TARGET_TYPE (this_type) = target_type;
15463   else
15464     {
15465       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15466          spec and cause infinite loops in GDB.  */
15467       complaint (&symfile_complaints,
15468                  _("Self-referential DW_TAG_typedef "
15469                    "- DIE at 0x%x [in module %s]"),
15470                  to_underlying (die->sect_off), objfile_name (objfile));
15471       TYPE_TARGET_TYPE (this_type) = NULL;
15472     }
15473   return this_type;
15474 }
15475
15476 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15477    (which may be different from NAME) to the architecture back-end to allow
15478    it to guess the correct format if necessary.  */
15479
15480 static struct type *
15481 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15482                         const char *name_hint)
15483 {
15484   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15485   const struct floatformat **format;
15486   struct type *type;
15487
15488   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15489   if (format)
15490     type = init_float_type (objfile, bits, name, format);
15491   else
15492     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15493
15494   return type;
15495 }
15496
15497 /* Find a representation of a given base type and install
15498    it in the TYPE field of the die.  */
15499
15500 static struct type *
15501 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15502 {
15503   struct objfile *objfile = cu->objfile;
15504   struct type *type;
15505   struct attribute *attr;
15506   int encoding = 0, bits = 0;
15507   const char *name;
15508
15509   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15510   if (attr)
15511     {
15512       encoding = DW_UNSND (attr);
15513     }
15514   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15515   if (attr)
15516     {
15517       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15518     }
15519   name = dwarf2_name (die, cu);
15520   if (!name)
15521     {
15522       complaint (&symfile_complaints,
15523                  _("DW_AT_name missing from DW_TAG_base_type"));
15524     }
15525
15526   switch (encoding)
15527     {
15528       case DW_ATE_address:
15529         /* Turn DW_ATE_address into a void * pointer.  */
15530         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
15531         type = init_pointer_type (objfile, bits, name, type);
15532         break;
15533       case DW_ATE_boolean:
15534         type = init_boolean_type (objfile, bits, 1, name);
15535         break;
15536       case DW_ATE_complex_float:
15537         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15538         type = init_complex_type (objfile, name, type);
15539         break;
15540       case DW_ATE_decimal_float:
15541         type = init_decfloat_type (objfile, bits, name);
15542         break;
15543       case DW_ATE_float:
15544         type = dwarf2_init_float_type (objfile, bits, name, name);
15545         break;
15546       case DW_ATE_signed:
15547         type = init_integer_type (objfile, bits, 0, name);
15548         break;
15549       case DW_ATE_unsigned:
15550         if (cu->language == language_fortran
15551             && name
15552             && startswith (name, "character("))
15553           type = init_character_type (objfile, bits, 1, name);
15554         else
15555           type = init_integer_type (objfile, bits, 1, name);
15556         break;
15557       case DW_ATE_signed_char:
15558         if (cu->language == language_ada || cu->language == language_m2
15559             || cu->language == language_pascal
15560             || cu->language == language_fortran)
15561           type = init_character_type (objfile, bits, 0, name);
15562         else
15563           type = init_integer_type (objfile, bits, 0, name);
15564         break;
15565       case DW_ATE_unsigned_char:
15566         if (cu->language == language_ada || cu->language == language_m2
15567             || cu->language == language_pascal
15568             || cu->language == language_fortran
15569             || cu->language == language_rust)
15570           type = init_character_type (objfile, bits, 1, name);
15571         else
15572           type = init_integer_type (objfile, bits, 1, name);
15573         break;
15574       case DW_ATE_UTF:
15575         {
15576           gdbarch *arch = get_objfile_arch (objfile);
15577
15578           if (bits == 16)
15579             type = builtin_type (arch)->builtin_char16;
15580           else if (bits == 32)
15581             type = builtin_type (arch)->builtin_char32;
15582           else
15583             {
15584               complaint (&symfile_complaints,
15585                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15586                          bits);
15587               type = init_integer_type (objfile, bits, 1, name);
15588             }
15589           return set_die_type (die, type, cu);
15590         }
15591         break;
15592
15593       default:
15594         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15595                    dwarf_type_encoding_name (encoding));
15596         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15597         break;
15598     }
15599
15600   if (name && strcmp (name, "char") == 0)
15601     TYPE_NOSIGN (type) = 1;
15602
15603   return set_die_type (die, type, cu);
15604 }
15605
15606 /* Parse dwarf attribute if it's a block, reference or constant and put the
15607    resulting value of the attribute into struct bound_prop.
15608    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15609
15610 static int
15611 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15612                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15613 {
15614   struct dwarf2_property_baton *baton;
15615   struct obstack *obstack = &cu->objfile->objfile_obstack;
15616
15617   if (attr == NULL || prop == NULL)
15618     return 0;
15619
15620   if (attr_form_is_block (attr))
15621     {
15622       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15623       baton->referenced_type = NULL;
15624       baton->locexpr.per_cu = cu->per_cu;
15625       baton->locexpr.size = DW_BLOCK (attr)->size;
15626       baton->locexpr.data = DW_BLOCK (attr)->data;
15627       prop->data.baton = baton;
15628       prop->kind = PROP_LOCEXPR;
15629       gdb_assert (prop->data.baton != NULL);
15630     }
15631   else if (attr_form_is_ref (attr))
15632     {
15633       struct dwarf2_cu *target_cu = cu;
15634       struct die_info *target_die;
15635       struct attribute *target_attr;
15636
15637       target_die = follow_die_ref (die, attr, &target_cu);
15638       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15639       if (target_attr == NULL)
15640         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15641                                    target_cu);
15642       if (target_attr == NULL)
15643         return 0;
15644
15645       switch (target_attr->name)
15646         {
15647           case DW_AT_location:
15648             if (attr_form_is_section_offset (target_attr))
15649               {
15650                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15651                 baton->referenced_type = die_type (target_die, target_cu);
15652                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15653                 prop->data.baton = baton;
15654                 prop->kind = PROP_LOCLIST;
15655                 gdb_assert (prop->data.baton != NULL);
15656               }
15657             else if (attr_form_is_block (target_attr))
15658               {
15659                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15660                 baton->referenced_type = die_type (target_die, target_cu);
15661                 baton->locexpr.per_cu = cu->per_cu;
15662                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15663                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15664                 prop->data.baton = baton;
15665                 prop->kind = PROP_LOCEXPR;
15666                 gdb_assert (prop->data.baton != NULL);
15667               }
15668             else
15669               {
15670                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15671                                                        "dynamic property");
15672                 return 0;
15673               }
15674             break;
15675           case DW_AT_data_member_location:
15676             {
15677               LONGEST offset;
15678
15679               if (!handle_data_member_location (target_die, target_cu,
15680                                                 &offset))
15681                 return 0;
15682
15683               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15684               baton->referenced_type = read_type_die (target_die->parent,
15685                                                       target_cu);
15686               baton->offset_info.offset = offset;
15687               baton->offset_info.type = die_type (target_die, target_cu);
15688               prop->data.baton = baton;
15689               prop->kind = PROP_ADDR_OFFSET;
15690               break;
15691             }
15692         }
15693     }
15694   else if (attr_form_is_constant (attr))
15695     {
15696       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15697       prop->kind = PROP_CONST;
15698     }
15699   else
15700     {
15701       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15702                                              dwarf2_name (die, cu));
15703       return 0;
15704     }
15705
15706   return 1;
15707 }
15708
15709 /* Read the given DW_AT_subrange DIE.  */
15710
15711 static struct type *
15712 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15713 {
15714   struct type *base_type, *orig_base_type;
15715   struct type *range_type;
15716   struct attribute *attr;
15717   struct dynamic_prop low, high;
15718   int low_default_is_valid;
15719   int high_bound_is_count = 0;
15720   const char *name;
15721   LONGEST negative_mask;
15722
15723   orig_base_type = die_type (die, cu);
15724   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15725      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15726      creating the range type, but we use the result of check_typedef
15727      when examining properties of the type.  */
15728   base_type = check_typedef (orig_base_type);
15729
15730   /* The die_type call above may have already set the type for this DIE.  */
15731   range_type = get_die_type (die, cu);
15732   if (range_type)
15733     return range_type;
15734
15735   low.kind = PROP_CONST;
15736   high.kind = PROP_CONST;
15737   high.data.const_val = 0;
15738
15739   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15740      omitting DW_AT_lower_bound.  */
15741   switch (cu->language)
15742     {
15743     case language_c:
15744     case language_cplus:
15745       low.data.const_val = 0;
15746       low_default_is_valid = 1;
15747       break;
15748     case language_fortran:
15749       low.data.const_val = 1;
15750       low_default_is_valid = 1;
15751       break;
15752     case language_d:
15753     case language_objc:
15754     case language_rust:
15755       low.data.const_val = 0;
15756       low_default_is_valid = (cu->header.version >= 4);
15757       break;
15758     case language_ada:
15759     case language_m2:
15760     case language_pascal:
15761       low.data.const_val = 1;
15762       low_default_is_valid = (cu->header.version >= 4);
15763       break;
15764     default:
15765       low.data.const_val = 0;
15766       low_default_is_valid = 0;
15767       break;
15768     }
15769
15770   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15771   if (attr)
15772     attr_to_dynamic_prop (attr, die, cu, &low);
15773   else if (!low_default_is_valid)
15774     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15775                                       "- DIE at 0x%x [in module %s]"),
15776                to_underlying (die->sect_off), objfile_name (cu->objfile));
15777
15778   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15779   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15780     {
15781       attr = dwarf2_attr (die, DW_AT_count, cu);
15782       if (attr_to_dynamic_prop (attr, die, cu, &high))
15783         {
15784           /* If bounds are constant do the final calculation here.  */
15785           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15786             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15787           else
15788             high_bound_is_count = 1;
15789         }
15790     }
15791
15792   /* Dwarf-2 specifications explicitly allows to create subrange types
15793      without specifying a base type.
15794      In that case, the base type must be set to the type of
15795      the lower bound, upper bound or count, in that order, if any of these
15796      three attributes references an object that has a type.
15797      If no base type is found, the Dwarf-2 specifications say that
15798      a signed integer type of size equal to the size of an address should
15799      be used.
15800      For the following C code: `extern char gdb_int [];'
15801      GCC produces an empty range DIE.
15802      FIXME: muller/2010-05-28: Possible references to object for low bound,
15803      high bound or count are not yet handled by this code.  */
15804   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15805     {
15806       struct objfile *objfile = cu->objfile;
15807       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15808       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15809       struct type *int_type = objfile_type (objfile)->builtin_int;
15810
15811       /* Test "int", "long int", and "long long int" objfile types,
15812          and select the first one having a size above or equal to the
15813          architecture address size.  */
15814       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15815         base_type = int_type;
15816       else
15817         {
15818           int_type = objfile_type (objfile)->builtin_long;
15819           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15820             base_type = int_type;
15821           else
15822             {
15823               int_type = objfile_type (objfile)->builtin_long_long;
15824               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15825                 base_type = int_type;
15826             }
15827         }
15828     }
15829
15830   /* Normally, the DWARF producers are expected to use a signed
15831      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15832      But this is unfortunately not always the case, as witnessed
15833      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15834      is used instead.  To work around that ambiguity, we treat
15835      the bounds as signed, and thus sign-extend their values, when
15836      the base type is signed.  */
15837   negative_mask =
15838     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15839   if (low.kind == PROP_CONST
15840       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15841     low.data.const_val |= negative_mask;
15842   if (high.kind == PROP_CONST
15843       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15844     high.data.const_val |= negative_mask;
15845
15846   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15847
15848   if (high_bound_is_count)
15849     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15850
15851   /* Ada expects an empty array on no boundary attributes.  */
15852   if (attr == NULL && cu->language != language_ada)
15853     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15854
15855   name = dwarf2_name (die, cu);
15856   if (name)
15857     TYPE_NAME (range_type) = name;
15858
15859   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15860   if (attr)
15861     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15862
15863   set_die_type (die, range_type, cu);
15864
15865   /* set_die_type should be already done.  */
15866   set_descriptive_type (range_type, die, cu);
15867
15868   return range_type;
15869 }
15870
15871 static struct type *
15872 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15873 {
15874   struct type *type;
15875
15876   /* For now, we only support the C meaning of an unspecified type: void.  */
15877
15878   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15879   TYPE_NAME (type) = dwarf2_name (die, cu);
15880
15881   return set_die_type (die, type, cu);
15882 }
15883
15884 /* Read a single die and all its descendents.  Set the die's sibling
15885    field to NULL; set other fields in the die correctly, and set all
15886    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15887    location of the info_ptr after reading all of those dies.  PARENT
15888    is the parent of the die in question.  */
15889
15890 static struct die_info *
15891 read_die_and_children (const struct die_reader_specs *reader,
15892                        const gdb_byte *info_ptr,
15893                        const gdb_byte **new_info_ptr,
15894                        struct die_info *parent)
15895 {
15896   struct die_info *die;
15897   const gdb_byte *cur_ptr;
15898   int has_children;
15899
15900   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15901   if (die == NULL)
15902     {
15903       *new_info_ptr = cur_ptr;
15904       return NULL;
15905     }
15906   store_in_ref_table (die, reader->cu);
15907
15908   if (has_children)
15909     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15910   else
15911     {
15912       die->child = NULL;
15913       *new_info_ptr = cur_ptr;
15914     }
15915
15916   die->sibling = NULL;
15917   die->parent = parent;
15918   return die;
15919 }
15920
15921 /* Read a die, all of its descendents, and all of its siblings; set
15922    all of the fields of all of the dies correctly.  Arguments are as
15923    in read_die_and_children.  */
15924
15925 static struct die_info *
15926 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15927                          const gdb_byte *info_ptr,
15928                          const gdb_byte **new_info_ptr,
15929                          struct die_info *parent)
15930 {
15931   struct die_info *first_die, *last_sibling;
15932   const gdb_byte *cur_ptr;
15933
15934   cur_ptr = info_ptr;
15935   first_die = last_sibling = NULL;
15936
15937   while (1)
15938     {
15939       struct die_info *die
15940         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15941
15942       if (die == NULL)
15943         {
15944           *new_info_ptr = cur_ptr;
15945           return first_die;
15946         }
15947
15948       if (!first_die)
15949         first_die = die;
15950       else
15951         last_sibling->sibling = die;
15952
15953       last_sibling = die;
15954     }
15955 }
15956
15957 /* Read a die, all of its descendents, and all of its siblings; set
15958    all of the fields of all of the dies correctly.  Arguments are as
15959    in read_die_and_children.
15960    This the main entry point for reading a DIE and all its children.  */
15961
15962 static struct die_info *
15963 read_die_and_siblings (const struct die_reader_specs *reader,
15964                        const gdb_byte *info_ptr,
15965                        const gdb_byte **new_info_ptr,
15966                        struct die_info *parent)
15967 {
15968   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15969                                                   new_info_ptr, parent);
15970
15971   if (dwarf_die_debug)
15972     {
15973       fprintf_unfiltered (gdb_stdlog,
15974                           "Read die from %s@0x%x of %s:\n",
15975                           get_section_name (reader->die_section),
15976                           (unsigned) (info_ptr - reader->die_section->buffer),
15977                           bfd_get_filename (reader->abfd));
15978       dump_die (die, dwarf_die_debug);
15979     }
15980
15981   return die;
15982 }
15983
15984 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15985    attributes.
15986    The caller is responsible for filling in the extra attributes
15987    and updating (*DIEP)->num_attrs.
15988    Set DIEP to point to a newly allocated die with its information,
15989    except for its child, sibling, and parent fields.
15990    Set HAS_CHILDREN to tell whether the die has children or not.  */
15991
15992 static const gdb_byte *
15993 read_full_die_1 (const struct die_reader_specs *reader,
15994                  struct die_info **diep, const gdb_byte *info_ptr,
15995                  int *has_children, int num_extra_attrs)
15996 {
15997   unsigned int abbrev_number, bytes_read, i;
15998   struct abbrev_info *abbrev;
15999   struct die_info *die;
16000   struct dwarf2_cu *cu = reader->cu;
16001   bfd *abfd = reader->abfd;
16002
16003   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
16004   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16005   info_ptr += bytes_read;
16006   if (!abbrev_number)
16007     {
16008       *diep = NULL;
16009       *has_children = 0;
16010       return info_ptr;
16011     }
16012
16013   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
16014   if (!abbrev)
16015     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
16016            abbrev_number,
16017            bfd_get_filename (abfd));
16018
16019   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16020   die->sect_off = sect_off;
16021   die->tag = abbrev->tag;
16022   die->abbrev = abbrev_number;
16023
16024   /* Make the result usable.
16025      The caller needs to update num_attrs after adding the extra
16026      attributes.  */
16027   die->num_attrs = abbrev->num_attrs;
16028
16029   for (i = 0; i < abbrev->num_attrs; ++i)
16030     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16031                                info_ptr);
16032
16033   *diep = die;
16034   *has_children = abbrev->has_children;
16035   return info_ptr;
16036 }
16037
16038 /* Read a die and all its attributes.
16039    Set DIEP to point to a newly allocated die with its information,
16040    except for its child, sibling, and parent fields.
16041    Set HAS_CHILDREN to tell whether the die has children or not.  */
16042
16043 static const gdb_byte *
16044 read_full_die (const struct die_reader_specs *reader,
16045                struct die_info **diep, const gdb_byte *info_ptr,
16046                int *has_children)
16047 {
16048   const gdb_byte *result;
16049
16050   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16051
16052   if (dwarf_die_debug)
16053     {
16054       fprintf_unfiltered (gdb_stdlog,
16055                           "Read die from %s@0x%x of %s:\n",
16056                           get_section_name (reader->die_section),
16057                           (unsigned) (info_ptr - reader->die_section->buffer),
16058                           bfd_get_filename (reader->abfd));
16059       dump_die (*diep, dwarf_die_debug);
16060     }
16061
16062   return result;
16063 }
16064 \f
16065 /* Abbreviation tables.
16066
16067    In DWARF version 2, the description of the debugging information is
16068    stored in a separate .debug_abbrev section.  Before we read any
16069    dies from a section we read in all abbreviations and install them
16070    in a hash table.  */
16071
16072 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16073
16074 static struct abbrev_info *
16075 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16076 {
16077   struct abbrev_info *abbrev;
16078
16079   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16080   memset (abbrev, 0, sizeof (struct abbrev_info));
16081
16082   return abbrev;
16083 }
16084
16085 /* Add an abbreviation to the table.  */
16086
16087 static void
16088 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16089                          unsigned int abbrev_number,
16090                          struct abbrev_info *abbrev)
16091 {
16092   unsigned int hash_number;
16093
16094   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16095   abbrev->next = abbrev_table->abbrevs[hash_number];
16096   abbrev_table->abbrevs[hash_number] = abbrev;
16097 }
16098
16099 /* Look up an abbrev in the table.
16100    Returns NULL if the abbrev is not found.  */
16101
16102 static struct abbrev_info *
16103 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16104                             unsigned int abbrev_number)
16105 {
16106   unsigned int hash_number;
16107   struct abbrev_info *abbrev;
16108
16109   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16110   abbrev = abbrev_table->abbrevs[hash_number];
16111
16112   while (abbrev)
16113     {
16114       if (abbrev->number == abbrev_number)
16115         return abbrev;
16116       abbrev = abbrev->next;
16117     }
16118   return NULL;
16119 }
16120
16121 /* Read in an abbrev table.  */
16122
16123 static struct abbrev_table *
16124 abbrev_table_read_table (struct dwarf2_section_info *section,
16125                          sect_offset sect_off)
16126 {
16127   struct objfile *objfile = dwarf2_per_objfile->objfile;
16128   bfd *abfd = get_section_bfd_owner (section);
16129   struct abbrev_table *abbrev_table;
16130   const gdb_byte *abbrev_ptr;
16131   struct abbrev_info *cur_abbrev;
16132   unsigned int abbrev_number, bytes_read, abbrev_name;
16133   unsigned int abbrev_form;
16134   struct attr_abbrev *cur_attrs;
16135   unsigned int allocated_attrs;
16136
16137   abbrev_table = XNEW (struct abbrev_table);
16138   abbrev_table->sect_off = sect_off;
16139   obstack_init (&abbrev_table->abbrev_obstack);
16140   abbrev_table->abbrevs =
16141     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16142                ABBREV_HASH_SIZE);
16143   memset (abbrev_table->abbrevs, 0,
16144           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16145
16146   dwarf2_read_section (objfile, section);
16147   abbrev_ptr = section->buffer + to_underlying (sect_off);
16148   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16149   abbrev_ptr += bytes_read;
16150
16151   allocated_attrs = ATTR_ALLOC_CHUNK;
16152   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16153
16154   /* Loop until we reach an abbrev number of 0.  */
16155   while (abbrev_number)
16156     {
16157       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16158
16159       /* read in abbrev header */
16160       cur_abbrev->number = abbrev_number;
16161       cur_abbrev->tag
16162         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16163       abbrev_ptr += bytes_read;
16164       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16165       abbrev_ptr += 1;
16166
16167       /* now read in declarations */
16168       for (;;)
16169         {
16170           LONGEST implicit_const;
16171
16172           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16173           abbrev_ptr += bytes_read;
16174           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16175           abbrev_ptr += bytes_read;
16176           if (abbrev_form == DW_FORM_implicit_const)
16177             {
16178               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16179                                                    &bytes_read);
16180               abbrev_ptr += bytes_read;
16181             }
16182           else
16183             {
16184               /* Initialize it due to a false compiler warning.  */
16185               implicit_const = -1;
16186             }
16187
16188           if (abbrev_name == 0)
16189             break;
16190
16191           if (cur_abbrev->num_attrs == allocated_attrs)
16192             {
16193               allocated_attrs += ATTR_ALLOC_CHUNK;
16194               cur_attrs
16195                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16196             }
16197
16198           cur_attrs[cur_abbrev->num_attrs].name
16199             = (enum dwarf_attribute) abbrev_name;
16200           cur_attrs[cur_abbrev->num_attrs].form
16201             = (enum dwarf_form) abbrev_form;
16202           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16203           ++cur_abbrev->num_attrs;
16204         }
16205
16206       cur_abbrev->attrs =
16207         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16208                    cur_abbrev->num_attrs);
16209       memcpy (cur_abbrev->attrs, cur_attrs,
16210               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16211
16212       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16213
16214       /* Get next abbreviation.
16215          Under Irix6 the abbreviations for a compilation unit are not
16216          always properly terminated with an abbrev number of 0.
16217          Exit loop if we encounter an abbreviation which we have
16218          already read (which means we are about to read the abbreviations
16219          for the next compile unit) or if the end of the abbreviation
16220          table is reached.  */
16221       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16222         break;
16223       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16224       abbrev_ptr += bytes_read;
16225       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16226         break;
16227     }
16228
16229   xfree (cur_attrs);
16230   return abbrev_table;
16231 }
16232
16233 /* Free the resources held by ABBREV_TABLE.  */
16234
16235 static void
16236 abbrev_table_free (struct abbrev_table *abbrev_table)
16237 {
16238   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16239   xfree (abbrev_table);
16240 }
16241
16242 /* Same as abbrev_table_free but as a cleanup.
16243    We pass in a pointer to the pointer to the table so that we can
16244    set the pointer to NULL when we're done.  It also simplifies
16245    build_type_psymtabs_1.  */
16246
16247 static void
16248 abbrev_table_free_cleanup (void *table_ptr)
16249 {
16250   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16251
16252   if (*abbrev_table_ptr != NULL)
16253     abbrev_table_free (*abbrev_table_ptr);
16254   *abbrev_table_ptr = NULL;
16255 }
16256
16257 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16258
16259 static void
16260 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16261                      struct dwarf2_section_info *abbrev_section)
16262 {
16263   cu->abbrev_table =
16264     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16265 }
16266
16267 /* Release the memory used by the abbrev table for a compilation unit.  */
16268
16269 static void
16270 dwarf2_free_abbrev_table (void *ptr_to_cu)
16271 {
16272   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16273
16274   if (cu->abbrev_table != NULL)
16275     abbrev_table_free (cu->abbrev_table);
16276   /* Set this to NULL so that we SEGV if we try to read it later,
16277      and also because free_comp_unit verifies this is NULL.  */
16278   cu->abbrev_table = NULL;
16279 }
16280 \f
16281 /* Returns nonzero if TAG represents a type that we might generate a partial
16282    symbol for.  */
16283
16284 static int
16285 is_type_tag_for_partial (int tag)
16286 {
16287   switch (tag)
16288     {
16289 #if 0
16290     /* Some types that would be reasonable to generate partial symbols for,
16291        that we don't at present.  */
16292     case DW_TAG_array_type:
16293     case DW_TAG_file_type:
16294     case DW_TAG_ptr_to_member_type:
16295     case DW_TAG_set_type:
16296     case DW_TAG_string_type:
16297     case DW_TAG_subroutine_type:
16298 #endif
16299     case DW_TAG_base_type:
16300     case DW_TAG_class_type:
16301     case DW_TAG_interface_type:
16302     case DW_TAG_enumeration_type:
16303     case DW_TAG_structure_type:
16304     case DW_TAG_subrange_type:
16305     case DW_TAG_typedef:
16306     case DW_TAG_union_type:
16307       return 1;
16308     default:
16309       return 0;
16310     }
16311 }
16312
16313 /* Load all DIEs that are interesting for partial symbols into memory.  */
16314
16315 static struct partial_die_info *
16316 load_partial_dies (const struct die_reader_specs *reader,
16317                    const gdb_byte *info_ptr, int building_psymtab)
16318 {
16319   struct dwarf2_cu *cu = reader->cu;
16320   struct objfile *objfile = cu->objfile;
16321   struct partial_die_info *part_die;
16322   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16323   struct abbrev_info *abbrev;
16324   unsigned int bytes_read;
16325   unsigned int load_all = 0;
16326   int nesting_level = 1;
16327
16328   parent_die = NULL;
16329   last_die = NULL;
16330
16331   gdb_assert (cu->per_cu != NULL);
16332   if (cu->per_cu->load_all_dies)
16333     load_all = 1;
16334
16335   cu->partial_dies
16336     = htab_create_alloc_ex (cu->header.length / 12,
16337                             partial_die_hash,
16338                             partial_die_eq,
16339                             NULL,
16340                             &cu->comp_unit_obstack,
16341                             hashtab_obstack_allocate,
16342                             dummy_obstack_deallocate);
16343
16344   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16345
16346   while (1)
16347     {
16348       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16349
16350       /* A NULL abbrev means the end of a series of children.  */
16351       if (abbrev == NULL)
16352         {
16353           if (--nesting_level == 0)
16354             {
16355               /* PART_DIE was probably the last thing allocated on the
16356                  comp_unit_obstack, so we could call obstack_free
16357                  here.  We don't do that because the waste is small,
16358                  and will be cleaned up when we're done with this
16359                  compilation unit.  This way, we're also more robust
16360                  against other users of the comp_unit_obstack.  */
16361               return first_die;
16362             }
16363           info_ptr += bytes_read;
16364           last_die = parent_die;
16365           parent_die = parent_die->die_parent;
16366           continue;
16367         }
16368
16369       /* Check for template arguments.  We never save these; if
16370          they're seen, we just mark the parent, and go on our way.  */
16371       if (parent_die != NULL
16372           && cu->language == language_cplus
16373           && (abbrev->tag == DW_TAG_template_type_param
16374               || abbrev->tag == DW_TAG_template_value_param))
16375         {
16376           parent_die->has_template_arguments = 1;
16377
16378           if (!load_all)
16379             {
16380               /* We don't need a partial DIE for the template argument.  */
16381               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16382               continue;
16383             }
16384         }
16385
16386       /* We only recurse into c++ subprograms looking for template arguments.
16387          Skip their other children.  */
16388       if (!load_all
16389           && cu->language == language_cplus
16390           && parent_die != NULL
16391           && parent_die->tag == DW_TAG_subprogram)
16392         {
16393           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16394           continue;
16395         }
16396
16397       /* Check whether this DIE is interesting enough to save.  Normally
16398          we would not be interested in members here, but there may be
16399          later variables referencing them via DW_AT_specification (for
16400          static members).  */
16401       if (!load_all
16402           && !is_type_tag_for_partial (abbrev->tag)
16403           && abbrev->tag != DW_TAG_constant
16404           && abbrev->tag != DW_TAG_enumerator
16405           && abbrev->tag != DW_TAG_subprogram
16406           && abbrev->tag != DW_TAG_lexical_block
16407           && abbrev->tag != DW_TAG_variable
16408           && abbrev->tag != DW_TAG_namespace
16409           && abbrev->tag != DW_TAG_module
16410           && abbrev->tag != DW_TAG_member
16411           && abbrev->tag != DW_TAG_imported_unit
16412           && abbrev->tag != DW_TAG_imported_declaration)
16413         {
16414           /* Otherwise we skip to the next sibling, if any.  */
16415           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16416           continue;
16417         }
16418
16419       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16420                                    info_ptr);
16421
16422       /* This two-pass algorithm for processing partial symbols has a
16423          high cost in cache pressure.  Thus, handle some simple cases
16424          here which cover the majority of C partial symbols.  DIEs
16425          which neither have specification tags in them, nor could have
16426          specification tags elsewhere pointing at them, can simply be
16427          processed and discarded.
16428
16429          This segment is also optional; scan_partial_symbols and
16430          add_partial_symbol will handle these DIEs if we chain
16431          them in normally.  When compilers which do not emit large
16432          quantities of duplicate debug information are more common,
16433          this code can probably be removed.  */
16434
16435       /* Any complete simple types at the top level (pretty much all
16436          of them, for a language without namespaces), can be processed
16437          directly.  */
16438       if (parent_die == NULL
16439           && part_die->has_specification == 0
16440           && part_die->is_declaration == 0
16441           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16442               || part_die->tag == DW_TAG_base_type
16443               || part_die->tag == DW_TAG_subrange_type))
16444         {
16445           if (building_psymtab && part_die->name != NULL)
16446             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16447                                  VAR_DOMAIN, LOC_TYPEDEF,
16448                                  &objfile->static_psymbols,
16449                                  0, cu->language, objfile);
16450           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16451           continue;
16452         }
16453
16454       /* The exception for DW_TAG_typedef with has_children above is
16455          a workaround of GCC PR debug/47510.  In the case of this complaint
16456          type_name_no_tag_or_error will error on such types later.
16457
16458          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16459          it could not find the child DIEs referenced later, this is checked
16460          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16461
16462       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16463         complaint (&symfile_complaints,
16464                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16465                      "- DIE at 0x%x [in module %s]"),
16466                    to_underlying (part_die->sect_off), objfile_name (objfile));
16467
16468       /* If we're at the second level, and we're an enumerator, and
16469          our parent has no specification (meaning possibly lives in a
16470          namespace elsewhere), then we can add the partial symbol now
16471          instead of queueing it.  */
16472       if (part_die->tag == DW_TAG_enumerator
16473           && parent_die != NULL
16474           && parent_die->die_parent == NULL
16475           && parent_die->tag == DW_TAG_enumeration_type
16476           && parent_die->has_specification == 0)
16477         {
16478           if (part_die->name == NULL)
16479             complaint (&symfile_complaints,
16480                        _("malformed enumerator DIE ignored"));
16481           else if (building_psymtab)
16482             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16483                                  VAR_DOMAIN, LOC_CONST,
16484                                  cu->language == language_cplus
16485                                  ? &objfile->global_psymbols
16486                                  : &objfile->static_psymbols,
16487                                  0, cu->language, objfile);
16488
16489           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16490           continue;
16491         }
16492
16493       /* We'll save this DIE so link it in.  */
16494       part_die->die_parent = parent_die;
16495       part_die->die_sibling = NULL;
16496       part_die->die_child = NULL;
16497
16498       if (last_die && last_die == parent_die)
16499         last_die->die_child = part_die;
16500       else if (last_die)
16501         last_die->die_sibling = part_die;
16502
16503       last_die = part_die;
16504
16505       if (first_die == NULL)
16506         first_die = part_die;
16507
16508       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16509          find interesting need to be in the hash table, because we
16510          also have the parent/sibling/child chains; only those that we
16511          might refer to by offset later during partial symbol reading.
16512
16513          For now this means things that might have be the target of a
16514          DW_AT_specification, DW_AT_abstract_origin, or
16515          DW_AT_extension.  DW_AT_extension will refer only to
16516          namespaces; DW_AT_abstract_origin refers to functions (and
16517          many things under the function DIE, but we do not recurse
16518          into function DIEs during partial symbol reading) and
16519          possibly variables as well; DW_AT_specification refers to
16520          declarations.  Declarations ought to have the DW_AT_declaration
16521          flag.  It happens that GCC forgets to put it in sometimes, but
16522          only for functions, not for types.
16523
16524          Adding more things than necessary to the hash table is harmless
16525          except for the performance cost.  Adding too few will result in
16526          wasted time in find_partial_die, when we reread the compilation
16527          unit with load_all_dies set.  */
16528
16529       if (load_all
16530           || abbrev->tag == DW_TAG_constant
16531           || abbrev->tag == DW_TAG_subprogram
16532           || abbrev->tag == DW_TAG_variable
16533           || abbrev->tag == DW_TAG_namespace
16534           || part_die->is_declaration)
16535         {
16536           void **slot;
16537
16538           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16539                                            to_underlying (part_die->sect_off),
16540                                            INSERT);
16541           *slot = part_die;
16542         }
16543
16544       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16545
16546       /* For some DIEs we want to follow their children (if any).  For C
16547          we have no reason to follow the children of structures; for other
16548          languages we have to, so that we can get at method physnames
16549          to infer fully qualified class names, for DW_AT_specification,
16550          and for C++ template arguments.  For C++, we also look one level
16551          inside functions to find template arguments (if the name of the
16552          function does not already contain the template arguments).
16553
16554          For Ada, we need to scan the children of subprograms and lexical
16555          blocks as well because Ada allows the definition of nested
16556          entities that could be interesting for the debugger, such as
16557          nested subprograms for instance.  */
16558       if (last_die->has_children
16559           && (load_all
16560               || last_die->tag == DW_TAG_namespace
16561               || last_die->tag == DW_TAG_module
16562               || last_die->tag == DW_TAG_enumeration_type
16563               || (cu->language == language_cplus
16564                   && last_die->tag == DW_TAG_subprogram
16565                   && (last_die->name == NULL
16566                       || strchr (last_die->name, '<') == NULL))
16567               || (cu->language != language_c
16568                   && (last_die->tag == DW_TAG_class_type
16569                       || last_die->tag == DW_TAG_interface_type
16570                       || last_die->tag == DW_TAG_structure_type
16571                       || last_die->tag == DW_TAG_union_type))
16572               || (cu->language == language_ada
16573                   && (last_die->tag == DW_TAG_subprogram
16574                       || last_die->tag == DW_TAG_lexical_block))))
16575         {
16576           nesting_level++;
16577           parent_die = last_die;
16578           continue;
16579         }
16580
16581       /* Otherwise we skip to the next sibling, if any.  */
16582       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16583
16584       /* Back to the top, do it again.  */
16585     }
16586 }
16587
16588 /* Read a minimal amount of information into the minimal die structure.  */
16589
16590 static const gdb_byte *
16591 read_partial_die (const struct die_reader_specs *reader,
16592                   struct partial_die_info *part_die,
16593                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16594                   const gdb_byte *info_ptr)
16595 {
16596   struct dwarf2_cu *cu = reader->cu;
16597   struct objfile *objfile = cu->objfile;
16598   const gdb_byte *buffer = reader->buffer;
16599   unsigned int i;
16600   struct attribute attr;
16601   int has_low_pc_attr = 0;
16602   int has_high_pc_attr = 0;
16603   int high_pc_relative = 0;
16604
16605   memset (part_die, 0, sizeof (struct partial_die_info));
16606
16607   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16608
16609   info_ptr += abbrev_len;
16610
16611   if (abbrev == NULL)
16612     return info_ptr;
16613
16614   part_die->tag = abbrev->tag;
16615   part_die->has_children = abbrev->has_children;
16616
16617   for (i = 0; i < abbrev->num_attrs; ++i)
16618     {
16619       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16620
16621       /* Store the data if it is of an attribute we want to keep in a
16622          partial symbol table.  */
16623       switch (attr.name)
16624         {
16625         case DW_AT_name:
16626           switch (part_die->tag)
16627             {
16628             case DW_TAG_compile_unit:
16629             case DW_TAG_partial_unit:
16630             case DW_TAG_type_unit:
16631               /* Compilation units have a DW_AT_name that is a filename, not
16632                  a source language identifier.  */
16633             case DW_TAG_enumeration_type:
16634             case DW_TAG_enumerator:
16635               /* These tags always have simple identifiers already; no need
16636                  to canonicalize them.  */
16637               part_die->name = DW_STRING (&attr);
16638               break;
16639             default:
16640               part_die->name
16641                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16642                                             &objfile->per_bfd->storage_obstack);
16643               break;
16644             }
16645           break;
16646         case DW_AT_linkage_name:
16647         case DW_AT_MIPS_linkage_name:
16648           /* Note that both forms of linkage name might appear.  We
16649              assume they will be the same, and we only store the last
16650              one we see.  */
16651           if (cu->language == language_ada)
16652             part_die->name = DW_STRING (&attr);
16653           part_die->linkage_name = DW_STRING (&attr);
16654           break;
16655         case DW_AT_low_pc:
16656           has_low_pc_attr = 1;
16657           part_die->lowpc = attr_value_as_address (&attr);
16658           break;
16659         case DW_AT_high_pc:
16660           has_high_pc_attr = 1;
16661           part_die->highpc = attr_value_as_address (&attr);
16662           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16663                 high_pc_relative = 1;
16664           break;
16665         case DW_AT_location:
16666           /* Support the .debug_loc offsets.  */
16667           if (attr_form_is_block (&attr))
16668             {
16669                part_die->d.locdesc = DW_BLOCK (&attr);
16670             }
16671           else if (attr_form_is_section_offset (&attr))
16672             {
16673               dwarf2_complex_location_expr_complaint ();
16674             }
16675           else
16676             {
16677               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16678                                                      "partial symbol information");
16679             }
16680           break;
16681         case DW_AT_external:
16682           part_die->is_external = DW_UNSND (&attr);
16683           break;
16684         case DW_AT_declaration:
16685           part_die->is_declaration = DW_UNSND (&attr);
16686           break;
16687         case DW_AT_type:
16688           part_die->has_type = 1;
16689           break;
16690         case DW_AT_abstract_origin:
16691         case DW_AT_specification:
16692         case DW_AT_extension:
16693           part_die->has_specification = 1;
16694           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16695           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16696                                    || cu->per_cu->is_dwz);
16697           break;
16698         case DW_AT_sibling:
16699           /* Ignore absolute siblings, they might point outside of
16700              the current compile unit.  */
16701           if (attr.form == DW_FORM_ref_addr)
16702             complaint (&symfile_complaints,
16703                        _("ignoring absolute DW_AT_sibling"));
16704           else
16705             {
16706               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16707               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16708
16709               if (sibling_ptr < info_ptr)
16710                 complaint (&symfile_complaints,
16711                            _("DW_AT_sibling points backwards"));
16712               else if (sibling_ptr > reader->buffer_end)
16713                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16714               else
16715                 part_die->sibling = sibling_ptr;
16716             }
16717           break;
16718         case DW_AT_byte_size:
16719           part_die->has_byte_size = 1;
16720           break;
16721         case DW_AT_const_value:
16722           part_die->has_const_value = 1;
16723           break;
16724         case DW_AT_calling_convention:
16725           /* DWARF doesn't provide a way to identify a program's source-level
16726              entry point.  DW_AT_calling_convention attributes are only meant
16727              to describe functions' calling conventions.
16728
16729              However, because it's a necessary piece of information in
16730              Fortran, and before DWARF 4 DW_CC_program was the only
16731              piece of debugging information whose definition refers to
16732              a 'main program' at all, several compilers marked Fortran
16733              main programs with DW_CC_program --- even when those
16734              functions use the standard calling conventions.
16735
16736              Although DWARF now specifies a way to provide this
16737              information, we support this practice for backward
16738              compatibility.  */
16739           if (DW_UNSND (&attr) == DW_CC_program
16740               && cu->language == language_fortran)
16741             part_die->main_subprogram = 1;
16742           break;
16743         case DW_AT_inline:
16744           if (DW_UNSND (&attr) == DW_INL_inlined
16745               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16746             part_die->may_be_inlined = 1;
16747           break;
16748
16749         case DW_AT_import:
16750           if (part_die->tag == DW_TAG_imported_unit)
16751             {
16752               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16753               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16754                                   || cu->per_cu->is_dwz);
16755             }
16756           break;
16757
16758         case DW_AT_main_subprogram:
16759           part_die->main_subprogram = DW_UNSND (&attr);
16760           break;
16761
16762         default:
16763           break;
16764         }
16765     }
16766
16767   if (high_pc_relative)
16768     part_die->highpc += part_die->lowpc;
16769
16770   if (has_low_pc_attr && has_high_pc_attr)
16771     {
16772       /* When using the GNU linker, .gnu.linkonce. sections are used to
16773          eliminate duplicate copies of functions and vtables and such.
16774          The linker will arbitrarily choose one and discard the others.
16775          The AT_*_pc values for such functions refer to local labels in
16776          these sections.  If the section from that file was discarded, the
16777          labels are not in the output, so the relocs get a value of 0.
16778          If this is a discarded function, mark the pc bounds as invalid,
16779          so that GDB will ignore it.  */
16780       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16781         {
16782           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16783
16784           complaint (&symfile_complaints,
16785                      _("DW_AT_low_pc %s is zero "
16786                        "for DIE at 0x%x [in module %s]"),
16787                      paddress (gdbarch, part_die->lowpc),
16788                      to_underlying (part_die->sect_off), objfile_name (objfile));
16789         }
16790       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16791       else if (part_die->lowpc >= part_die->highpc)
16792         {
16793           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16794
16795           complaint (&symfile_complaints,
16796                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16797                        "for DIE at 0x%x [in module %s]"),
16798                      paddress (gdbarch, part_die->lowpc),
16799                      paddress (gdbarch, part_die->highpc),
16800                      to_underlying (part_die->sect_off),
16801                      objfile_name (objfile));
16802         }
16803       else
16804         part_die->has_pc_info = 1;
16805     }
16806
16807   return info_ptr;
16808 }
16809
16810 /* Find a cached partial DIE at OFFSET in CU.  */
16811
16812 static struct partial_die_info *
16813 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16814 {
16815   struct partial_die_info *lookup_die = NULL;
16816   struct partial_die_info part_die;
16817
16818   part_die.sect_off = sect_off;
16819   lookup_die = ((struct partial_die_info *)
16820                 htab_find_with_hash (cu->partial_dies, &part_die,
16821                                      to_underlying (sect_off)));
16822
16823   return lookup_die;
16824 }
16825
16826 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16827    except in the case of .debug_types DIEs which do not reference
16828    outside their CU (they do however referencing other types via
16829    DW_FORM_ref_sig8).  */
16830
16831 static struct partial_die_info *
16832 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16833 {
16834   struct objfile *objfile = cu->objfile;
16835   struct dwarf2_per_cu_data *per_cu = NULL;
16836   struct partial_die_info *pd = NULL;
16837
16838   if (offset_in_dwz == cu->per_cu->is_dwz
16839       && offset_in_cu_p (&cu->header, sect_off))
16840     {
16841       pd = find_partial_die_in_comp_unit (sect_off, cu);
16842       if (pd != NULL)
16843         return pd;
16844       /* We missed recording what we needed.
16845          Load all dies and try again.  */
16846       per_cu = cu->per_cu;
16847     }
16848   else
16849     {
16850       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16851       if (cu->per_cu->is_debug_types)
16852         {
16853           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16854                    " external reference to offset 0x%x [in module %s].\n"),
16855                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16856                  bfd_get_filename (objfile->obfd));
16857         }
16858       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16859                                                  objfile);
16860
16861       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16862         load_partial_comp_unit (per_cu);
16863
16864       per_cu->cu->last_used = 0;
16865       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16866     }
16867
16868   /* If we didn't find it, and not all dies have been loaded,
16869      load them all and try again.  */
16870
16871   if (pd == NULL && per_cu->load_all_dies == 0)
16872     {
16873       per_cu->load_all_dies = 1;
16874
16875       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16876          THIS_CU->cu may already be in use.  So we can't just free it and
16877          replace its DIEs with the ones we read in.  Instead, we leave those
16878          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16879          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16880          set.  */
16881       load_partial_comp_unit (per_cu);
16882
16883       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16884     }
16885
16886   if (pd == NULL)
16887     internal_error (__FILE__, __LINE__,
16888                     _("could not find partial DIE 0x%x "
16889                       "in cache [from module %s]\n"),
16890                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16891   return pd;
16892 }
16893
16894 /* See if we can figure out if the class lives in a namespace.  We do
16895    this by looking for a member function; its demangled name will
16896    contain namespace info, if there is any.  */
16897
16898 static void
16899 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16900                                   struct dwarf2_cu *cu)
16901 {
16902   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16903      what template types look like, because the demangler
16904      frequently doesn't give the same name as the debug info.  We
16905      could fix this by only using the demangled name to get the
16906      prefix (but see comment in read_structure_type).  */
16907
16908   struct partial_die_info *real_pdi;
16909   struct partial_die_info *child_pdi;
16910
16911   /* If this DIE (this DIE's specification, if any) has a parent, then
16912      we should not do this.  We'll prepend the parent's fully qualified
16913      name when we create the partial symbol.  */
16914
16915   real_pdi = struct_pdi;
16916   while (real_pdi->has_specification)
16917     real_pdi = find_partial_die (real_pdi->spec_offset,
16918                                  real_pdi->spec_is_dwz, cu);
16919
16920   if (real_pdi->die_parent != NULL)
16921     return;
16922
16923   for (child_pdi = struct_pdi->die_child;
16924        child_pdi != NULL;
16925        child_pdi = child_pdi->die_sibling)
16926     {
16927       if (child_pdi->tag == DW_TAG_subprogram
16928           && child_pdi->linkage_name != NULL)
16929         {
16930           char *actual_class_name
16931             = language_class_name_from_physname (cu->language_defn,
16932                                                  child_pdi->linkage_name);
16933           if (actual_class_name != NULL)
16934             {
16935               struct_pdi->name
16936                 = ((const char *)
16937                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16938                                   actual_class_name,
16939                                   strlen (actual_class_name)));
16940               xfree (actual_class_name);
16941             }
16942           break;
16943         }
16944     }
16945 }
16946
16947 /* Adjust PART_DIE before generating a symbol for it.  This function
16948    may set the is_external flag or change the DIE's name.  */
16949
16950 static void
16951 fixup_partial_die (struct partial_die_info *part_die,
16952                    struct dwarf2_cu *cu)
16953 {
16954   /* Once we've fixed up a die, there's no point in doing so again.
16955      This also avoids a memory leak if we were to call
16956      guess_partial_die_structure_name multiple times.  */
16957   if (part_die->fixup_called)
16958     return;
16959
16960   /* If we found a reference attribute and the DIE has no name, try
16961      to find a name in the referred to DIE.  */
16962
16963   if (part_die->name == NULL && part_die->has_specification)
16964     {
16965       struct partial_die_info *spec_die;
16966
16967       spec_die = find_partial_die (part_die->spec_offset,
16968                                    part_die->spec_is_dwz, cu);
16969
16970       fixup_partial_die (spec_die, cu);
16971
16972       if (spec_die->name)
16973         {
16974           part_die->name = spec_die->name;
16975
16976           /* Copy DW_AT_external attribute if it is set.  */
16977           if (spec_die->is_external)
16978             part_die->is_external = spec_die->is_external;
16979         }
16980     }
16981
16982   /* Set default names for some unnamed DIEs.  */
16983
16984   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16985     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16986
16987   /* If there is no parent die to provide a namespace, and there are
16988      children, see if we can determine the namespace from their linkage
16989      name.  */
16990   if (cu->language == language_cplus
16991       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16992       && part_die->die_parent == NULL
16993       && part_die->has_children
16994       && (part_die->tag == DW_TAG_class_type
16995           || part_die->tag == DW_TAG_structure_type
16996           || part_die->tag == DW_TAG_union_type))
16997     guess_partial_die_structure_name (part_die, cu);
16998
16999   /* GCC might emit a nameless struct or union that has a linkage
17000      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17001   if (part_die->name == NULL
17002       && (part_die->tag == DW_TAG_class_type
17003           || part_die->tag == DW_TAG_interface_type
17004           || part_die->tag == DW_TAG_structure_type
17005           || part_die->tag == DW_TAG_union_type)
17006       && part_die->linkage_name != NULL)
17007     {
17008       char *demangled;
17009
17010       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
17011       if (demangled)
17012         {
17013           const char *base;
17014
17015           /* Strip any leading namespaces/classes, keep only the base name.
17016              DW_AT_name for named DIEs does not contain the prefixes.  */
17017           base = strrchr (demangled, ':');
17018           if (base && base > demangled && base[-1] == ':')
17019             base++;
17020           else
17021             base = demangled;
17022
17023           part_die->name
17024             = ((const char *)
17025                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17026                               base, strlen (base)));
17027           xfree (demangled);
17028         }
17029     }
17030
17031   part_die->fixup_called = 1;
17032 }
17033
17034 /* Read an attribute value described by an attribute form.  */
17035
17036 static const gdb_byte *
17037 read_attribute_value (const struct die_reader_specs *reader,
17038                       struct attribute *attr, unsigned form,
17039                       LONGEST implicit_const, const gdb_byte *info_ptr)
17040 {
17041   struct dwarf2_cu *cu = reader->cu;
17042   struct objfile *objfile = cu->objfile;
17043   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17044   bfd *abfd = reader->abfd;
17045   struct comp_unit_head *cu_header = &cu->header;
17046   unsigned int bytes_read;
17047   struct dwarf_block *blk;
17048
17049   attr->form = (enum dwarf_form) form;
17050   switch (form)
17051     {
17052     case DW_FORM_ref_addr:
17053       if (cu->header.version == 2)
17054         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17055       else
17056         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17057                                        &cu->header, &bytes_read);
17058       info_ptr += bytes_read;
17059       break;
17060     case DW_FORM_GNU_ref_alt:
17061       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17062       info_ptr += bytes_read;
17063       break;
17064     case DW_FORM_addr:
17065       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17066       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17067       info_ptr += bytes_read;
17068       break;
17069     case DW_FORM_block2:
17070       blk = dwarf_alloc_block (cu);
17071       blk->size = read_2_bytes (abfd, info_ptr);
17072       info_ptr += 2;
17073       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17074       info_ptr += blk->size;
17075       DW_BLOCK (attr) = blk;
17076       break;
17077     case DW_FORM_block4:
17078       blk = dwarf_alloc_block (cu);
17079       blk->size = read_4_bytes (abfd, info_ptr);
17080       info_ptr += 4;
17081       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17082       info_ptr += blk->size;
17083       DW_BLOCK (attr) = blk;
17084       break;
17085     case DW_FORM_data2:
17086       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17087       info_ptr += 2;
17088       break;
17089     case DW_FORM_data4:
17090       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17091       info_ptr += 4;
17092       break;
17093     case DW_FORM_data8:
17094       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17095       info_ptr += 8;
17096       break;
17097     case DW_FORM_data16:
17098       blk = dwarf_alloc_block (cu);
17099       blk->size = 16;
17100       blk->data = read_n_bytes (abfd, info_ptr, 16);
17101       info_ptr += 16;
17102       DW_BLOCK (attr) = blk;
17103       break;
17104     case DW_FORM_sec_offset:
17105       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17106       info_ptr += bytes_read;
17107       break;
17108     case DW_FORM_string:
17109       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17110       DW_STRING_IS_CANONICAL (attr) = 0;
17111       info_ptr += bytes_read;
17112       break;
17113     case DW_FORM_strp:
17114       if (!cu->per_cu->is_dwz)
17115         {
17116           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17117                                                    &bytes_read);
17118           DW_STRING_IS_CANONICAL (attr) = 0;
17119           info_ptr += bytes_read;
17120           break;
17121         }
17122       /* FALLTHROUGH */
17123     case DW_FORM_line_strp:
17124       if (!cu->per_cu->is_dwz)
17125         {
17126           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17127                                                         cu_header, &bytes_read);
17128           DW_STRING_IS_CANONICAL (attr) = 0;
17129           info_ptr += bytes_read;
17130           break;
17131         }
17132       /* FALLTHROUGH */
17133     case DW_FORM_GNU_strp_alt:
17134       {
17135         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17136         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17137                                           &bytes_read);
17138
17139         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17140         DW_STRING_IS_CANONICAL (attr) = 0;
17141         info_ptr += bytes_read;
17142       }
17143       break;
17144     case DW_FORM_exprloc:
17145     case DW_FORM_block:
17146       blk = dwarf_alloc_block (cu);
17147       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17148       info_ptr += bytes_read;
17149       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17150       info_ptr += blk->size;
17151       DW_BLOCK (attr) = blk;
17152       break;
17153     case DW_FORM_block1:
17154       blk = dwarf_alloc_block (cu);
17155       blk->size = read_1_byte (abfd, info_ptr);
17156       info_ptr += 1;
17157       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17158       info_ptr += blk->size;
17159       DW_BLOCK (attr) = blk;
17160       break;
17161     case DW_FORM_data1:
17162       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17163       info_ptr += 1;
17164       break;
17165     case DW_FORM_flag:
17166       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17167       info_ptr += 1;
17168       break;
17169     case DW_FORM_flag_present:
17170       DW_UNSND (attr) = 1;
17171       break;
17172     case DW_FORM_sdata:
17173       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17174       info_ptr += bytes_read;
17175       break;
17176     case DW_FORM_udata:
17177       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17178       info_ptr += bytes_read;
17179       break;
17180     case DW_FORM_ref1:
17181       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17182                          + read_1_byte (abfd, info_ptr));
17183       info_ptr += 1;
17184       break;
17185     case DW_FORM_ref2:
17186       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17187                          + read_2_bytes (abfd, info_ptr));
17188       info_ptr += 2;
17189       break;
17190     case DW_FORM_ref4:
17191       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17192                          + read_4_bytes (abfd, info_ptr));
17193       info_ptr += 4;
17194       break;
17195     case DW_FORM_ref8:
17196       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17197                          + read_8_bytes (abfd, info_ptr));
17198       info_ptr += 8;
17199       break;
17200     case DW_FORM_ref_sig8:
17201       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17202       info_ptr += 8;
17203       break;
17204     case DW_FORM_ref_udata:
17205       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17206                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17207       info_ptr += bytes_read;
17208       break;
17209     case DW_FORM_indirect:
17210       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17211       info_ptr += bytes_read;
17212       if (form == DW_FORM_implicit_const)
17213         {
17214           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17215           info_ptr += bytes_read;
17216         }
17217       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17218                                        info_ptr);
17219       break;
17220     case DW_FORM_implicit_const:
17221       DW_SND (attr) = implicit_const;
17222       break;
17223     case DW_FORM_GNU_addr_index:
17224       if (reader->dwo_file == NULL)
17225         {
17226           /* For now flag a hard error.
17227              Later we can turn this into a complaint.  */
17228           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17229                  dwarf_form_name (form),
17230                  bfd_get_filename (abfd));
17231         }
17232       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17233       info_ptr += bytes_read;
17234       break;
17235     case DW_FORM_GNU_str_index:
17236       if (reader->dwo_file == NULL)
17237         {
17238           /* For now flag a hard error.
17239              Later we can turn this into a complaint if warranted.  */
17240           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17241                  dwarf_form_name (form),
17242                  bfd_get_filename (abfd));
17243         }
17244       {
17245         ULONGEST str_index =
17246           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17247
17248         DW_STRING (attr) = read_str_index (reader, str_index);
17249         DW_STRING_IS_CANONICAL (attr) = 0;
17250         info_ptr += bytes_read;
17251       }
17252       break;
17253     default:
17254       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17255              dwarf_form_name (form),
17256              bfd_get_filename (abfd));
17257     }
17258
17259   /* Super hack.  */
17260   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17261     attr->form = DW_FORM_GNU_ref_alt;
17262
17263   /* We have seen instances where the compiler tried to emit a byte
17264      size attribute of -1 which ended up being encoded as an unsigned
17265      0xffffffff.  Although 0xffffffff is technically a valid size value,
17266      an object of this size seems pretty unlikely so we can relatively
17267      safely treat these cases as if the size attribute was invalid and
17268      treat them as zero by default.  */
17269   if (attr->name == DW_AT_byte_size
17270       && form == DW_FORM_data4
17271       && DW_UNSND (attr) >= 0xffffffff)
17272     {
17273       complaint
17274         (&symfile_complaints,
17275          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17276          hex_string (DW_UNSND (attr)));
17277       DW_UNSND (attr) = 0;
17278     }
17279
17280   return info_ptr;
17281 }
17282
17283 /* Read an attribute described by an abbreviated attribute.  */
17284
17285 static const gdb_byte *
17286 read_attribute (const struct die_reader_specs *reader,
17287                 struct attribute *attr, struct attr_abbrev *abbrev,
17288                 const gdb_byte *info_ptr)
17289 {
17290   attr->name = abbrev->name;
17291   return read_attribute_value (reader, attr, abbrev->form,
17292                                abbrev->implicit_const, info_ptr);
17293 }
17294
17295 /* Read dwarf information from a buffer.  */
17296
17297 static unsigned int
17298 read_1_byte (bfd *abfd, const gdb_byte *buf)
17299 {
17300   return bfd_get_8 (abfd, buf);
17301 }
17302
17303 static int
17304 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17305 {
17306   return bfd_get_signed_8 (abfd, buf);
17307 }
17308
17309 static unsigned int
17310 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17311 {
17312   return bfd_get_16 (abfd, buf);
17313 }
17314
17315 static int
17316 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17317 {
17318   return bfd_get_signed_16 (abfd, buf);
17319 }
17320
17321 static unsigned int
17322 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17323 {
17324   return bfd_get_32 (abfd, buf);
17325 }
17326
17327 static int
17328 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17329 {
17330   return bfd_get_signed_32 (abfd, buf);
17331 }
17332
17333 static ULONGEST
17334 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17335 {
17336   return bfd_get_64 (abfd, buf);
17337 }
17338
17339 static CORE_ADDR
17340 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17341               unsigned int *bytes_read)
17342 {
17343   struct comp_unit_head *cu_header = &cu->header;
17344   CORE_ADDR retval = 0;
17345
17346   if (cu_header->signed_addr_p)
17347     {
17348       switch (cu_header->addr_size)
17349         {
17350         case 2:
17351           retval = bfd_get_signed_16 (abfd, buf);
17352           break;
17353         case 4:
17354           retval = bfd_get_signed_32 (abfd, buf);
17355           break;
17356         case 8:
17357           retval = bfd_get_signed_64 (abfd, buf);
17358           break;
17359         default:
17360           internal_error (__FILE__, __LINE__,
17361                           _("read_address: bad switch, signed [in module %s]"),
17362                           bfd_get_filename (abfd));
17363         }
17364     }
17365   else
17366     {
17367       switch (cu_header->addr_size)
17368         {
17369         case 2:
17370           retval = bfd_get_16 (abfd, buf);
17371           break;
17372         case 4:
17373           retval = bfd_get_32 (abfd, buf);
17374           break;
17375         case 8:
17376           retval = bfd_get_64 (abfd, buf);
17377           break;
17378         default:
17379           internal_error (__FILE__, __LINE__,
17380                           _("read_address: bad switch, "
17381                             "unsigned [in module %s]"),
17382                           bfd_get_filename (abfd));
17383         }
17384     }
17385
17386   *bytes_read = cu_header->addr_size;
17387   return retval;
17388 }
17389
17390 /* Read the initial length from a section.  The (draft) DWARF 3
17391    specification allows the initial length to take up either 4 bytes
17392    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17393    bytes describe the length and all offsets will be 8 bytes in length
17394    instead of 4.
17395
17396    An older, non-standard 64-bit format is also handled by this
17397    function.  The older format in question stores the initial length
17398    as an 8-byte quantity without an escape value.  Lengths greater
17399    than 2^32 aren't very common which means that the initial 4 bytes
17400    is almost always zero.  Since a length value of zero doesn't make
17401    sense for the 32-bit format, this initial zero can be considered to
17402    be an escape value which indicates the presence of the older 64-bit
17403    format.  As written, the code can't detect (old format) lengths
17404    greater than 4GB.  If it becomes necessary to handle lengths
17405    somewhat larger than 4GB, we could allow other small values (such
17406    as the non-sensical values of 1, 2, and 3) to also be used as
17407    escape values indicating the presence of the old format.
17408
17409    The value returned via bytes_read should be used to increment the
17410    relevant pointer after calling read_initial_length().
17411
17412    [ Note:  read_initial_length() and read_offset() are based on the
17413      document entitled "DWARF Debugging Information Format", revision
17414      3, draft 8, dated November 19, 2001.  This document was obtained
17415      from:
17416
17417         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17418
17419      This document is only a draft and is subject to change.  (So beware.)
17420
17421      Details regarding the older, non-standard 64-bit format were
17422      determined empirically by examining 64-bit ELF files produced by
17423      the SGI toolchain on an IRIX 6.5 machine.
17424
17425      - Kevin, July 16, 2002
17426    ] */
17427
17428 static LONGEST
17429 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17430 {
17431   LONGEST length = bfd_get_32 (abfd, buf);
17432
17433   if (length == 0xffffffff)
17434     {
17435       length = bfd_get_64 (abfd, buf + 4);
17436       *bytes_read = 12;
17437     }
17438   else if (length == 0)
17439     {
17440       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17441       length = bfd_get_64 (abfd, buf);
17442       *bytes_read = 8;
17443     }
17444   else
17445     {
17446       *bytes_read = 4;
17447     }
17448
17449   return length;
17450 }
17451
17452 /* Cover function for read_initial_length.
17453    Returns the length of the object at BUF, and stores the size of the
17454    initial length in *BYTES_READ and stores the size that offsets will be in
17455    *OFFSET_SIZE.
17456    If the initial length size is not equivalent to that specified in
17457    CU_HEADER then issue a complaint.
17458    This is useful when reading non-comp-unit headers.  */
17459
17460 static LONGEST
17461 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17462                                         const struct comp_unit_head *cu_header,
17463                                         unsigned int *bytes_read,
17464                                         unsigned int *offset_size)
17465 {
17466   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17467
17468   gdb_assert (cu_header->initial_length_size == 4
17469               || cu_header->initial_length_size == 8
17470               || cu_header->initial_length_size == 12);
17471
17472   if (cu_header->initial_length_size != *bytes_read)
17473     complaint (&symfile_complaints,
17474                _("intermixed 32-bit and 64-bit DWARF sections"));
17475
17476   *offset_size = (*bytes_read == 4) ? 4 : 8;
17477   return length;
17478 }
17479
17480 /* Read an offset from the data stream.  The size of the offset is
17481    given by cu_header->offset_size.  */
17482
17483 static LONGEST
17484 read_offset (bfd *abfd, const gdb_byte *buf,
17485              const struct comp_unit_head *cu_header,
17486              unsigned int *bytes_read)
17487 {
17488   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17489
17490   *bytes_read = cu_header->offset_size;
17491   return offset;
17492 }
17493
17494 /* Read an offset from the data stream.  */
17495
17496 static LONGEST
17497 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17498 {
17499   LONGEST retval = 0;
17500
17501   switch (offset_size)
17502     {
17503     case 4:
17504       retval = bfd_get_32 (abfd, buf);
17505       break;
17506     case 8:
17507       retval = bfd_get_64 (abfd, buf);
17508       break;
17509     default:
17510       internal_error (__FILE__, __LINE__,
17511                       _("read_offset_1: bad switch [in module %s]"),
17512                       bfd_get_filename (abfd));
17513     }
17514
17515   return retval;
17516 }
17517
17518 static const gdb_byte *
17519 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17520 {
17521   /* If the size of a host char is 8 bits, we can return a pointer
17522      to the buffer, otherwise we have to copy the data to a buffer
17523      allocated on the temporary obstack.  */
17524   gdb_assert (HOST_CHAR_BIT == 8);
17525   return buf;
17526 }
17527
17528 static const char *
17529 read_direct_string (bfd *abfd, const gdb_byte *buf,
17530                     unsigned int *bytes_read_ptr)
17531 {
17532   /* If the size of a host char is 8 bits, we can return a pointer
17533      to the string, otherwise we have to copy the string to a buffer
17534      allocated on the temporary obstack.  */
17535   gdb_assert (HOST_CHAR_BIT == 8);
17536   if (*buf == '\0')
17537     {
17538       *bytes_read_ptr = 1;
17539       return NULL;
17540     }
17541   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17542   return (const char *) buf;
17543 }
17544
17545 /* Return pointer to string at section SECT offset STR_OFFSET with error
17546    reporting strings FORM_NAME and SECT_NAME.  */
17547
17548 static const char *
17549 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17550                                      struct dwarf2_section_info *sect,
17551                                      const char *form_name,
17552                                      const char *sect_name)
17553 {
17554   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17555   if (sect->buffer == NULL)
17556     error (_("%s used without %s section [in module %s]"),
17557            form_name, sect_name, bfd_get_filename (abfd));
17558   if (str_offset >= sect->size)
17559     error (_("%s pointing outside of %s section [in module %s]"),
17560            form_name, sect_name, bfd_get_filename (abfd));
17561   gdb_assert (HOST_CHAR_BIT == 8);
17562   if (sect->buffer[str_offset] == '\0')
17563     return NULL;
17564   return (const char *) (sect->buffer + str_offset);
17565 }
17566
17567 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17568
17569 static const char *
17570 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17571 {
17572   return read_indirect_string_at_offset_from (abfd, str_offset,
17573                                               &dwarf2_per_objfile->str,
17574                                               "DW_FORM_strp", ".debug_str");
17575 }
17576
17577 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17578
17579 static const char *
17580 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17581 {
17582   return read_indirect_string_at_offset_from (abfd, str_offset,
17583                                               &dwarf2_per_objfile->line_str,
17584                                               "DW_FORM_line_strp",
17585                                               ".debug_line_str");
17586 }
17587
17588 /* Read a string at offset STR_OFFSET in the .debug_str section from
17589    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17590    the string consists of a single NUL byte, return NULL; otherwise
17591    return a pointer to the string.  */
17592
17593 static const char *
17594 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17595 {
17596   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17597
17598   if (dwz->str.buffer == NULL)
17599     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17600              "section [in module %s]"),
17601            bfd_get_filename (dwz->dwz_bfd));
17602   if (str_offset >= dwz->str.size)
17603     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17604              ".debug_str section [in module %s]"),
17605            bfd_get_filename (dwz->dwz_bfd));
17606   gdb_assert (HOST_CHAR_BIT == 8);
17607   if (dwz->str.buffer[str_offset] == '\0')
17608     return NULL;
17609   return (const char *) (dwz->str.buffer + str_offset);
17610 }
17611
17612 /* Return pointer to string at .debug_str offset as read from BUF.
17613    BUF is assumed to be in a compilation unit described by CU_HEADER.
17614    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17615
17616 static const char *
17617 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17618                       const struct comp_unit_head *cu_header,
17619                       unsigned int *bytes_read_ptr)
17620 {
17621   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17622
17623   return read_indirect_string_at_offset (abfd, str_offset);
17624 }
17625
17626 /* Return pointer to string at .debug_line_str offset as read from BUF.
17627    BUF is assumed to be in a compilation unit described by CU_HEADER.
17628    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17629
17630 static const char *
17631 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17632                            const struct comp_unit_head *cu_header,
17633                            unsigned int *bytes_read_ptr)
17634 {
17635   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17636
17637   return read_indirect_line_string_at_offset (abfd, str_offset);
17638 }
17639
17640 ULONGEST
17641 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17642                           unsigned int *bytes_read_ptr)
17643 {
17644   ULONGEST result;
17645   unsigned int num_read;
17646   int shift;
17647   unsigned char byte;
17648
17649   result = 0;
17650   shift = 0;
17651   num_read = 0;
17652   while (1)
17653     {
17654       byte = bfd_get_8 (abfd, buf);
17655       buf++;
17656       num_read++;
17657       result |= ((ULONGEST) (byte & 127) << shift);
17658       if ((byte & 128) == 0)
17659         {
17660           break;
17661         }
17662       shift += 7;
17663     }
17664   *bytes_read_ptr = num_read;
17665   return result;
17666 }
17667
17668 static LONGEST
17669 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17670                     unsigned int *bytes_read_ptr)
17671 {
17672   LONGEST result;
17673   int shift, num_read;
17674   unsigned char byte;
17675
17676   result = 0;
17677   shift = 0;
17678   num_read = 0;
17679   while (1)
17680     {
17681       byte = bfd_get_8 (abfd, buf);
17682       buf++;
17683       num_read++;
17684       result |= ((LONGEST) (byte & 127) << shift);
17685       shift += 7;
17686       if ((byte & 128) == 0)
17687         {
17688           break;
17689         }
17690     }
17691   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17692     result |= -(((LONGEST) 1) << shift);
17693   *bytes_read_ptr = num_read;
17694   return result;
17695 }
17696
17697 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17698    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17699    ADDR_SIZE is the size of addresses from the CU header.  */
17700
17701 static CORE_ADDR
17702 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17703 {
17704   struct objfile *objfile = dwarf2_per_objfile->objfile;
17705   bfd *abfd = objfile->obfd;
17706   const gdb_byte *info_ptr;
17707
17708   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17709   if (dwarf2_per_objfile->addr.buffer == NULL)
17710     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17711            objfile_name (objfile));
17712   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17713     error (_("DW_FORM_addr_index pointing outside of "
17714              ".debug_addr section [in module %s]"),
17715            objfile_name (objfile));
17716   info_ptr = (dwarf2_per_objfile->addr.buffer
17717               + addr_base + addr_index * addr_size);
17718   if (addr_size == 4)
17719     return bfd_get_32 (abfd, info_ptr);
17720   else
17721     return bfd_get_64 (abfd, info_ptr);
17722 }
17723
17724 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17725
17726 static CORE_ADDR
17727 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17728 {
17729   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17730 }
17731
17732 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17733
17734 static CORE_ADDR
17735 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17736                              unsigned int *bytes_read)
17737 {
17738   bfd *abfd = cu->objfile->obfd;
17739   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17740
17741   return read_addr_index (cu, addr_index);
17742 }
17743
17744 /* Data structure to pass results from dwarf2_read_addr_index_reader
17745    back to dwarf2_read_addr_index.  */
17746
17747 struct dwarf2_read_addr_index_data
17748 {
17749   ULONGEST addr_base;
17750   int addr_size;
17751 };
17752
17753 /* die_reader_func for dwarf2_read_addr_index.  */
17754
17755 static void
17756 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17757                                const gdb_byte *info_ptr,
17758                                struct die_info *comp_unit_die,
17759                                int has_children,
17760                                void *data)
17761 {
17762   struct dwarf2_cu *cu = reader->cu;
17763   struct dwarf2_read_addr_index_data *aidata =
17764     (struct dwarf2_read_addr_index_data *) data;
17765
17766   aidata->addr_base = cu->addr_base;
17767   aidata->addr_size = cu->header.addr_size;
17768 }
17769
17770 /* Given an index in .debug_addr, fetch the value.
17771    NOTE: This can be called during dwarf expression evaluation,
17772    long after the debug information has been read, and thus per_cu->cu
17773    may no longer exist.  */
17774
17775 CORE_ADDR
17776 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17777                         unsigned int addr_index)
17778 {
17779   struct objfile *objfile = per_cu->objfile;
17780   struct dwarf2_cu *cu = per_cu->cu;
17781   ULONGEST addr_base;
17782   int addr_size;
17783
17784   /* This is intended to be called from outside this file.  */
17785   dw2_setup (objfile);
17786
17787   /* We need addr_base and addr_size.
17788      If we don't have PER_CU->cu, we have to get it.
17789      Nasty, but the alternative is storing the needed info in PER_CU,
17790      which at this point doesn't seem justified: it's not clear how frequently
17791      it would get used and it would increase the size of every PER_CU.
17792      Entry points like dwarf2_per_cu_addr_size do a similar thing
17793      so we're not in uncharted territory here.
17794      Alas we need to be a bit more complicated as addr_base is contained
17795      in the DIE.
17796
17797      We don't need to read the entire CU(/TU).
17798      We just need the header and top level die.
17799
17800      IWBN to use the aging mechanism to let us lazily later discard the CU.
17801      For now we skip this optimization.  */
17802
17803   if (cu != NULL)
17804     {
17805       addr_base = cu->addr_base;
17806       addr_size = cu->header.addr_size;
17807     }
17808   else
17809     {
17810       struct dwarf2_read_addr_index_data aidata;
17811
17812       /* Note: We can't use init_cutu_and_read_dies_simple here,
17813          we need addr_base.  */
17814       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17815                                dwarf2_read_addr_index_reader, &aidata);
17816       addr_base = aidata.addr_base;
17817       addr_size = aidata.addr_size;
17818     }
17819
17820   return read_addr_index_1 (addr_index, addr_base, addr_size);
17821 }
17822
17823 /* Given a DW_FORM_GNU_str_index, fetch the string.
17824    This is only used by the Fission support.  */
17825
17826 static const char *
17827 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17828 {
17829   struct objfile *objfile = dwarf2_per_objfile->objfile;
17830   const char *objf_name = objfile_name (objfile);
17831   bfd *abfd = objfile->obfd;
17832   struct dwarf2_cu *cu = reader->cu;
17833   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17834   struct dwarf2_section_info *str_offsets_section =
17835     &reader->dwo_file->sections.str_offsets;
17836   const gdb_byte *info_ptr;
17837   ULONGEST str_offset;
17838   static const char form_name[] = "DW_FORM_GNU_str_index";
17839
17840   dwarf2_read_section (objfile, str_section);
17841   dwarf2_read_section (objfile, str_offsets_section);
17842   if (str_section->buffer == NULL)
17843     error (_("%s used without .debug_str.dwo section"
17844              " in CU at offset 0x%x [in module %s]"),
17845            form_name, to_underlying (cu->header.sect_off), objf_name);
17846   if (str_offsets_section->buffer == NULL)
17847     error (_("%s used without .debug_str_offsets.dwo section"
17848              " in CU at offset 0x%x [in module %s]"),
17849            form_name, to_underlying (cu->header.sect_off), objf_name);
17850   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17851     error (_("%s pointing outside of .debug_str_offsets.dwo"
17852              " section in CU at offset 0x%x [in module %s]"),
17853            form_name, to_underlying (cu->header.sect_off), objf_name);
17854   info_ptr = (str_offsets_section->buffer
17855               + str_index * cu->header.offset_size);
17856   if (cu->header.offset_size == 4)
17857     str_offset = bfd_get_32 (abfd, info_ptr);
17858   else
17859     str_offset = bfd_get_64 (abfd, info_ptr);
17860   if (str_offset >= str_section->size)
17861     error (_("Offset from %s pointing outside of"
17862              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17863            form_name, to_underlying (cu->header.sect_off), objf_name);
17864   return (const char *) (str_section->buffer + str_offset);
17865 }
17866
17867 /* Return the length of an LEB128 number in BUF.  */
17868
17869 static int
17870 leb128_size (const gdb_byte *buf)
17871 {
17872   const gdb_byte *begin = buf;
17873   gdb_byte byte;
17874
17875   while (1)
17876     {
17877       byte = *buf++;
17878       if ((byte & 128) == 0)
17879         return buf - begin;
17880     }
17881 }
17882
17883 static void
17884 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17885 {
17886   switch (lang)
17887     {
17888     case DW_LANG_C89:
17889     case DW_LANG_C99:
17890     case DW_LANG_C11:
17891     case DW_LANG_C:
17892     case DW_LANG_UPC:
17893       cu->language = language_c;
17894       break;
17895     case DW_LANG_Java:
17896     case DW_LANG_C_plus_plus:
17897     case DW_LANG_C_plus_plus_11:
17898     case DW_LANG_C_plus_plus_14:
17899       cu->language = language_cplus;
17900       break;
17901     case DW_LANG_D:
17902       cu->language = language_d;
17903       break;
17904     case DW_LANG_Fortran77:
17905     case DW_LANG_Fortran90:
17906     case DW_LANG_Fortran95:
17907     case DW_LANG_Fortran03:
17908     case DW_LANG_Fortran08:
17909       cu->language = language_fortran;
17910       break;
17911     case DW_LANG_Go:
17912       cu->language = language_go;
17913       break;
17914     case DW_LANG_Mips_Assembler:
17915       cu->language = language_asm;
17916       break;
17917     case DW_LANG_Ada83:
17918     case DW_LANG_Ada95:
17919       cu->language = language_ada;
17920       break;
17921     case DW_LANG_Modula2:
17922       cu->language = language_m2;
17923       break;
17924     case DW_LANG_Pascal83:
17925       cu->language = language_pascal;
17926       break;
17927     case DW_LANG_ObjC:
17928       cu->language = language_objc;
17929       break;
17930     case DW_LANG_Rust:
17931     case DW_LANG_Rust_old:
17932       cu->language = language_rust;
17933       break;
17934     case DW_LANG_Cobol74:
17935     case DW_LANG_Cobol85:
17936     default:
17937       cu->language = language_minimal;
17938       break;
17939     }
17940   cu->language_defn = language_def (cu->language);
17941 }
17942
17943 /* Return the named attribute or NULL if not there.  */
17944
17945 static struct attribute *
17946 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17947 {
17948   for (;;)
17949     {
17950       unsigned int i;
17951       struct attribute *spec = NULL;
17952
17953       for (i = 0; i < die->num_attrs; ++i)
17954         {
17955           if (die->attrs[i].name == name)
17956             return &die->attrs[i];
17957           if (die->attrs[i].name == DW_AT_specification
17958               || die->attrs[i].name == DW_AT_abstract_origin)
17959             spec = &die->attrs[i];
17960         }
17961
17962       if (!spec)
17963         break;
17964
17965       die = follow_die_ref (die, spec, &cu);
17966     }
17967
17968   return NULL;
17969 }
17970
17971 /* Return the named attribute or NULL if not there,
17972    but do not follow DW_AT_specification, etc.
17973    This is for use in contexts where we're reading .debug_types dies.
17974    Following DW_AT_specification, DW_AT_abstract_origin will take us
17975    back up the chain, and we want to go down.  */
17976
17977 static struct attribute *
17978 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17979 {
17980   unsigned int i;
17981
17982   for (i = 0; i < die->num_attrs; ++i)
17983     if (die->attrs[i].name == name)
17984       return &die->attrs[i];
17985
17986   return NULL;
17987 }
17988
17989 /* Return the string associated with a string-typed attribute, or NULL if it
17990    is either not found or is of an incorrect type.  */
17991
17992 static const char *
17993 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17994 {
17995   struct attribute *attr;
17996   const char *str = NULL;
17997
17998   attr = dwarf2_attr (die, name, cu);
17999
18000   if (attr != NULL)
18001     {
18002       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
18003           || attr->form == DW_FORM_string
18004           || attr->form == DW_FORM_GNU_str_index
18005           || attr->form == DW_FORM_GNU_strp_alt)
18006         str = DW_STRING (attr);
18007       else
18008         complaint (&symfile_complaints,
18009                    _("string type expected for attribute %s for "
18010                      "DIE at 0x%x in module %s"),
18011                    dwarf_attr_name (name), to_underlying (die->sect_off),
18012                    objfile_name (cu->objfile));
18013     }
18014
18015   return str;
18016 }
18017
18018 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18019    and holds a non-zero value.  This function should only be used for
18020    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18021
18022 static int
18023 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18024 {
18025   struct attribute *attr = dwarf2_attr (die, name, cu);
18026
18027   return (attr && DW_UNSND (attr));
18028 }
18029
18030 static int
18031 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18032 {
18033   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18034      which value is non-zero.  However, we have to be careful with
18035      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18036      (via dwarf2_flag_true_p) follows this attribute.  So we may
18037      end up accidently finding a declaration attribute that belongs
18038      to a different DIE referenced by the specification attribute,
18039      even though the given DIE does not have a declaration attribute.  */
18040   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18041           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18042 }
18043
18044 /* Return the die giving the specification for DIE, if there is
18045    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18046    containing the return value on output.  If there is no
18047    specification, but there is an abstract origin, that is
18048    returned.  */
18049
18050 static struct die_info *
18051 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18052 {
18053   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18054                                              *spec_cu);
18055
18056   if (spec_attr == NULL)
18057     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18058
18059   if (spec_attr == NULL)
18060     return NULL;
18061   else
18062     return follow_die_ref (die, spec_attr, spec_cu);
18063 }
18064
18065 /* Stub for free_line_header to match void * callback types.  */
18066
18067 static void
18068 free_line_header_voidp (void *arg)
18069 {
18070   struct line_header *lh = (struct line_header *) arg;
18071
18072   delete lh;
18073 }
18074
18075 void
18076 line_header::add_include_dir (const char *include_dir)
18077 {
18078   if (dwarf_line_debug >= 2)
18079     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18080                         include_dirs.size () + 1, include_dir);
18081
18082   include_dirs.push_back (include_dir);
18083 }
18084
18085 void
18086 line_header::add_file_name (const char *name,
18087                             dir_index d_index,
18088                             unsigned int mod_time,
18089                             unsigned int length)
18090 {
18091   if (dwarf_line_debug >= 2)
18092     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18093                         (unsigned) file_names.size () + 1, name);
18094
18095   file_names.emplace_back (name, d_index, mod_time, length);
18096 }
18097
18098 /* A convenience function to find the proper .debug_line section for a CU.  */
18099
18100 static struct dwarf2_section_info *
18101 get_debug_line_section (struct dwarf2_cu *cu)
18102 {
18103   struct dwarf2_section_info *section;
18104
18105   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18106      DWO file.  */
18107   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18108     section = &cu->dwo_unit->dwo_file->sections.line;
18109   else if (cu->per_cu->is_dwz)
18110     {
18111       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18112
18113       section = &dwz->line;
18114     }
18115   else
18116     section = &dwarf2_per_objfile->line;
18117
18118   return section;
18119 }
18120
18121 /* Read directory or file name entry format, starting with byte of
18122    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18123    entries count and the entries themselves in the described entry
18124    format.  */
18125
18126 static void
18127 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18128                         struct line_header *lh,
18129                         const struct comp_unit_head *cu_header,
18130                         void (*callback) (struct line_header *lh,
18131                                           const char *name,
18132                                           dir_index d_index,
18133                                           unsigned int mod_time,
18134                                           unsigned int length))
18135 {
18136   gdb_byte format_count, formati;
18137   ULONGEST data_count, datai;
18138   const gdb_byte *buf = *bufp;
18139   const gdb_byte *format_header_data;
18140   int i;
18141   unsigned int bytes_read;
18142
18143   format_count = read_1_byte (abfd, buf);
18144   buf += 1;
18145   format_header_data = buf;
18146   for (formati = 0; formati < format_count; formati++)
18147     {
18148       read_unsigned_leb128 (abfd, buf, &bytes_read);
18149       buf += bytes_read;
18150       read_unsigned_leb128 (abfd, buf, &bytes_read);
18151       buf += bytes_read;
18152     }
18153
18154   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18155   buf += bytes_read;
18156   for (datai = 0; datai < data_count; datai++)
18157     {
18158       const gdb_byte *format = format_header_data;
18159       struct file_entry fe;
18160
18161       for (formati = 0; formati < format_count; formati++)
18162         {
18163           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18164           format += bytes_read;
18165
18166           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18167           format += bytes_read;
18168
18169           gdb::optional<const char *> string;
18170           gdb::optional<unsigned int> uint;
18171
18172           switch (form)
18173             {
18174             case DW_FORM_string:
18175               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18176               buf += bytes_read;
18177               break;
18178
18179             case DW_FORM_line_strp:
18180               string.emplace (read_indirect_line_string (abfd, buf,
18181                                                          cu_header,
18182                                                          &bytes_read));
18183               buf += bytes_read;
18184               break;
18185
18186             case DW_FORM_data1:
18187               uint.emplace (read_1_byte (abfd, buf));
18188               buf += 1;
18189               break;
18190
18191             case DW_FORM_data2:
18192               uint.emplace (read_2_bytes (abfd, buf));
18193               buf += 2;
18194               break;
18195
18196             case DW_FORM_data4:
18197               uint.emplace (read_4_bytes (abfd, buf));
18198               buf += 4;
18199               break;
18200
18201             case DW_FORM_data8:
18202               uint.emplace (read_8_bytes (abfd, buf));
18203               buf += 8;
18204               break;
18205
18206             case DW_FORM_udata:
18207               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18208               buf += bytes_read;
18209               break;
18210
18211             case DW_FORM_block:
18212               /* It is valid only for DW_LNCT_timestamp which is ignored by
18213                  current GDB.  */
18214               break;
18215             }
18216
18217           switch (content_type)
18218             {
18219             case DW_LNCT_path:
18220               if (string.has_value ())
18221                 fe.name = *string;
18222               break;
18223             case DW_LNCT_directory_index:
18224               if (uint.has_value ())
18225                 fe.d_index = (dir_index) *uint;
18226               break;
18227             case DW_LNCT_timestamp:
18228               if (uint.has_value ())
18229                 fe.mod_time = *uint;
18230               break;
18231             case DW_LNCT_size:
18232               if (uint.has_value ())
18233                 fe.length = *uint;
18234               break;
18235             case DW_LNCT_MD5:
18236               break;
18237             default:
18238               complaint (&symfile_complaints,
18239                          _("Unknown format content type %s"),
18240                          pulongest (content_type));
18241             }
18242         }
18243
18244       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18245     }
18246
18247   *bufp = buf;
18248 }
18249
18250 /* Read the statement program header starting at OFFSET in
18251    .debug_line, or .debug_line.dwo.  Return a pointer
18252    to a struct line_header, allocated using xmalloc.
18253    Returns NULL if there is a problem reading the header, e.g., if it
18254    has a version we don't understand.
18255
18256    NOTE: the strings in the include directory and file name tables of
18257    the returned object point into the dwarf line section buffer,
18258    and must not be freed.  */
18259
18260 static line_header_up
18261 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18262 {
18263   const gdb_byte *line_ptr;
18264   unsigned int bytes_read, offset_size;
18265   int i;
18266   const char *cur_dir, *cur_file;
18267   struct dwarf2_section_info *section;
18268   bfd *abfd;
18269
18270   section = get_debug_line_section (cu);
18271   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18272   if (section->buffer == NULL)
18273     {
18274       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18275         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18276       else
18277         complaint (&symfile_complaints, _("missing .debug_line section"));
18278       return 0;
18279     }
18280
18281   /* We can't do this until we know the section is non-empty.
18282      Only then do we know we have such a section.  */
18283   abfd = get_section_bfd_owner (section);
18284
18285   /* Make sure that at least there's room for the total_length field.
18286      That could be 12 bytes long, but we're just going to fudge that.  */
18287   if (to_underlying (sect_off) + 4 >= section->size)
18288     {
18289       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18290       return 0;
18291     }
18292
18293   line_header_up lh (new line_header ());
18294
18295   lh->sect_off = sect_off;
18296   lh->offset_in_dwz = cu->per_cu->is_dwz;
18297
18298   line_ptr = section->buffer + to_underlying (sect_off);
18299
18300   /* Read in the header.  */
18301   lh->total_length =
18302     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18303                                             &bytes_read, &offset_size);
18304   line_ptr += bytes_read;
18305   if (line_ptr + lh->total_length > (section->buffer + section->size))
18306     {
18307       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18308       return 0;
18309     }
18310   lh->statement_program_end = line_ptr + lh->total_length;
18311   lh->version = read_2_bytes (abfd, line_ptr);
18312   line_ptr += 2;
18313   if (lh->version > 5)
18314     {
18315       /* This is a version we don't understand.  The format could have
18316          changed in ways we don't handle properly so just punt.  */
18317       complaint (&symfile_complaints,
18318                  _("unsupported version in .debug_line section"));
18319       return NULL;
18320     }
18321   if (lh->version >= 5)
18322     {
18323       gdb_byte segment_selector_size;
18324
18325       /* Skip address size.  */
18326       read_1_byte (abfd, line_ptr);
18327       line_ptr += 1;
18328
18329       segment_selector_size = read_1_byte (abfd, line_ptr);
18330       line_ptr += 1;
18331       if (segment_selector_size != 0)
18332         {
18333           complaint (&symfile_complaints,
18334                      _("unsupported segment selector size %u "
18335                        "in .debug_line section"),
18336                      segment_selector_size);
18337           return NULL;
18338         }
18339     }
18340   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18341   line_ptr += offset_size;
18342   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18343   line_ptr += 1;
18344   if (lh->version >= 4)
18345     {
18346       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18347       line_ptr += 1;
18348     }
18349   else
18350     lh->maximum_ops_per_instruction = 1;
18351
18352   if (lh->maximum_ops_per_instruction == 0)
18353     {
18354       lh->maximum_ops_per_instruction = 1;
18355       complaint (&symfile_complaints,
18356                  _("invalid maximum_ops_per_instruction "
18357                    "in `.debug_line' section"));
18358     }
18359
18360   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18361   line_ptr += 1;
18362   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18363   line_ptr += 1;
18364   lh->line_range = read_1_byte (abfd, line_ptr);
18365   line_ptr += 1;
18366   lh->opcode_base = read_1_byte (abfd, line_ptr);
18367   line_ptr += 1;
18368   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18369
18370   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18371   for (i = 1; i < lh->opcode_base; ++i)
18372     {
18373       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18374       line_ptr += 1;
18375     }
18376
18377   if (lh->version >= 5)
18378     {
18379       /* Read directory table.  */
18380       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18381                               [] (struct line_header *lh, const char *name,
18382                                   dir_index d_index, unsigned int mod_time,
18383                                   unsigned int length)
18384         {
18385           lh->add_include_dir (name);
18386         });
18387
18388       /* Read file name table.  */
18389       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18390                               [] (struct line_header *lh, const char *name,
18391                                   dir_index d_index, unsigned int mod_time,
18392                                   unsigned int length)
18393         {
18394           lh->add_file_name (name, d_index, mod_time, length);
18395         });
18396     }
18397   else
18398     {
18399       /* Read directory table.  */
18400       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18401         {
18402           line_ptr += bytes_read;
18403           lh->add_include_dir (cur_dir);
18404         }
18405       line_ptr += bytes_read;
18406
18407       /* Read file name table.  */
18408       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18409         {
18410           unsigned int mod_time, length;
18411           dir_index d_index;
18412
18413           line_ptr += bytes_read;
18414           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18415           line_ptr += bytes_read;
18416           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18417           line_ptr += bytes_read;
18418           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18419           line_ptr += bytes_read;
18420
18421           lh->add_file_name (cur_file, d_index, mod_time, length);
18422         }
18423       line_ptr += bytes_read;
18424     }
18425   lh->statement_program_start = line_ptr;
18426
18427   if (line_ptr > (section->buffer + section->size))
18428     complaint (&symfile_complaints,
18429                _("line number info header doesn't "
18430                  "fit in `.debug_line' section"));
18431
18432   return lh;
18433 }
18434
18435 /* Subroutine of dwarf_decode_lines to simplify it.
18436    Return the file name of the psymtab for included file FILE_INDEX
18437    in line header LH of PST.
18438    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18439    If space for the result is malloc'd, it will be freed by a cleanup.
18440    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18441
18442    The function creates dangling cleanup registration.  */
18443
18444 static const char *
18445 psymtab_include_file_name (const struct line_header *lh, int file_index,
18446                            const struct partial_symtab *pst,
18447                            const char *comp_dir)
18448 {
18449   const file_entry &fe = lh->file_names[file_index];
18450   const char *include_name = fe.name;
18451   const char *include_name_to_compare = include_name;
18452   const char *pst_filename;
18453   char *copied_name = NULL;
18454   int file_is_pst;
18455
18456   const char *dir_name = fe.include_dir (lh);
18457
18458   if (!IS_ABSOLUTE_PATH (include_name)
18459       && (dir_name != NULL || comp_dir != NULL))
18460     {
18461       /* Avoid creating a duplicate psymtab for PST.
18462          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18463          Before we do the comparison, however, we need to account
18464          for DIR_NAME and COMP_DIR.
18465          First prepend dir_name (if non-NULL).  If we still don't
18466          have an absolute path prepend comp_dir (if non-NULL).
18467          However, the directory we record in the include-file's
18468          psymtab does not contain COMP_DIR (to match the
18469          corresponding symtab(s)).
18470
18471          Example:
18472
18473          bash$ cd /tmp
18474          bash$ gcc -g ./hello.c
18475          include_name = "hello.c"
18476          dir_name = "."
18477          DW_AT_comp_dir = comp_dir = "/tmp"
18478          DW_AT_name = "./hello.c"
18479
18480       */
18481
18482       if (dir_name != NULL)
18483         {
18484           char *tem = concat (dir_name, SLASH_STRING,
18485                               include_name, (char *)NULL);
18486
18487           make_cleanup (xfree, tem);
18488           include_name = tem;
18489           include_name_to_compare = include_name;
18490         }
18491       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18492         {
18493           char *tem = concat (comp_dir, SLASH_STRING,
18494                               include_name, (char *)NULL);
18495
18496           make_cleanup (xfree, tem);
18497           include_name_to_compare = tem;
18498         }
18499     }
18500
18501   pst_filename = pst->filename;
18502   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18503     {
18504       copied_name = concat (pst->dirname, SLASH_STRING,
18505                             pst_filename, (char *)NULL);
18506       pst_filename = copied_name;
18507     }
18508
18509   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18510
18511   if (copied_name != NULL)
18512     xfree (copied_name);
18513
18514   if (file_is_pst)
18515     return NULL;
18516   return include_name;
18517 }
18518
18519 /* State machine to track the state of the line number program.  */
18520
18521 class lnp_state_machine
18522 {
18523 public:
18524   /* Initialize a machine state for the start of a line number
18525      program.  */
18526   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18527
18528   file_entry *current_file ()
18529   {
18530     /* lh->file_names is 0-based, but the file name numbers in the
18531        statement program are 1-based.  */
18532     return m_line_header->file_name_at (m_file);
18533   }
18534
18535   /* Record the line in the state machine.  END_SEQUENCE is true if
18536      we're processing the end of a sequence.  */
18537   void record_line (bool end_sequence);
18538
18539   /* Check address and if invalid nop-out the rest of the lines in this
18540      sequence.  */
18541   void check_line_address (struct dwarf2_cu *cu,
18542                            const gdb_byte *line_ptr,
18543                            CORE_ADDR lowpc, CORE_ADDR address);
18544
18545   void handle_set_discriminator (unsigned int discriminator)
18546   {
18547     m_discriminator = discriminator;
18548     m_line_has_non_zero_discriminator |= discriminator != 0;
18549   }
18550
18551   /* Handle DW_LNE_set_address.  */
18552   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18553   {
18554     m_op_index = 0;
18555     address += baseaddr;
18556     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18557   }
18558
18559   /* Handle DW_LNS_advance_pc.  */
18560   void handle_advance_pc (CORE_ADDR adjust);
18561
18562   /* Handle a special opcode.  */
18563   void handle_special_opcode (unsigned char op_code);
18564
18565   /* Handle DW_LNS_advance_line.  */
18566   void handle_advance_line (int line_delta)
18567   {
18568     advance_line (line_delta);
18569   }
18570
18571   /* Handle DW_LNS_set_file.  */
18572   void handle_set_file (file_name_index file);
18573
18574   /* Handle DW_LNS_negate_stmt.  */
18575   void handle_negate_stmt ()
18576   {
18577     m_is_stmt = !m_is_stmt;
18578   }
18579
18580   /* Handle DW_LNS_const_add_pc.  */
18581   void handle_const_add_pc ();
18582
18583   /* Handle DW_LNS_fixed_advance_pc.  */
18584   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18585   {
18586     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18587     m_op_index = 0;
18588   }
18589
18590   /* Handle DW_LNS_copy.  */
18591   void handle_copy ()
18592   {
18593     record_line (false);
18594     m_discriminator = 0;
18595   }
18596
18597   /* Handle DW_LNE_end_sequence.  */
18598   void handle_end_sequence ()
18599   {
18600     m_record_line_callback = ::record_line;
18601   }
18602
18603 private:
18604   /* Advance the line by LINE_DELTA.  */
18605   void advance_line (int line_delta)
18606   {
18607     m_line += line_delta;
18608
18609     if (line_delta != 0)
18610       m_line_has_non_zero_discriminator = m_discriminator != 0;
18611   }
18612
18613   gdbarch *m_gdbarch;
18614
18615   /* True if we're recording lines.
18616      Otherwise we're building partial symtabs and are just interested in
18617      finding include files mentioned by the line number program.  */
18618   bool m_record_lines_p;
18619
18620   /* The line number header.  */
18621   line_header *m_line_header;
18622
18623   /* These are part of the standard DWARF line number state machine,
18624      and initialized according to the DWARF spec.  */
18625
18626   unsigned char m_op_index = 0;
18627   /* The line table index (1-based) of the current file.  */
18628   file_name_index m_file = (file_name_index) 1;
18629   unsigned int m_line = 1;
18630
18631   /* These are initialized in the constructor.  */
18632
18633   CORE_ADDR m_address;
18634   bool m_is_stmt;
18635   unsigned int m_discriminator;
18636
18637   /* Additional bits of state we need to track.  */
18638
18639   /* The last file that we called dwarf2_start_subfile for.
18640      This is only used for TLLs.  */
18641   unsigned int m_last_file = 0;
18642   /* The last file a line number was recorded for.  */
18643   struct subfile *m_last_subfile = NULL;
18644
18645   /* The function to call to record a line.  */
18646   record_line_ftype *m_record_line_callback = NULL;
18647
18648   /* The last line number that was recorded, used to coalesce
18649      consecutive entries for the same line.  This can happen, for
18650      example, when discriminators are present.  PR 17276.  */
18651   unsigned int m_last_line = 0;
18652   bool m_line_has_non_zero_discriminator = false;
18653 };
18654
18655 void
18656 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18657 {
18658   CORE_ADDR addr_adj = (((m_op_index + adjust)
18659                          / m_line_header->maximum_ops_per_instruction)
18660                         * m_line_header->minimum_instruction_length);
18661   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18662   m_op_index = ((m_op_index + adjust)
18663                 % m_line_header->maximum_ops_per_instruction);
18664 }
18665
18666 void
18667 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18668 {
18669   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18670   CORE_ADDR addr_adj = (((m_op_index
18671                           + (adj_opcode / m_line_header->line_range))
18672                          / m_line_header->maximum_ops_per_instruction)
18673                         * m_line_header->minimum_instruction_length);
18674   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18675   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18676                 % m_line_header->maximum_ops_per_instruction);
18677
18678   int line_delta = (m_line_header->line_base
18679                     + (adj_opcode % m_line_header->line_range));
18680   advance_line (line_delta);
18681   record_line (false);
18682   m_discriminator = 0;
18683 }
18684
18685 void
18686 lnp_state_machine::handle_set_file (file_name_index file)
18687 {
18688   m_file = file;
18689
18690   const file_entry *fe = current_file ();
18691   if (fe == NULL)
18692     dwarf2_debug_line_missing_file_complaint ();
18693   else if (m_record_lines_p)
18694     {
18695       const char *dir = fe->include_dir (m_line_header);
18696
18697       m_last_subfile = current_subfile;
18698       m_line_has_non_zero_discriminator = m_discriminator != 0;
18699       dwarf2_start_subfile (fe->name, dir);
18700     }
18701 }
18702
18703 void
18704 lnp_state_machine::handle_const_add_pc ()
18705 {
18706   CORE_ADDR adjust
18707     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18708
18709   CORE_ADDR addr_adj
18710     = (((m_op_index + adjust)
18711         / m_line_header->maximum_ops_per_instruction)
18712        * m_line_header->minimum_instruction_length);
18713
18714   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18715   m_op_index = ((m_op_index + adjust)
18716                 % m_line_header->maximum_ops_per_instruction);
18717 }
18718
18719 /* Ignore this record_line request.  */
18720
18721 static void
18722 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18723 {
18724   return;
18725 }
18726
18727 /* Return non-zero if we should add LINE to the line number table.
18728    LINE is the line to add, LAST_LINE is the last line that was added,
18729    LAST_SUBFILE is the subfile for LAST_LINE.
18730    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18731    had a non-zero discriminator.
18732
18733    We have to be careful in the presence of discriminators.
18734    E.g., for this line:
18735
18736      for (i = 0; i < 100000; i++);
18737
18738    clang can emit four line number entries for that one line,
18739    each with a different discriminator.
18740    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18741
18742    However, we want gdb to coalesce all four entries into one.
18743    Otherwise the user could stepi into the middle of the line and
18744    gdb would get confused about whether the pc really was in the
18745    middle of the line.
18746
18747    Things are further complicated by the fact that two consecutive
18748    line number entries for the same line is a heuristic used by gcc
18749    to denote the end of the prologue.  So we can't just discard duplicate
18750    entries, we have to be selective about it.  The heuristic we use is
18751    that we only collapse consecutive entries for the same line if at least
18752    one of those entries has a non-zero discriminator.  PR 17276.
18753
18754    Note: Addresses in the line number state machine can never go backwards
18755    within one sequence, thus this coalescing is ok.  */
18756
18757 static int
18758 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18759                      int line_has_non_zero_discriminator,
18760                      struct subfile *last_subfile)
18761 {
18762   if (current_subfile != last_subfile)
18763     return 1;
18764   if (line != last_line)
18765     return 1;
18766   /* Same line for the same file that we've seen already.
18767      As a last check, for pr 17276, only record the line if the line
18768      has never had a non-zero discriminator.  */
18769   if (!line_has_non_zero_discriminator)
18770     return 1;
18771   return 0;
18772 }
18773
18774 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18775    in the line table of subfile SUBFILE.  */
18776
18777 static void
18778 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18779                      unsigned int line, CORE_ADDR address,
18780                      record_line_ftype p_record_line)
18781 {
18782   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18783
18784   if (dwarf_line_debug)
18785     {
18786       fprintf_unfiltered (gdb_stdlog,
18787                           "Recording line %u, file %s, address %s\n",
18788                           line, lbasename (subfile->name),
18789                           paddress (gdbarch, address));
18790     }
18791
18792   (*p_record_line) (subfile, line, addr);
18793 }
18794
18795 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18796    Mark the end of a set of line number records.
18797    The arguments are the same as for dwarf_record_line_1.
18798    If SUBFILE is NULL the request is ignored.  */
18799
18800 static void
18801 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18802                    CORE_ADDR address, record_line_ftype p_record_line)
18803 {
18804   if (subfile == NULL)
18805     return;
18806
18807   if (dwarf_line_debug)
18808     {
18809       fprintf_unfiltered (gdb_stdlog,
18810                           "Finishing current line, file %s, address %s\n",
18811                           lbasename (subfile->name),
18812                           paddress (gdbarch, address));
18813     }
18814
18815   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18816 }
18817
18818 void
18819 lnp_state_machine::record_line (bool end_sequence)
18820 {
18821   if (dwarf_line_debug)
18822     {
18823       fprintf_unfiltered (gdb_stdlog,
18824                           "Processing actual line %u: file %u,"
18825                           " address %s, is_stmt %u, discrim %u\n",
18826                           m_line, to_underlying (m_file),
18827                           paddress (m_gdbarch, m_address),
18828                           m_is_stmt, m_discriminator);
18829     }
18830
18831   file_entry *fe = current_file ();
18832
18833   if (fe == NULL)
18834     dwarf2_debug_line_missing_file_complaint ();
18835   /* For now we ignore lines not starting on an instruction boundary.
18836      But not when processing end_sequence for compatibility with the
18837      previous version of the code.  */
18838   else if (m_op_index == 0 || end_sequence)
18839     {
18840       fe->included_p = 1;
18841       if (m_record_lines_p && m_is_stmt)
18842         {
18843           if (m_last_subfile != current_subfile || end_sequence)
18844             {
18845               dwarf_finish_line (m_gdbarch, m_last_subfile,
18846                                  m_address, m_record_line_callback);
18847             }
18848
18849           if (!end_sequence)
18850             {
18851               if (dwarf_record_line_p (m_line, m_last_line,
18852                                        m_line_has_non_zero_discriminator,
18853                                        m_last_subfile))
18854                 {
18855                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18856                                        m_line, m_address,
18857                                        m_record_line_callback);
18858                 }
18859               m_last_subfile = current_subfile;
18860               m_last_line = m_line;
18861             }
18862         }
18863     }
18864 }
18865
18866 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18867                                       bool record_lines_p)
18868 {
18869   m_gdbarch = arch;
18870   m_record_lines_p = record_lines_p;
18871   m_line_header = lh;
18872
18873   m_record_line_callback = ::record_line;
18874
18875   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18876      was a line entry for it so that the backend has a chance to adjust it
18877      and also record it in case it needs it.  This is currently used by MIPS
18878      code, cf. `mips_adjust_dwarf2_line'.  */
18879   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18880   m_is_stmt = lh->default_is_stmt;
18881   m_discriminator = 0;
18882 }
18883
18884 void
18885 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18886                                        const gdb_byte *line_ptr,
18887                                        CORE_ADDR lowpc, CORE_ADDR address)
18888 {
18889   /* If address < lowpc then it's not a usable value, it's outside the
18890      pc range of the CU.  However, we restrict the test to only address
18891      values of zero to preserve GDB's previous behaviour which is to
18892      handle the specific case of a function being GC'd by the linker.  */
18893
18894   if (address == 0 && address < lowpc)
18895     {
18896       /* This line table is for a function which has been
18897          GCd by the linker.  Ignore it.  PR gdb/12528 */
18898
18899       struct objfile *objfile = cu->objfile;
18900       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18901
18902       complaint (&symfile_complaints,
18903                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18904                  line_offset, objfile_name (objfile));
18905       m_record_line_callback = noop_record_line;
18906       /* Note: record_line_callback is left as noop_record_line until
18907          we see DW_LNE_end_sequence.  */
18908     }
18909 }
18910
18911 /* Subroutine of dwarf_decode_lines to simplify it.
18912    Process the line number information in LH.
18913    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18914    program in order to set included_p for every referenced header.  */
18915
18916 static void
18917 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18918                       const int decode_for_pst_p, CORE_ADDR lowpc)
18919 {
18920   const gdb_byte *line_ptr, *extended_end;
18921   const gdb_byte *line_end;
18922   unsigned int bytes_read, extended_len;
18923   unsigned char op_code, extended_op;
18924   CORE_ADDR baseaddr;
18925   struct objfile *objfile = cu->objfile;
18926   bfd *abfd = objfile->obfd;
18927   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18928   /* True if we're recording line info (as opposed to building partial
18929      symtabs and just interested in finding include files mentioned by
18930      the line number program).  */
18931   bool record_lines_p = !decode_for_pst_p;
18932
18933   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18934
18935   line_ptr = lh->statement_program_start;
18936   line_end = lh->statement_program_end;
18937
18938   /* Read the statement sequences until there's nothing left.  */
18939   while (line_ptr < line_end)
18940     {
18941       /* The DWARF line number program state machine.  Reset the state
18942          machine at the start of each sequence.  */
18943       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18944       bool end_sequence = false;
18945
18946       if (record_lines_p)
18947         {
18948           /* Start a subfile for the current file of the state
18949              machine.  */
18950           const file_entry *fe = state_machine.current_file ();
18951
18952           if (fe != NULL)
18953             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18954         }
18955
18956       /* Decode the table.  */
18957       while (line_ptr < line_end && !end_sequence)
18958         {
18959           op_code = read_1_byte (abfd, line_ptr);
18960           line_ptr += 1;
18961
18962           if (op_code >= lh->opcode_base)
18963             {
18964               /* Special opcode.  */
18965               state_machine.handle_special_opcode (op_code);
18966             }
18967           else switch (op_code)
18968             {
18969             case DW_LNS_extended_op:
18970               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18971                                                    &bytes_read);
18972               line_ptr += bytes_read;
18973               extended_end = line_ptr + extended_len;
18974               extended_op = read_1_byte (abfd, line_ptr);
18975               line_ptr += 1;
18976               switch (extended_op)
18977                 {
18978                 case DW_LNE_end_sequence:
18979                   state_machine.handle_end_sequence ();
18980                   end_sequence = true;
18981                   break;
18982                 case DW_LNE_set_address:
18983                   {
18984                     CORE_ADDR address
18985                       = read_address (abfd, line_ptr, cu, &bytes_read);
18986                     line_ptr += bytes_read;
18987
18988                     state_machine.check_line_address (cu, line_ptr,
18989                                                       lowpc, address);
18990                     state_machine.handle_set_address (baseaddr, address);
18991                   }
18992                   break;
18993                 case DW_LNE_define_file:
18994                   {
18995                     const char *cur_file;
18996                     unsigned int mod_time, length;
18997                     dir_index dindex;
18998
18999                     cur_file = read_direct_string (abfd, line_ptr,
19000                                                    &bytes_read);
19001                     line_ptr += bytes_read;
19002                     dindex = (dir_index)
19003                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19004                     line_ptr += bytes_read;
19005                     mod_time =
19006                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19007                     line_ptr += bytes_read;
19008                     length =
19009                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19010                     line_ptr += bytes_read;
19011                     lh->add_file_name (cur_file, dindex, mod_time, length);
19012                   }
19013                   break;
19014                 case DW_LNE_set_discriminator:
19015                   {
19016                     /* The discriminator is not interesting to the
19017                        debugger; just ignore it.  We still need to
19018                        check its value though:
19019                        if there are consecutive entries for the same
19020                        (non-prologue) line we want to coalesce them.
19021                        PR 17276.  */
19022                     unsigned int discr
19023                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19024                     line_ptr += bytes_read;
19025
19026                     state_machine.handle_set_discriminator (discr);
19027                   }
19028                   break;
19029                 default:
19030                   complaint (&symfile_complaints,
19031                              _("mangled .debug_line section"));
19032                   return;
19033                 }
19034               /* Make sure that we parsed the extended op correctly.  If e.g.
19035                  we expected a different address size than the producer used,
19036                  we may have read the wrong number of bytes.  */
19037               if (line_ptr != extended_end)
19038                 {
19039                   complaint (&symfile_complaints,
19040                              _("mangled .debug_line section"));
19041                   return;
19042                 }
19043               break;
19044             case DW_LNS_copy:
19045               state_machine.handle_copy ();
19046               break;
19047             case DW_LNS_advance_pc:
19048               {
19049                 CORE_ADDR adjust
19050                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19051                 line_ptr += bytes_read;
19052
19053                 state_machine.handle_advance_pc (adjust);
19054               }
19055               break;
19056             case DW_LNS_advance_line:
19057               {
19058                 int line_delta
19059                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19060                 line_ptr += bytes_read;
19061
19062                 state_machine.handle_advance_line (line_delta);
19063               }
19064               break;
19065             case DW_LNS_set_file:
19066               {
19067                 file_name_index file
19068                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19069                                                             &bytes_read);
19070                 line_ptr += bytes_read;
19071
19072                 state_machine.handle_set_file (file);
19073               }
19074               break;
19075             case DW_LNS_set_column:
19076               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19077               line_ptr += bytes_read;
19078               break;
19079             case DW_LNS_negate_stmt:
19080               state_machine.handle_negate_stmt ();
19081               break;
19082             case DW_LNS_set_basic_block:
19083               break;
19084             /* Add to the address register of the state machine the
19085                address increment value corresponding to special opcode
19086                255.  I.e., this value is scaled by the minimum
19087                instruction length since special opcode 255 would have
19088                scaled the increment.  */
19089             case DW_LNS_const_add_pc:
19090               state_machine.handle_const_add_pc ();
19091               break;
19092             case DW_LNS_fixed_advance_pc:
19093               {
19094                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19095                 line_ptr += 2;
19096
19097                 state_machine.handle_fixed_advance_pc (addr_adj);
19098               }
19099               break;
19100             default:
19101               {
19102                 /* Unknown standard opcode, ignore it.  */
19103                 int i;
19104
19105                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19106                   {
19107                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19108                     line_ptr += bytes_read;
19109                   }
19110               }
19111             }
19112         }
19113
19114       if (!end_sequence)
19115         dwarf2_debug_line_missing_end_sequence_complaint ();
19116
19117       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19118          in which case we still finish recording the last line).  */
19119       state_machine.record_line (true);
19120     }
19121 }
19122
19123 /* Decode the Line Number Program (LNP) for the given line_header
19124    structure and CU.  The actual information extracted and the type
19125    of structures created from the LNP depends on the value of PST.
19126
19127    1. If PST is NULL, then this procedure uses the data from the program
19128       to create all necessary symbol tables, and their linetables.
19129
19130    2. If PST is not NULL, this procedure reads the program to determine
19131       the list of files included by the unit represented by PST, and
19132       builds all the associated partial symbol tables.
19133
19134    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19135    It is used for relative paths in the line table.
19136    NOTE: When processing partial symtabs (pst != NULL),
19137    comp_dir == pst->dirname.
19138
19139    NOTE: It is important that psymtabs have the same file name (via strcmp)
19140    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19141    symtab we don't use it in the name of the psymtabs we create.
19142    E.g. expand_line_sal requires this when finding psymtabs to expand.
19143    A good testcase for this is mb-inline.exp.
19144
19145    LOWPC is the lowest address in CU (or 0 if not known).
19146
19147    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19148    for its PC<->lines mapping information.  Otherwise only the filename
19149    table is read in.  */
19150
19151 static void
19152 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19153                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19154                     CORE_ADDR lowpc, int decode_mapping)
19155 {
19156   struct objfile *objfile = cu->objfile;
19157   const int decode_for_pst_p = (pst != NULL);
19158
19159   if (decode_mapping)
19160     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19161
19162   if (decode_for_pst_p)
19163     {
19164       int file_index;
19165
19166       /* Now that we're done scanning the Line Header Program, we can
19167          create the psymtab of each included file.  */
19168       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19169         if (lh->file_names[file_index].included_p == 1)
19170           {
19171             const char *include_name =
19172               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19173             if (include_name != NULL)
19174               dwarf2_create_include_psymtab (include_name, pst, objfile);
19175           }
19176     }
19177   else
19178     {
19179       /* Make sure a symtab is created for every file, even files
19180          which contain only variables (i.e. no code with associated
19181          line numbers).  */
19182       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19183       int i;
19184
19185       for (i = 0; i < lh->file_names.size (); i++)
19186         {
19187           file_entry &fe = lh->file_names[i];
19188
19189           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19190
19191           if (current_subfile->symtab == NULL)
19192             {
19193               current_subfile->symtab
19194                 = allocate_symtab (cust, current_subfile->name);
19195             }
19196           fe.symtab = current_subfile->symtab;
19197         }
19198     }
19199 }
19200
19201 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19202    DIRNAME the name of the source directory which contains FILENAME
19203    or NULL if not known.
19204    This routine tries to keep line numbers from identical absolute and
19205    relative file names in a common subfile.
19206
19207    Using the `list' example from the GDB testsuite, which resides in
19208    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19209    of /srcdir/list0.c yields the following debugging information for list0.c:
19210
19211    DW_AT_name:          /srcdir/list0.c
19212    DW_AT_comp_dir:      /compdir
19213    files.files[0].name: list0.h
19214    files.files[0].dir:  /srcdir
19215    files.files[1].name: list0.c
19216    files.files[1].dir:  /srcdir
19217
19218    The line number information for list0.c has to end up in a single
19219    subfile, so that `break /srcdir/list0.c:1' works as expected.
19220    start_subfile will ensure that this happens provided that we pass the
19221    concatenation of files.files[1].dir and files.files[1].name as the
19222    subfile's name.  */
19223
19224 static void
19225 dwarf2_start_subfile (const char *filename, const char *dirname)
19226 {
19227   char *copy = NULL;
19228
19229   /* In order not to lose the line information directory,
19230      we concatenate it to the filename when it makes sense.
19231      Note that the Dwarf3 standard says (speaking of filenames in line
19232      information): ``The directory index is ignored for file names
19233      that represent full path names''.  Thus ignoring dirname in the
19234      `else' branch below isn't an issue.  */
19235
19236   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19237     {
19238       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19239       filename = copy;
19240     }
19241
19242   start_subfile (filename);
19243
19244   if (copy != NULL)
19245     xfree (copy);
19246 }
19247
19248 /* Start a symtab for DWARF.
19249    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19250
19251 static struct compunit_symtab *
19252 dwarf2_start_symtab (struct dwarf2_cu *cu,
19253                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19254 {
19255   struct compunit_symtab *cust
19256     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19257
19258   record_debugformat ("DWARF 2");
19259   record_producer (cu->producer);
19260
19261   /* We assume that we're processing GCC output.  */
19262   processing_gcc_compilation = 2;
19263
19264   cu->processing_has_namespace_info = 0;
19265
19266   return cust;
19267 }
19268
19269 static void
19270 var_decode_location (struct attribute *attr, struct symbol *sym,
19271                      struct dwarf2_cu *cu)
19272 {
19273   struct objfile *objfile = cu->objfile;
19274   struct comp_unit_head *cu_header = &cu->header;
19275
19276   /* NOTE drow/2003-01-30: There used to be a comment and some special
19277      code here to turn a symbol with DW_AT_external and a
19278      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19279      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19280      with some versions of binutils) where shared libraries could have
19281      relocations against symbols in their debug information - the
19282      minimal symbol would have the right address, but the debug info
19283      would not.  It's no longer necessary, because we will explicitly
19284      apply relocations when we read in the debug information now.  */
19285
19286   /* A DW_AT_location attribute with no contents indicates that a
19287      variable has been optimized away.  */
19288   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19289     {
19290       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19291       return;
19292     }
19293
19294   /* Handle one degenerate form of location expression specially, to
19295      preserve GDB's previous behavior when section offsets are
19296      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19297      then mark this symbol as LOC_STATIC.  */
19298
19299   if (attr_form_is_block (attr)
19300       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19301            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19302           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19303               && (DW_BLOCK (attr)->size
19304                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19305     {
19306       unsigned int dummy;
19307
19308       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19309         SYMBOL_VALUE_ADDRESS (sym) =
19310           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19311       else
19312         SYMBOL_VALUE_ADDRESS (sym) =
19313           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19314       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19315       fixup_symbol_section (sym, objfile);
19316       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19317                                               SYMBOL_SECTION (sym));
19318       return;
19319     }
19320
19321   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19322      expression evaluator, and use LOC_COMPUTED only when necessary
19323      (i.e. when the value of a register or memory location is
19324      referenced, or a thread-local block, etc.).  Then again, it might
19325      not be worthwhile.  I'm assuming that it isn't unless performance
19326      or memory numbers show me otherwise.  */
19327
19328   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19329
19330   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19331     cu->has_loclist = 1;
19332 }
19333
19334 /* Given a pointer to a DWARF information entry, figure out if we need
19335    to make a symbol table entry for it, and if so, create a new entry
19336    and return a pointer to it.
19337    If TYPE is NULL, determine symbol type from the die, otherwise
19338    used the passed type.
19339    If SPACE is not NULL, use it to hold the new symbol.  If it is
19340    NULL, allocate a new symbol on the objfile's obstack.  */
19341
19342 static struct symbol *
19343 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19344                  struct symbol *space)
19345 {
19346   struct objfile *objfile = cu->objfile;
19347   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19348   struct symbol *sym = NULL;
19349   const char *name;
19350   struct attribute *attr = NULL;
19351   struct attribute *attr2 = NULL;
19352   CORE_ADDR baseaddr;
19353   struct pending **list_to_add = NULL;
19354
19355   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19356
19357   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19358
19359   name = dwarf2_name (die, cu);
19360   if (name)
19361     {
19362       const char *linkagename;
19363       int suppress_add = 0;
19364
19365       if (space)
19366         sym = space;
19367       else
19368         sym = allocate_symbol (objfile);
19369       OBJSTAT (objfile, n_syms++);
19370
19371       /* Cache this symbol's name and the name's demangled form (if any).  */
19372       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19373       linkagename = dwarf2_physname (name, die, cu);
19374       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19375
19376       /* Fortran does not have mangling standard and the mangling does differ
19377          between gfortran, iFort etc.  */
19378       if (cu->language == language_fortran
19379           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19380         symbol_set_demangled_name (&(sym->ginfo),
19381                                    dwarf2_full_name (name, die, cu),
19382                                    NULL);
19383
19384       /* Default assumptions.
19385          Use the passed type or decode it from the die.  */
19386       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19387       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19388       if (type != NULL)
19389         SYMBOL_TYPE (sym) = type;
19390       else
19391         SYMBOL_TYPE (sym) = die_type (die, cu);
19392       attr = dwarf2_attr (die,
19393                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19394                           cu);
19395       if (attr)
19396         {
19397           SYMBOL_LINE (sym) = DW_UNSND (attr);
19398         }
19399
19400       attr = dwarf2_attr (die,
19401                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19402                           cu);
19403       if (attr)
19404         {
19405           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19406           struct file_entry *fe;
19407
19408           if (cu->line_header != NULL)
19409             fe = cu->line_header->file_name_at (file_index);
19410           else
19411             fe = NULL;
19412
19413           if (fe == NULL)
19414             complaint (&symfile_complaints,
19415                        _("file index out of range"));
19416           else
19417             symbol_set_symtab (sym, fe->symtab);
19418         }
19419
19420       switch (die->tag)
19421         {
19422         case DW_TAG_label:
19423           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19424           if (attr)
19425             {
19426               CORE_ADDR addr;
19427
19428               addr = attr_value_as_address (attr);
19429               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19430               SYMBOL_VALUE_ADDRESS (sym) = addr;
19431             }
19432           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19433           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19434           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19435           add_symbol_to_list (sym, cu->list_in_scope);
19436           break;
19437         case DW_TAG_subprogram:
19438           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19439              finish_block.  */
19440           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19441           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19442           if ((attr2 && (DW_UNSND (attr2) != 0))
19443               || cu->language == language_ada)
19444             {
19445               /* Subprograms marked external are stored as a global symbol.
19446                  Ada subprograms, whether marked external or not, are always
19447                  stored as a global symbol, because we want to be able to
19448                  access them globally.  For instance, we want to be able
19449                  to break on a nested subprogram without having to
19450                  specify the context.  */
19451               list_to_add = &global_symbols;
19452             }
19453           else
19454             {
19455               list_to_add = cu->list_in_scope;
19456             }
19457           break;
19458         case DW_TAG_inlined_subroutine:
19459           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19460              finish_block.  */
19461           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19462           SYMBOL_INLINED (sym) = 1;
19463           list_to_add = cu->list_in_scope;
19464           break;
19465         case DW_TAG_template_value_param:
19466           suppress_add = 1;
19467           /* Fall through.  */
19468         case DW_TAG_constant:
19469         case DW_TAG_variable:
19470         case DW_TAG_member:
19471           /* Compilation with minimal debug info may result in
19472              variables with missing type entries.  Change the
19473              misleading `void' type to something sensible.  */
19474           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19475             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19476
19477           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19478           /* In the case of DW_TAG_member, we should only be called for
19479              static const members.  */
19480           if (die->tag == DW_TAG_member)
19481             {
19482               /* dwarf2_add_field uses die_is_declaration,
19483                  so we do the same.  */
19484               gdb_assert (die_is_declaration (die, cu));
19485               gdb_assert (attr);
19486             }
19487           if (attr)
19488             {
19489               dwarf2_const_value (attr, sym, cu);
19490               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19491               if (!suppress_add)
19492                 {
19493                   if (attr2 && (DW_UNSND (attr2) != 0))
19494                     list_to_add = &global_symbols;
19495                   else
19496                     list_to_add = cu->list_in_scope;
19497                 }
19498               break;
19499             }
19500           attr = dwarf2_attr (die, DW_AT_location, cu);
19501           if (attr)
19502             {
19503               var_decode_location (attr, sym, cu);
19504               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19505
19506               /* Fortran explicitly imports any global symbols to the local
19507                  scope by DW_TAG_common_block.  */
19508               if (cu->language == language_fortran && die->parent
19509                   && die->parent->tag == DW_TAG_common_block)
19510                 attr2 = NULL;
19511
19512               if (SYMBOL_CLASS (sym) == LOC_STATIC
19513                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19514                   && !dwarf2_per_objfile->has_section_at_zero)
19515                 {
19516                   /* When a static variable is eliminated by the linker,
19517                      the corresponding debug information is not stripped
19518                      out, but the variable address is set to null;
19519                      do not add such variables into symbol table.  */
19520                 }
19521               else if (attr2 && (DW_UNSND (attr2) != 0))
19522                 {
19523                   /* Workaround gfortran PR debug/40040 - it uses
19524                      DW_AT_location for variables in -fPIC libraries which may
19525                      get overriden by other libraries/executable and get
19526                      a different address.  Resolve it by the minimal symbol
19527                      which may come from inferior's executable using copy
19528                      relocation.  Make this workaround only for gfortran as for
19529                      other compilers GDB cannot guess the minimal symbol
19530                      Fortran mangling kind.  */
19531                   if (cu->language == language_fortran && die->parent
19532                       && die->parent->tag == DW_TAG_module
19533                       && cu->producer
19534                       && startswith (cu->producer, "GNU Fortran"))
19535                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19536
19537                   /* A variable with DW_AT_external is never static,
19538                      but it may be block-scoped.  */
19539                   list_to_add = (cu->list_in_scope == &file_symbols
19540                                  ? &global_symbols : cu->list_in_scope);
19541                 }
19542               else
19543                 list_to_add = cu->list_in_scope;
19544             }
19545           else
19546             {
19547               /* We do not know the address of this symbol.
19548                  If it is an external symbol and we have type information
19549                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19550                  The address of the variable will then be determined from
19551                  the minimal symbol table whenever the variable is
19552                  referenced.  */
19553               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19554
19555               /* Fortran explicitly imports any global symbols to the local
19556                  scope by DW_TAG_common_block.  */
19557               if (cu->language == language_fortran && die->parent
19558                   && die->parent->tag == DW_TAG_common_block)
19559                 {
19560                   /* SYMBOL_CLASS doesn't matter here because
19561                      read_common_block is going to reset it.  */
19562                   if (!suppress_add)
19563                     list_to_add = cu->list_in_scope;
19564                 }
19565               else if (attr2 && (DW_UNSND (attr2) != 0)
19566                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19567                 {
19568                   /* A variable with DW_AT_external is never static, but it
19569                      may be block-scoped.  */
19570                   list_to_add = (cu->list_in_scope == &file_symbols
19571                                  ? &global_symbols : cu->list_in_scope);
19572
19573                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19574                 }
19575               else if (!die_is_declaration (die, cu))
19576                 {
19577                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19578                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19579                   if (!suppress_add)
19580                     list_to_add = cu->list_in_scope;
19581                 }
19582             }
19583           break;
19584         case DW_TAG_formal_parameter:
19585           /* If we are inside a function, mark this as an argument.  If
19586              not, we might be looking at an argument to an inlined function
19587              when we do not have enough information to show inlined frames;
19588              pretend it's a local variable in that case so that the user can
19589              still see it.  */
19590           if (context_stack_depth > 0
19591               && context_stack[context_stack_depth - 1].name != NULL)
19592             SYMBOL_IS_ARGUMENT (sym) = 1;
19593           attr = dwarf2_attr (die, DW_AT_location, cu);
19594           if (attr)
19595             {
19596               var_decode_location (attr, sym, cu);
19597             }
19598           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19599           if (attr)
19600             {
19601               dwarf2_const_value (attr, sym, cu);
19602             }
19603
19604           list_to_add = cu->list_in_scope;
19605           break;
19606         case DW_TAG_unspecified_parameters:
19607           /* From varargs functions; gdb doesn't seem to have any
19608              interest in this information, so just ignore it for now.
19609              (FIXME?) */
19610           break;
19611         case DW_TAG_template_type_param:
19612           suppress_add = 1;
19613           /* Fall through.  */
19614         case DW_TAG_class_type:
19615         case DW_TAG_interface_type:
19616         case DW_TAG_structure_type:
19617         case DW_TAG_union_type:
19618         case DW_TAG_set_type:
19619         case DW_TAG_enumeration_type:
19620           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19621           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19622
19623           {
19624             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19625                really ever be static objects: otherwise, if you try
19626                to, say, break of a class's method and you're in a file
19627                which doesn't mention that class, it won't work unless
19628                the check for all static symbols in lookup_symbol_aux
19629                saves you.  See the OtherFileClass tests in
19630                gdb.c++/namespace.exp.  */
19631
19632             if (!suppress_add)
19633               {
19634                 list_to_add = (cu->list_in_scope == &file_symbols
19635                                && cu->language == language_cplus
19636                                ? &global_symbols : cu->list_in_scope);
19637
19638                 /* The semantics of C++ state that "struct foo {
19639                    ... }" also defines a typedef for "foo".  */
19640                 if (cu->language == language_cplus
19641                     || cu->language == language_ada
19642                     || cu->language == language_d
19643                     || cu->language == language_rust)
19644                   {
19645                     /* The symbol's name is already allocated along
19646                        with this objfile, so we don't need to
19647                        duplicate it for the type.  */
19648                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19649                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19650                   }
19651               }
19652           }
19653           break;
19654         case DW_TAG_typedef:
19655           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19656           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19657           list_to_add = cu->list_in_scope;
19658           break;
19659         case DW_TAG_base_type:
19660         case DW_TAG_subrange_type:
19661           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19662           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19663           list_to_add = cu->list_in_scope;
19664           break;
19665         case DW_TAG_enumerator:
19666           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19667           if (attr)
19668             {
19669               dwarf2_const_value (attr, sym, cu);
19670             }
19671           {
19672             /* NOTE: carlton/2003-11-10: See comment above in the
19673                DW_TAG_class_type, etc. block.  */
19674
19675             list_to_add = (cu->list_in_scope == &file_symbols
19676                            && cu->language == language_cplus
19677                            ? &global_symbols : cu->list_in_scope);
19678           }
19679           break;
19680         case DW_TAG_imported_declaration:
19681         case DW_TAG_namespace:
19682           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19683           list_to_add = &global_symbols;
19684           break;
19685         case DW_TAG_module:
19686           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19687           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19688           list_to_add = &global_symbols;
19689           break;
19690         case DW_TAG_common_block:
19691           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19692           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19693           add_symbol_to_list (sym, cu->list_in_scope);
19694           break;
19695         default:
19696           /* Not a tag we recognize.  Hopefully we aren't processing
19697              trash data, but since we must specifically ignore things
19698              we don't recognize, there is nothing else we should do at
19699              this point.  */
19700           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19701                      dwarf_tag_name (die->tag));
19702           break;
19703         }
19704
19705       if (suppress_add)
19706         {
19707           sym->hash_next = objfile->template_symbols;
19708           objfile->template_symbols = sym;
19709           list_to_add = NULL;
19710         }
19711
19712       if (list_to_add != NULL)
19713         add_symbol_to_list (sym, list_to_add);
19714
19715       /* For the benefit of old versions of GCC, check for anonymous
19716          namespaces based on the demangled name.  */
19717       if (!cu->processing_has_namespace_info
19718           && cu->language == language_cplus)
19719         cp_scan_for_anonymous_namespaces (sym, objfile);
19720     }
19721   return (sym);
19722 }
19723
19724 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19725
19726 static struct symbol *
19727 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19728 {
19729   return new_symbol_full (die, type, cu, NULL);
19730 }
19731
19732 /* Given an attr with a DW_FORM_dataN value in host byte order,
19733    zero-extend it as appropriate for the symbol's type.  The DWARF
19734    standard (v4) is not entirely clear about the meaning of using
19735    DW_FORM_dataN for a constant with a signed type, where the type is
19736    wider than the data.  The conclusion of a discussion on the DWARF
19737    list was that this is unspecified.  We choose to always zero-extend
19738    because that is the interpretation long in use by GCC.  */
19739
19740 static gdb_byte *
19741 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19742                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19743 {
19744   struct objfile *objfile = cu->objfile;
19745   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19746                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19747   LONGEST l = DW_UNSND (attr);
19748
19749   if (bits < sizeof (*value) * 8)
19750     {
19751       l &= ((LONGEST) 1 << bits) - 1;
19752       *value = l;
19753     }
19754   else if (bits == sizeof (*value) * 8)
19755     *value = l;
19756   else
19757     {
19758       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19759       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19760       return bytes;
19761     }
19762
19763   return NULL;
19764 }
19765
19766 /* Read a constant value from an attribute.  Either set *VALUE, or if
19767    the value does not fit in *VALUE, set *BYTES - either already
19768    allocated on the objfile obstack, or newly allocated on OBSTACK,
19769    or, set *BATON, if we translated the constant to a location
19770    expression.  */
19771
19772 static void
19773 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19774                          const char *name, struct obstack *obstack,
19775                          struct dwarf2_cu *cu,
19776                          LONGEST *value, const gdb_byte **bytes,
19777                          struct dwarf2_locexpr_baton **baton)
19778 {
19779   struct objfile *objfile = cu->objfile;
19780   struct comp_unit_head *cu_header = &cu->header;
19781   struct dwarf_block *blk;
19782   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19783                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19784
19785   *value = 0;
19786   *bytes = NULL;
19787   *baton = NULL;
19788
19789   switch (attr->form)
19790     {
19791     case DW_FORM_addr:
19792     case DW_FORM_GNU_addr_index:
19793       {
19794         gdb_byte *data;
19795
19796         if (TYPE_LENGTH (type) != cu_header->addr_size)
19797           dwarf2_const_value_length_mismatch_complaint (name,
19798                                                         cu_header->addr_size,
19799                                                         TYPE_LENGTH (type));
19800         /* Symbols of this form are reasonably rare, so we just
19801            piggyback on the existing location code rather than writing
19802            a new implementation of symbol_computed_ops.  */
19803         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19804         (*baton)->per_cu = cu->per_cu;
19805         gdb_assert ((*baton)->per_cu);
19806
19807         (*baton)->size = 2 + cu_header->addr_size;
19808         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19809         (*baton)->data = data;
19810
19811         data[0] = DW_OP_addr;
19812         store_unsigned_integer (&data[1], cu_header->addr_size,
19813                                 byte_order, DW_ADDR (attr));
19814         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19815       }
19816       break;
19817     case DW_FORM_string:
19818     case DW_FORM_strp:
19819     case DW_FORM_GNU_str_index:
19820     case DW_FORM_GNU_strp_alt:
19821       /* DW_STRING is already allocated on the objfile obstack, point
19822          directly to it.  */
19823       *bytes = (const gdb_byte *) DW_STRING (attr);
19824       break;
19825     case DW_FORM_block1:
19826     case DW_FORM_block2:
19827     case DW_FORM_block4:
19828     case DW_FORM_block:
19829     case DW_FORM_exprloc:
19830     case DW_FORM_data16:
19831       blk = DW_BLOCK (attr);
19832       if (TYPE_LENGTH (type) != blk->size)
19833         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19834                                                       TYPE_LENGTH (type));
19835       *bytes = blk->data;
19836       break;
19837
19838       /* The DW_AT_const_value attributes are supposed to carry the
19839          symbol's value "represented as it would be on the target
19840          architecture."  By the time we get here, it's already been
19841          converted to host endianness, so we just need to sign- or
19842          zero-extend it as appropriate.  */
19843     case DW_FORM_data1:
19844       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19845       break;
19846     case DW_FORM_data2:
19847       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19848       break;
19849     case DW_FORM_data4:
19850       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19851       break;
19852     case DW_FORM_data8:
19853       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19854       break;
19855
19856     case DW_FORM_sdata:
19857     case DW_FORM_implicit_const:
19858       *value = DW_SND (attr);
19859       break;
19860
19861     case DW_FORM_udata:
19862       *value = DW_UNSND (attr);
19863       break;
19864
19865     default:
19866       complaint (&symfile_complaints,
19867                  _("unsupported const value attribute form: '%s'"),
19868                  dwarf_form_name (attr->form));
19869       *value = 0;
19870       break;
19871     }
19872 }
19873
19874
19875 /* Copy constant value from an attribute to a symbol.  */
19876
19877 static void
19878 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19879                     struct dwarf2_cu *cu)
19880 {
19881   struct objfile *objfile = cu->objfile;
19882   LONGEST value;
19883   const gdb_byte *bytes;
19884   struct dwarf2_locexpr_baton *baton;
19885
19886   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19887                            SYMBOL_PRINT_NAME (sym),
19888                            &objfile->objfile_obstack, cu,
19889                            &value, &bytes, &baton);
19890
19891   if (baton != NULL)
19892     {
19893       SYMBOL_LOCATION_BATON (sym) = baton;
19894       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19895     }
19896   else if (bytes != NULL)
19897      {
19898       SYMBOL_VALUE_BYTES (sym) = bytes;
19899       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19900     }
19901   else
19902     {
19903       SYMBOL_VALUE (sym) = value;
19904       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19905     }
19906 }
19907
19908 /* Return the type of the die in question using its DW_AT_type attribute.  */
19909
19910 static struct type *
19911 die_type (struct die_info *die, struct dwarf2_cu *cu)
19912 {
19913   struct attribute *type_attr;
19914
19915   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19916   if (!type_attr)
19917     {
19918       /* A missing DW_AT_type represents a void type.  */
19919       return objfile_type (cu->objfile)->builtin_void;
19920     }
19921
19922   return lookup_die_type (die, type_attr, cu);
19923 }
19924
19925 /* True iff CU's producer generates GNAT Ada auxiliary information
19926    that allows to find parallel types through that information instead
19927    of having to do expensive parallel lookups by type name.  */
19928
19929 static int
19930 need_gnat_info (struct dwarf2_cu *cu)
19931 {
19932   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19933      of GNAT produces this auxiliary information, without any indication
19934      that it is produced.  Part of enhancing the FSF version of GNAT
19935      to produce that information will be to put in place an indicator
19936      that we can use in order to determine whether the descriptive type
19937      info is available or not.  One suggestion that has been made is
19938      to use a new attribute, attached to the CU die.  For now, assume
19939      that the descriptive type info is not available.  */
19940   return 0;
19941 }
19942
19943 /* Return the auxiliary type of the die in question using its
19944    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19945    attribute is not present.  */
19946
19947 static struct type *
19948 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19949 {
19950   struct attribute *type_attr;
19951
19952   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19953   if (!type_attr)
19954     return NULL;
19955
19956   return lookup_die_type (die, type_attr, cu);
19957 }
19958
19959 /* If DIE has a descriptive_type attribute, then set the TYPE's
19960    descriptive type accordingly.  */
19961
19962 static void
19963 set_descriptive_type (struct type *type, struct die_info *die,
19964                       struct dwarf2_cu *cu)
19965 {
19966   struct type *descriptive_type = die_descriptive_type (die, cu);
19967
19968   if (descriptive_type)
19969     {
19970       ALLOCATE_GNAT_AUX_TYPE (type);
19971       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19972     }
19973 }
19974
19975 /* Return the containing type of the die in question using its
19976    DW_AT_containing_type attribute.  */
19977
19978 static struct type *
19979 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19980 {
19981   struct attribute *type_attr;
19982
19983   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19984   if (!type_attr)
19985     error (_("Dwarf Error: Problem turning containing type into gdb type "
19986              "[in module %s]"), objfile_name (cu->objfile));
19987
19988   return lookup_die_type (die, type_attr, cu);
19989 }
19990
19991 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19992
19993 static struct type *
19994 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19995 {
19996   struct objfile *objfile = dwarf2_per_objfile->objfile;
19997   char *message, *saved;
19998
19999   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
20000                         objfile_name (objfile),
20001                         to_underlying (cu->header.sect_off),
20002                         to_underlying (die->sect_off));
20003   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
20004                                   message, strlen (message));
20005   xfree (message);
20006
20007   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
20008 }
20009
20010 /* Look up the type of DIE in CU using its type attribute ATTR.
20011    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
20012    DW_AT_containing_type.
20013    If there is no type substitute an error marker.  */
20014
20015 static struct type *
20016 lookup_die_type (struct die_info *die, const struct attribute *attr,
20017                  struct dwarf2_cu *cu)
20018 {
20019   struct objfile *objfile = cu->objfile;
20020   struct type *this_type;
20021
20022   gdb_assert (attr->name == DW_AT_type
20023               || attr->name == DW_AT_GNAT_descriptive_type
20024               || attr->name == DW_AT_containing_type);
20025
20026   /* First see if we have it cached.  */
20027
20028   if (attr->form == DW_FORM_GNU_ref_alt)
20029     {
20030       struct dwarf2_per_cu_data *per_cu;
20031       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20032
20033       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20034       this_type = get_die_type_at_offset (sect_off, per_cu);
20035     }
20036   else if (attr_form_is_ref (attr))
20037     {
20038       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20039
20040       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20041     }
20042   else if (attr->form == DW_FORM_ref_sig8)
20043     {
20044       ULONGEST signature = DW_SIGNATURE (attr);
20045
20046       return get_signatured_type (die, signature, cu);
20047     }
20048   else
20049     {
20050       complaint (&symfile_complaints,
20051                  _("Dwarf Error: Bad type attribute %s in DIE"
20052                    " at 0x%x [in module %s]"),
20053                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20054                  objfile_name (objfile));
20055       return build_error_marker_type (cu, die);
20056     }
20057
20058   /* If not cached we need to read it in.  */
20059
20060   if (this_type == NULL)
20061     {
20062       struct die_info *type_die = NULL;
20063       struct dwarf2_cu *type_cu = cu;
20064
20065       if (attr_form_is_ref (attr))
20066         type_die = follow_die_ref (die, attr, &type_cu);
20067       if (type_die == NULL)
20068         return build_error_marker_type (cu, die);
20069       /* If we find the type now, it's probably because the type came
20070          from an inter-CU reference and the type's CU got expanded before
20071          ours.  */
20072       this_type = read_type_die (type_die, type_cu);
20073     }
20074
20075   /* If we still don't have a type use an error marker.  */
20076
20077   if (this_type == NULL)
20078     return build_error_marker_type (cu, die);
20079
20080   return this_type;
20081 }
20082
20083 /* Return the type in DIE, CU.
20084    Returns NULL for invalid types.
20085
20086    This first does a lookup in die_type_hash,
20087    and only reads the die in if necessary.
20088
20089    NOTE: This can be called when reading in partial or full symbols.  */
20090
20091 static struct type *
20092 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20093 {
20094   struct type *this_type;
20095
20096   this_type = get_die_type (die, cu);
20097   if (this_type)
20098     return this_type;
20099
20100   return read_type_die_1 (die, cu);
20101 }
20102
20103 /* Read the type in DIE, CU.
20104    Returns NULL for invalid types.  */
20105
20106 static struct type *
20107 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20108 {
20109   struct type *this_type = NULL;
20110
20111   switch (die->tag)
20112     {
20113     case DW_TAG_class_type:
20114     case DW_TAG_interface_type:
20115     case DW_TAG_structure_type:
20116     case DW_TAG_union_type:
20117       this_type = read_structure_type (die, cu);
20118       break;
20119     case DW_TAG_enumeration_type:
20120       this_type = read_enumeration_type (die, cu);
20121       break;
20122     case DW_TAG_subprogram:
20123     case DW_TAG_subroutine_type:
20124     case DW_TAG_inlined_subroutine:
20125       this_type = read_subroutine_type (die, cu);
20126       break;
20127     case DW_TAG_array_type:
20128       this_type = read_array_type (die, cu);
20129       break;
20130     case DW_TAG_set_type:
20131       this_type = read_set_type (die, cu);
20132       break;
20133     case DW_TAG_pointer_type:
20134       this_type = read_tag_pointer_type (die, cu);
20135       break;
20136     case DW_TAG_ptr_to_member_type:
20137       this_type = read_tag_ptr_to_member_type (die, cu);
20138       break;
20139     case DW_TAG_reference_type:
20140       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20141       break;
20142     case DW_TAG_rvalue_reference_type:
20143       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20144       break;
20145     case DW_TAG_const_type:
20146       this_type = read_tag_const_type (die, cu);
20147       break;
20148     case DW_TAG_volatile_type:
20149       this_type = read_tag_volatile_type (die, cu);
20150       break;
20151     case DW_TAG_restrict_type:
20152       this_type = read_tag_restrict_type (die, cu);
20153       break;
20154     case DW_TAG_string_type:
20155       this_type = read_tag_string_type (die, cu);
20156       break;
20157     case DW_TAG_typedef:
20158       this_type = read_typedef (die, cu);
20159       break;
20160     case DW_TAG_subrange_type:
20161       this_type = read_subrange_type (die, cu);
20162       break;
20163     case DW_TAG_base_type:
20164       this_type = read_base_type (die, cu);
20165       break;
20166     case DW_TAG_unspecified_type:
20167       this_type = read_unspecified_type (die, cu);
20168       break;
20169     case DW_TAG_namespace:
20170       this_type = read_namespace_type (die, cu);
20171       break;
20172     case DW_TAG_module:
20173       this_type = read_module_type (die, cu);
20174       break;
20175     case DW_TAG_atomic_type:
20176       this_type = read_tag_atomic_type (die, cu);
20177       break;
20178     default:
20179       complaint (&symfile_complaints,
20180                  _("unexpected tag in read_type_die: '%s'"),
20181                  dwarf_tag_name (die->tag));
20182       break;
20183     }
20184
20185   return this_type;
20186 }
20187
20188 /* See if we can figure out if the class lives in a namespace.  We do
20189    this by looking for a member function; its demangled name will
20190    contain namespace info, if there is any.
20191    Return the computed name or NULL.
20192    Space for the result is allocated on the objfile's obstack.
20193    This is the full-die version of guess_partial_die_structure_name.
20194    In this case we know DIE has no useful parent.  */
20195
20196 static char *
20197 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20198 {
20199   struct die_info *spec_die;
20200   struct dwarf2_cu *spec_cu;
20201   struct die_info *child;
20202
20203   spec_cu = cu;
20204   spec_die = die_specification (die, &spec_cu);
20205   if (spec_die != NULL)
20206     {
20207       die = spec_die;
20208       cu = spec_cu;
20209     }
20210
20211   for (child = die->child;
20212        child != NULL;
20213        child = child->sibling)
20214     {
20215       if (child->tag == DW_TAG_subprogram)
20216         {
20217           const char *linkage_name = dw2_linkage_name (child, cu);
20218
20219           if (linkage_name != NULL)
20220             {
20221               char *actual_name
20222                 = language_class_name_from_physname (cu->language_defn,
20223                                                      linkage_name);
20224               char *name = NULL;
20225
20226               if (actual_name != NULL)
20227                 {
20228                   const char *die_name = dwarf2_name (die, cu);
20229
20230                   if (die_name != NULL
20231                       && strcmp (die_name, actual_name) != 0)
20232                     {
20233                       /* Strip off the class name from the full name.
20234                          We want the prefix.  */
20235                       int die_name_len = strlen (die_name);
20236                       int actual_name_len = strlen (actual_name);
20237
20238                       /* Test for '::' as a sanity check.  */
20239                       if (actual_name_len > die_name_len + 2
20240                           && actual_name[actual_name_len
20241                                          - die_name_len - 1] == ':')
20242                         name = (char *) obstack_copy0 (
20243                           &cu->objfile->per_bfd->storage_obstack,
20244                           actual_name, actual_name_len - die_name_len - 2);
20245                     }
20246                 }
20247               xfree (actual_name);
20248               return name;
20249             }
20250         }
20251     }
20252
20253   return NULL;
20254 }
20255
20256 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20257    prefix part in such case.  See
20258    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20259
20260 static const char *
20261 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20262 {
20263   struct attribute *attr;
20264   const char *base;
20265
20266   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20267       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20268     return NULL;
20269
20270   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20271     return NULL;
20272
20273   attr = dw2_linkage_name_attr (die, cu);
20274   if (attr == NULL || DW_STRING (attr) == NULL)
20275     return NULL;
20276
20277   /* dwarf2_name had to be already called.  */
20278   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20279
20280   /* Strip the base name, keep any leading namespaces/classes.  */
20281   base = strrchr (DW_STRING (attr), ':');
20282   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20283     return "";
20284
20285   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20286                                  DW_STRING (attr),
20287                                  &base[-1] - DW_STRING (attr));
20288 }
20289
20290 /* Return the name of the namespace/class that DIE is defined within,
20291    or "" if we can't tell.  The caller should not xfree the result.
20292
20293    For example, if we're within the method foo() in the following
20294    code:
20295
20296    namespace N {
20297      class C {
20298        void foo () {
20299        }
20300      };
20301    }
20302
20303    then determine_prefix on foo's die will return "N::C".  */
20304
20305 static const char *
20306 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20307 {
20308   struct die_info *parent, *spec_die;
20309   struct dwarf2_cu *spec_cu;
20310   struct type *parent_type;
20311   const char *retval;
20312
20313   if (cu->language != language_cplus
20314       && cu->language != language_fortran && cu->language != language_d
20315       && cu->language != language_rust)
20316     return "";
20317
20318   retval = anonymous_struct_prefix (die, cu);
20319   if (retval)
20320     return retval;
20321
20322   /* We have to be careful in the presence of DW_AT_specification.
20323      For example, with GCC 3.4, given the code
20324
20325      namespace N {
20326        void foo() {
20327          // Definition of N::foo.
20328        }
20329      }
20330
20331      then we'll have a tree of DIEs like this:
20332
20333      1: DW_TAG_compile_unit
20334        2: DW_TAG_namespace        // N
20335          3: DW_TAG_subprogram     // declaration of N::foo
20336        4: DW_TAG_subprogram       // definition of N::foo
20337             DW_AT_specification   // refers to die #3
20338
20339      Thus, when processing die #4, we have to pretend that we're in
20340      the context of its DW_AT_specification, namely the contex of die
20341      #3.  */
20342   spec_cu = cu;
20343   spec_die = die_specification (die, &spec_cu);
20344   if (spec_die == NULL)
20345     parent = die->parent;
20346   else
20347     {
20348       parent = spec_die->parent;
20349       cu = spec_cu;
20350     }
20351
20352   if (parent == NULL)
20353     return "";
20354   else if (parent->building_fullname)
20355     {
20356       const char *name;
20357       const char *parent_name;
20358
20359       /* It has been seen on RealView 2.2 built binaries,
20360          DW_TAG_template_type_param types actually _defined_ as
20361          children of the parent class:
20362
20363          enum E {};
20364          template class <class Enum> Class{};
20365          Class<enum E> class_e;
20366
20367          1: DW_TAG_class_type (Class)
20368            2: DW_TAG_enumeration_type (E)
20369              3: DW_TAG_enumerator (enum1:0)
20370              3: DW_TAG_enumerator (enum2:1)
20371              ...
20372            2: DW_TAG_template_type_param
20373               DW_AT_type  DW_FORM_ref_udata (E)
20374
20375          Besides being broken debug info, it can put GDB into an
20376          infinite loop.  Consider:
20377
20378          When we're building the full name for Class<E>, we'll start
20379          at Class, and go look over its template type parameters,
20380          finding E.  We'll then try to build the full name of E, and
20381          reach here.  We're now trying to build the full name of E,
20382          and look over the parent DIE for containing scope.  In the
20383          broken case, if we followed the parent DIE of E, we'd again
20384          find Class, and once again go look at its template type
20385          arguments, etc., etc.  Simply don't consider such parent die
20386          as source-level parent of this die (it can't be, the language
20387          doesn't allow it), and break the loop here.  */
20388       name = dwarf2_name (die, cu);
20389       parent_name = dwarf2_name (parent, cu);
20390       complaint (&symfile_complaints,
20391                  _("template param type '%s' defined within parent '%s'"),
20392                  name ? name : "<unknown>",
20393                  parent_name ? parent_name : "<unknown>");
20394       return "";
20395     }
20396   else
20397     switch (parent->tag)
20398       {
20399       case DW_TAG_namespace:
20400         parent_type = read_type_die (parent, cu);
20401         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20402            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20403            Work around this problem here.  */
20404         if (cu->language == language_cplus
20405             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20406           return "";
20407         /* We give a name to even anonymous namespaces.  */
20408         return TYPE_TAG_NAME (parent_type);
20409       case DW_TAG_class_type:
20410       case DW_TAG_interface_type:
20411       case DW_TAG_structure_type:
20412       case DW_TAG_union_type:
20413       case DW_TAG_module:
20414         parent_type = read_type_die (parent, cu);
20415         if (TYPE_TAG_NAME (parent_type) != NULL)
20416           return TYPE_TAG_NAME (parent_type);
20417         else
20418           /* An anonymous structure is only allowed non-static data
20419              members; no typedefs, no member functions, et cetera.
20420              So it does not need a prefix.  */
20421           return "";
20422       case DW_TAG_compile_unit:
20423       case DW_TAG_partial_unit:
20424         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20425         if (cu->language == language_cplus
20426             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20427             && die->child != NULL
20428             && (die->tag == DW_TAG_class_type
20429                 || die->tag == DW_TAG_structure_type
20430                 || die->tag == DW_TAG_union_type))
20431           {
20432             char *name = guess_full_die_structure_name (die, cu);
20433             if (name != NULL)
20434               return name;
20435           }
20436         return "";
20437       case DW_TAG_enumeration_type:
20438         parent_type = read_type_die (parent, cu);
20439         if (TYPE_DECLARED_CLASS (parent_type))
20440           {
20441             if (TYPE_TAG_NAME (parent_type) != NULL)
20442               return TYPE_TAG_NAME (parent_type);
20443             return "";
20444           }
20445         /* Fall through.  */
20446       default:
20447         return determine_prefix (parent, cu);
20448       }
20449 }
20450
20451 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20452    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20453    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20454    an obconcat, otherwise allocate storage for the result.  The CU argument is
20455    used to determine the language and hence, the appropriate separator.  */
20456
20457 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20458
20459 static char *
20460 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20461                  int physname, struct dwarf2_cu *cu)
20462 {
20463   const char *lead = "";
20464   const char *sep;
20465
20466   if (suffix == NULL || suffix[0] == '\0'
20467       || prefix == NULL || prefix[0] == '\0')
20468     sep = "";
20469   else if (cu->language == language_d)
20470     {
20471       /* For D, the 'main' function could be defined in any module, but it
20472          should never be prefixed.  */
20473       if (strcmp (suffix, "D main") == 0)
20474         {
20475           prefix = "";
20476           sep = "";
20477         }
20478       else
20479         sep = ".";
20480     }
20481   else if (cu->language == language_fortran && physname)
20482     {
20483       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20484          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20485
20486       lead = "__";
20487       sep = "_MOD_";
20488     }
20489   else
20490     sep = "::";
20491
20492   if (prefix == NULL)
20493     prefix = "";
20494   if (suffix == NULL)
20495     suffix = "";
20496
20497   if (obs == NULL)
20498     {
20499       char *retval
20500         = ((char *)
20501            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20502
20503       strcpy (retval, lead);
20504       strcat (retval, prefix);
20505       strcat (retval, sep);
20506       strcat (retval, suffix);
20507       return retval;
20508     }
20509   else
20510     {
20511       /* We have an obstack.  */
20512       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20513     }
20514 }
20515
20516 /* Return sibling of die, NULL if no sibling.  */
20517
20518 static struct die_info *
20519 sibling_die (struct die_info *die)
20520 {
20521   return die->sibling;
20522 }
20523
20524 /* Get name of a die, return NULL if not found.  */
20525
20526 static const char *
20527 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20528                           struct obstack *obstack)
20529 {
20530   if (name && cu->language == language_cplus)
20531     {
20532       std::string canon_name = cp_canonicalize_string (name);
20533
20534       if (!canon_name.empty ())
20535         {
20536           if (canon_name != name)
20537             name = (const char *) obstack_copy0 (obstack,
20538                                                  canon_name.c_str (),
20539                                                  canon_name.length ());
20540         }
20541     }
20542
20543   return name;
20544 }
20545
20546 /* Get name of a die, return NULL if not found.
20547    Anonymous namespaces are converted to their magic string.  */
20548
20549 static const char *
20550 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20551 {
20552   struct attribute *attr;
20553
20554   attr = dwarf2_attr (die, DW_AT_name, cu);
20555   if ((!attr || !DW_STRING (attr))
20556       && die->tag != DW_TAG_namespace
20557       && die->tag != DW_TAG_class_type
20558       && die->tag != DW_TAG_interface_type
20559       && die->tag != DW_TAG_structure_type
20560       && die->tag != DW_TAG_union_type)
20561     return NULL;
20562
20563   switch (die->tag)
20564     {
20565     case DW_TAG_compile_unit:
20566     case DW_TAG_partial_unit:
20567       /* Compilation units have a DW_AT_name that is a filename, not
20568          a source language identifier.  */
20569     case DW_TAG_enumeration_type:
20570     case DW_TAG_enumerator:
20571       /* These tags always have simple identifiers already; no need
20572          to canonicalize them.  */
20573       return DW_STRING (attr);
20574
20575     case DW_TAG_namespace:
20576       if (attr != NULL && DW_STRING (attr) != NULL)
20577         return DW_STRING (attr);
20578       return CP_ANONYMOUS_NAMESPACE_STR;
20579
20580     case DW_TAG_class_type:
20581     case DW_TAG_interface_type:
20582     case DW_TAG_structure_type:
20583     case DW_TAG_union_type:
20584       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20585          structures or unions.  These were of the form "._%d" in GCC 4.1,
20586          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20587          and GCC 4.4.  We work around this problem by ignoring these.  */
20588       if (attr && DW_STRING (attr)
20589           && (startswith (DW_STRING (attr), "._")
20590               || startswith (DW_STRING (attr), "<anonymous")))
20591         return NULL;
20592
20593       /* GCC might emit a nameless typedef that has a linkage name.  See
20594          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20595       if (!attr || DW_STRING (attr) == NULL)
20596         {
20597           char *demangled = NULL;
20598
20599           attr = dw2_linkage_name_attr (die, cu);
20600           if (attr == NULL || DW_STRING (attr) == NULL)
20601             return NULL;
20602
20603           /* Avoid demangling DW_STRING (attr) the second time on a second
20604              call for the same DIE.  */
20605           if (!DW_STRING_IS_CANONICAL (attr))
20606             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20607
20608           if (demangled)
20609             {
20610               const char *base;
20611
20612               /* FIXME: we already did this for the partial symbol... */
20613               DW_STRING (attr)
20614                 = ((const char *)
20615                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20616                                   demangled, strlen (demangled)));
20617               DW_STRING_IS_CANONICAL (attr) = 1;
20618               xfree (demangled);
20619
20620               /* Strip any leading namespaces/classes, keep only the base name.
20621                  DW_AT_name for named DIEs does not contain the prefixes.  */
20622               base = strrchr (DW_STRING (attr), ':');
20623               if (base && base > DW_STRING (attr) && base[-1] == ':')
20624                 return &base[1];
20625               else
20626                 return DW_STRING (attr);
20627             }
20628         }
20629       break;
20630
20631     default:
20632       break;
20633     }
20634
20635   if (!DW_STRING_IS_CANONICAL (attr))
20636     {
20637       DW_STRING (attr)
20638         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20639                                     &cu->objfile->per_bfd->storage_obstack);
20640       DW_STRING_IS_CANONICAL (attr) = 1;
20641     }
20642   return DW_STRING (attr);
20643 }
20644
20645 /* Return the die that this die in an extension of, or NULL if there
20646    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20647    containing the return value on output.  */
20648
20649 static struct die_info *
20650 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20651 {
20652   struct attribute *attr;
20653
20654   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20655   if (attr == NULL)
20656     return NULL;
20657
20658   return follow_die_ref (die, attr, ext_cu);
20659 }
20660
20661 /* Convert a DIE tag into its string name.  */
20662
20663 static const char *
20664 dwarf_tag_name (unsigned tag)
20665 {
20666   const char *name = get_DW_TAG_name (tag);
20667
20668   if (name == NULL)
20669     return "DW_TAG_<unknown>";
20670
20671   return name;
20672 }
20673
20674 /* Convert a DWARF attribute code into its string name.  */
20675
20676 static const char *
20677 dwarf_attr_name (unsigned attr)
20678 {
20679   const char *name;
20680
20681 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20682   if (attr == DW_AT_MIPS_fde)
20683     return "DW_AT_MIPS_fde";
20684 #else
20685   if (attr == DW_AT_HP_block_index)
20686     return "DW_AT_HP_block_index";
20687 #endif
20688
20689   name = get_DW_AT_name (attr);
20690
20691   if (name == NULL)
20692     return "DW_AT_<unknown>";
20693
20694   return name;
20695 }
20696
20697 /* Convert a DWARF value form code into its string name.  */
20698
20699 static const char *
20700 dwarf_form_name (unsigned form)
20701 {
20702   const char *name = get_DW_FORM_name (form);
20703
20704   if (name == NULL)
20705     return "DW_FORM_<unknown>";
20706
20707   return name;
20708 }
20709
20710 static const char *
20711 dwarf_bool_name (unsigned mybool)
20712 {
20713   if (mybool)
20714     return "TRUE";
20715   else
20716     return "FALSE";
20717 }
20718
20719 /* Convert a DWARF type code into its string name.  */
20720
20721 static const char *
20722 dwarf_type_encoding_name (unsigned enc)
20723 {
20724   const char *name = get_DW_ATE_name (enc);
20725
20726   if (name == NULL)
20727     return "DW_ATE_<unknown>";
20728
20729   return name;
20730 }
20731
20732 static void
20733 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20734 {
20735   unsigned int i;
20736
20737   print_spaces (indent, f);
20738   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20739                       dwarf_tag_name (die->tag), die->abbrev,
20740                       to_underlying (die->sect_off));
20741
20742   if (die->parent != NULL)
20743     {
20744       print_spaces (indent, f);
20745       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20746                           to_underlying (die->parent->sect_off));
20747     }
20748
20749   print_spaces (indent, f);
20750   fprintf_unfiltered (f, "  has children: %s\n",
20751            dwarf_bool_name (die->child != NULL));
20752
20753   print_spaces (indent, f);
20754   fprintf_unfiltered (f, "  attributes:\n");
20755
20756   for (i = 0; i < die->num_attrs; ++i)
20757     {
20758       print_spaces (indent, f);
20759       fprintf_unfiltered (f, "    %s (%s) ",
20760                dwarf_attr_name (die->attrs[i].name),
20761                dwarf_form_name (die->attrs[i].form));
20762
20763       switch (die->attrs[i].form)
20764         {
20765         case DW_FORM_addr:
20766         case DW_FORM_GNU_addr_index:
20767           fprintf_unfiltered (f, "address: ");
20768           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20769           break;
20770         case DW_FORM_block2:
20771         case DW_FORM_block4:
20772         case DW_FORM_block:
20773         case DW_FORM_block1:
20774           fprintf_unfiltered (f, "block: size %s",
20775                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20776           break;
20777         case DW_FORM_exprloc:
20778           fprintf_unfiltered (f, "expression: size %s",
20779                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20780           break;
20781         case DW_FORM_data16:
20782           fprintf_unfiltered (f, "constant of 16 bytes");
20783           break;
20784         case DW_FORM_ref_addr:
20785           fprintf_unfiltered (f, "ref address: ");
20786           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20787           break;
20788         case DW_FORM_GNU_ref_alt:
20789           fprintf_unfiltered (f, "alt ref address: ");
20790           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20791           break;
20792         case DW_FORM_ref1:
20793         case DW_FORM_ref2:
20794         case DW_FORM_ref4:
20795         case DW_FORM_ref8:
20796         case DW_FORM_ref_udata:
20797           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20798                               (long) (DW_UNSND (&die->attrs[i])));
20799           break;
20800         case DW_FORM_data1:
20801         case DW_FORM_data2:
20802         case DW_FORM_data4:
20803         case DW_FORM_data8:
20804         case DW_FORM_udata:
20805         case DW_FORM_sdata:
20806           fprintf_unfiltered (f, "constant: %s",
20807                               pulongest (DW_UNSND (&die->attrs[i])));
20808           break;
20809         case DW_FORM_sec_offset:
20810           fprintf_unfiltered (f, "section offset: %s",
20811                               pulongest (DW_UNSND (&die->attrs[i])));
20812           break;
20813         case DW_FORM_ref_sig8:
20814           fprintf_unfiltered (f, "signature: %s",
20815                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20816           break;
20817         case DW_FORM_string:
20818         case DW_FORM_strp:
20819         case DW_FORM_line_strp:
20820         case DW_FORM_GNU_str_index:
20821         case DW_FORM_GNU_strp_alt:
20822           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20823                    DW_STRING (&die->attrs[i])
20824                    ? DW_STRING (&die->attrs[i]) : "",
20825                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20826           break;
20827         case DW_FORM_flag:
20828           if (DW_UNSND (&die->attrs[i]))
20829             fprintf_unfiltered (f, "flag: TRUE");
20830           else
20831             fprintf_unfiltered (f, "flag: FALSE");
20832           break;
20833         case DW_FORM_flag_present:
20834           fprintf_unfiltered (f, "flag: TRUE");
20835           break;
20836         case DW_FORM_indirect:
20837           /* The reader will have reduced the indirect form to
20838              the "base form" so this form should not occur.  */
20839           fprintf_unfiltered (f, 
20840                               "unexpected attribute form: DW_FORM_indirect");
20841           break;
20842         case DW_FORM_implicit_const:
20843           fprintf_unfiltered (f, "constant: %s",
20844                               plongest (DW_SND (&die->attrs[i])));
20845           break;
20846         default:
20847           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20848                    die->attrs[i].form);
20849           break;
20850         }
20851       fprintf_unfiltered (f, "\n");
20852     }
20853 }
20854
20855 static void
20856 dump_die_for_error (struct die_info *die)
20857 {
20858   dump_die_shallow (gdb_stderr, 0, die);
20859 }
20860
20861 static void
20862 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20863 {
20864   int indent = level * 4;
20865
20866   gdb_assert (die != NULL);
20867
20868   if (level >= max_level)
20869     return;
20870
20871   dump_die_shallow (f, indent, die);
20872
20873   if (die->child != NULL)
20874     {
20875       print_spaces (indent, f);
20876       fprintf_unfiltered (f, "  Children:");
20877       if (level + 1 < max_level)
20878         {
20879           fprintf_unfiltered (f, "\n");
20880           dump_die_1 (f, level + 1, max_level, die->child);
20881         }
20882       else
20883         {
20884           fprintf_unfiltered (f,
20885                               " [not printed, max nesting level reached]\n");
20886         }
20887     }
20888
20889   if (die->sibling != NULL && level > 0)
20890     {
20891       dump_die_1 (f, level, max_level, die->sibling);
20892     }
20893 }
20894
20895 /* This is called from the pdie macro in gdbinit.in.
20896    It's not static so gcc will keep a copy callable from gdb.  */
20897
20898 void
20899 dump_die (struct die_info *die, int max_level)
20900 {
20901   dump_die_1 (gdb_stdlog, 0, max_level, die);
20902 }
20903
20904 static void
20905 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20906 {
20907   void **slot;
20908
20909   slot = htab_find_slot_with_hash (cu->die_hash, die,
20910                                    to_underlying (die->sect_off),
20911                                    INSERT);
20912
20913   *slot = die;
20914 }
20915
20916 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20917    required kind.  */
20918
20919 static sect_offset
20920 dwarf2_get_ref_die_offset (const struct attribute *attr)
20921 {
20922   if (attr_form_is_ref (attr))
20923     return (sect_offset) DW_UNSND (attr);
20924
20925   complaint (&symfile_complaints,
20926              _("unsupported die ref attribute form: '%s'"),
20927              dwarf_form_name (attr->form));
20928   return {};
20929 }
20930
20931 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20932  * the value held by the attribute is not constant.  */
20933
20934 static LONGEST
20935 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20936 {
20937   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20938     return DW_SND (attr);
20939   else if (attr->form == DW_FORM_udata
20940            || attr->form == DW_FORM_data1
20941            || attr->form == DW_FORM_data2
20942            || attr->form == DW_FORM_data4
20943            || attr->form == DW_FORM_data8)
20944     return DW_UNSND (attr);
20945   else
20946     {
20947       /* For DW_FORM_data16 see attr_form_is_constant.  */
20948       complaint (&symfile_complaints,
20949                  _("Attribute value is not a constant (%s)"),
20950                  dwarf_form_name (attr->form));
20951       return default_value;
20952     }
20953 }
20954
20955 /* Follow reference or signature attribute ATTR of SRC_DIE.
20956    On entry *REF_CU is the CU of SRC_DIE.
20957    On exit *REF_CU is the CU of the result.  */
20958
20959 static struct die_info *
20960 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20961                        struct dwarf2_cu **ref_cu)
20962 {
20963   struct die_info *die;
20964
20965   if (attr_form_is_ref (attr))
20966     die = follow_die_ref (src_die, attr, ref_cu);
20967   else if (attr->form == DW_FORM_ref_sig8)
20968     die = follow_die_sig (src_die, attr, ref_cu);
20969   else
20970     {
20971       dump_die_for_error (src_die);
20972       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20973              objfile_name ((*ref_cu)->objfile));
20974     }
20975
20976   return die;
20977 }
20978
20979 /* Follow reference OFFSET.
20980    On entry *REF_CU is the CU of the source die referencing OFFSET.
20981    On exit *REF_CU is the CU of the result.
20982    Returns NULL if OFFSET is invalid.  */
20983
20984 static struct die_info *
20985 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20986                    struct dwarf2_cu **ref_cu)
20987 {
20988   struct die_info temp_die;
20989   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20990
20991   gdb_assert (cu->per_cu != NULL);
20992
20993   target_cu = cu;
20994
20995   if (cu->per_cu->is_debug_types)
20996     {
20997       /* .debug_types CUs cannot reference anything outside their CU.
20998          If they need to, they have to reference a signatured type via
20999          DW_FORM_ref_sig8.  */
21000       if (!offset_in_cu_p (&cu->header, sect_off))
21001         return NULL;
21002     }
21003   else if (offset_in_dwz != cu->per_cu->is_dwz
21004            || !offset_in_cu_p (&cu->header, sect_off))
21005     {
21006       struct dwarf2_per_cu_data *per_cu;
21007
21008       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
21009                                                  cu->objfile);
21010
21011       /* If necessary, add it to the queue and load its DIEs.  */
21012       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
21013         load_full_comp_unit (per_cu, cu->language);
21014
21015       target_cu = per_cu->cu;
21016     }
21017   else if (cu->dies == NULL)
21018     {
21019       /* We're loading full DIEs during partial symbol reading.  */
21020       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21021       load_full_comp_unit (cu->per_cu, language_minimal);
21022     }
21023
21024   *ref_cu = target_cu;
21025   temp_die.sect_off = sect_off;
21026   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21027                                                   &temp_die,
21028                                                   to_underlying (sect_off));
21029 }
21030
21031 /* Follow reference attribute ATTR of SRC_DIE.
21032    On entry *REF_CU is the CU of SRC_DIE.
21033    On exit *REF_CU is the CU of the result.  */
21034
21035 static struct die_info *
21036 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21037                 struct dwarf2_cu **ref_cu)
21038 {
21039   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21040   struct dwarf2_cu *cu = *ref_cu;
21041   struct die_info *die;
21042
21043   die = follow_die_offset (sect_off,
21044                            (attr->form == DW_FORM_GNU_ref_alt
21045                             || cu->per_cu->is_dwz),
21046                            ref_cu);
21047   if (!die)
21048     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21049            "at 0x%x [in module %s]"),
21050            to_underlying (sect_off), to_underlying (src_die->sect_off),
21051            objfile_name (cu->objfile));
21052
21053   return die;
21054 }
21055
21056 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21057    Returned value is intended for DW_OP_call*.  Returned
21058    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21059
21060 struct dwarf2_locexpr_baton
21061 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21062                                struct dwarf2_per_cu_data *per_cu,
21063                                CORE_ADDR (*get_frame_pc) (void *baton),
21064                                void *baton)
21065 {
21066   struct dwarf2_cu *cu;
21067   struct die_info *die;
21068   struct attribute *attr;
21069   struct dwarf2_locexpr_baton retval;
21070
21071   dw2_setup (per_cu->objfile);
21072
21073   if (per_cu->cu == NULL)
21074     load_cu (per_cu);
21075   cu = per_cu->cu;
21076   if (cu == NULL)
21077     {
21078       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21079          Instead just throw an error, not much else we can do.  */
21080       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21081              to_underlying (sect_off), objfile_name (per_cu->objfile));
21082     }
21083
21084   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21085   if (!die)
21086     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21087            to_underlying (sect_off), objfile_name (per_cu->objfile));
21088
21089   attr = dwarf2_attr (die, DW_AT_location, cu);
21090   if (!attr)
21091     {
21092       /* DWARF: "If there is no such attribute, then there is no effect.".
21093          DATA is ignored if SIZE is 0.  */
21094
21095       retval.data = NULL;
21096       retval.size = 0;
21097     }
21098   else if (attr_form_is_section_offset (attr))
21099     {
21100       struct dwarf2_loclist_baton loclist_baton;
21101       CORE_ADDR pc = (*get_frame_pc) (baton);
21102       size_t size;
21103
21104       fill_in_loclist_baton (cu, &loclist_baton, attr);
21105
21106       retval.data = dwarf2_find_location_expression (&loclist_baton,
21107                                                      &size, pc);
21108       retval.size = size;
21109     }
21110   else
21111     {
21112       if (!attr_form_is_block (attr))
21113         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21114                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21115                to_underlying (sect_off), objfile_name (per_cu->objfile));
21116
21117       retval.data = DW_BLOCK (attr)->data;
21118       retval.size = DW_BLOCK (attr)->size;
21119     }
21120   retval.per_cu = cu->per_cu;
21121
21122   age_cached_comp_units ();
21123
21124   return retval;
21125 }
21126
21127 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21128    offset.  */
21129
21130 struct dwarf2_locexpr_baton
21131 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21132                              struct dwarf2_per_cu_data *per_cu,
21133                              CORE_ADDR (*get_frame_pc) (void *baton),
21134                              void *baton)
21135 {
21136   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21137
21138   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21139 }
21140
21141 /* Write a constant of a given type as target-ordered bytes into
21142    OBSTACK.  */
21143
21144 static const gdb_byte *
21145 write_constant_as_bytes (struct obstack *obstack,
21146                          enum bfd_endian byte_order,
21147                          struct type *type,
21148                          ULONGEST value,
21149                          LONGEST *len)
21150 {
21151   gdb_byte *result;
21152
21153   *len = TYPE_LENGTH (type);
21154   result = (gdb_byte *) obstack_alloc (obstack, *len);
21155   store_unsigned_integer (result, *len, byte_order, value);
21156
21157   return result;
21158 }
21159
21160 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21161    pointer to the constant bytes and set LEN to the length of the
21162    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21163    does not have a DW_AT_const_value, return NULL.  */
21164
21165 const gdb_byte *
21166 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21167                              struct dwarf2_per_cu_data *per_cu,
21168                              struct obstack *obstack,
21169                              LONGEST *len)
21170 {
21171   struct dwarf2_cu *cu;
21172   struct die_info *die;
21173   struct attribute *attr;
21174   const gdb_byte *result = NULL;
21175   struct type *type;
21176   LONGEST value;
21177   enum bfd_endian byte_order;
21178
21179   dw2_setup (per_cu->objfile);
21180
21181   if (per_cu->cu == NULL)
21182     load_cu (per_cu);
21183   cu = per_cu->cu;
21184   if (cu == NULL)
21185     {
21186       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21187          Instead just throw an error, not much else we can do.  */
21188       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21189              to_underlying (sect_off), objfile_name (per_cu->objfile));
21190     }
21191
21192   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21193   if (!die)
21194     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21195            to_underlying (sect_off), objfile_name (per_cu->objfile));
21196
21197
21198   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21199   if (attr == NULL)
21200     return NULL;
21201
21202   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21203                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21204
21205   switch (attr->form)
21206     {
21207     case DW_FORM_addr:
21208     case DW_FORM_GNU_addr_index:
21209       {
21210         gdb_byte *tem;
21211
21212         *len = cu->header.addr_size;
21213         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21214         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21215         result = tem;
21216       }
21217       break;
21218     case DW_FORM_string:
21219     case DW_FORM_strp:
21220     case DW_FORM_GNU_str_index:
21221     case DW_FORM_GNU_strp_alt:
21222       /* DW_STRING is already allocated on the objfile obstack, point
21223          directly to it.  */
21224       result = (const gdb_byte *) DW_STRING (attr);
21225       *len = strlen (DW_STRING (attr));
21226       break;
21227     case DW_FORM_block1:
21228     case DW_FORM_block2:
21229     case DW_FORM_block4:
21230     case DW_FORM_block:
21231     case DW_FORM_exprloc:
21232     case DW_FORM_data16:
21233       result = DW_BLOCK (attr)->data;
21234       *len = DW_BLOCK (attr)->size;
21235       break;
21236
21237       /* The DW_AT_const_value attributes are supposed to carry the
21238          symbol's value "represented as it would be on the target
21239          architecture."  By the time we get here, it's already been
21240          converted to host endianness, so we just need to sign- or
21241          zero-extend it as appropriate.  */
21242     case DW_FORM_data1:
21243       type = die_type (die, cu);
21244       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21245       if (result == NULL)
21246         result = write_constant_as_bytes (obstack, byte_order,
21247                                           type, value, len);
21248       break;
21249     case DW_FORM_data2:
21250       type = die_type (die, cu);
21251       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21252       if (result == NULL)
21253         result = write_constant_as_bytes (obstack, byte_order,
21254                                           type, value, len);
21255       break;
21256     case DW_FORM_data4:
21257       type = die_type (die, cu);
21258       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21259       if (result == NULL)
21260         result = write_constant_as_bytes (obstack, byte_order,
21261                                           type, value, len);
21262       break;
21263     case DW_FORM_data8:
21264       type = die_type (die, cu);
21265       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21266       if (result == NULL)
21267         result = write_constant_as_bytes (obstack, byte_order,
21268                                           type, value, len);
21269       break;
21270
21271     case DW_FORM_sdata:
21272     case DW_FORM_implicit_const:
21273       type = die_type (die, cu);
21274       result = write_constant_as_bytes (obstack, byte_order,
21275                                         type, DW_SND (attr), len);
21276       break;
21277
21278     case DW_FORM_udata:
21279       type = die_type (die, cu);
21280       result = write_constant_as_bytes (obstack, byte_order,
21281                                         type, DW_UNSND (attr), len);
21282       break;
21283
21284     default:
21285       complaint (&symfile_complaints,
21286                  _("unsupported const value attribute form: '%s'"),
21287                  dwarf_form_name (attr->form));
21288       break;
21289     }
21290
21291   return result;
21292 }
21293
21294 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21295    valid type for this die is found.  */
21296
21297 struct type *
21298 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21299                                 struct dwarf2_per_cu_data *per_cu)
21300 {
21301   struct dwarf2_cu *cu;
21302   struct die_info *die;
21303
21304   dw2_setup (per_cu->objfile);
21305
21306   if (per_cu->cu == NULL)
21307     load_cu (per_cu);
21308   cu = per_cu->cu;
21309   if (!cu)
21310     return NULL;
21311
21312   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21313   if (!die)
21314     return NULL;
21315
21316   return die_type (die, cu);
21317 }
21318
21319 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21320    PER_CU.  */
21321
21322 struct type *
21323 dwarf2_get_die_type (cu_offset die_offset,
21324                      struct dwarf2_per_cu_data *per_cu)
21325 {
21326   dw2_setup (per_cu->objfile);
21327
21328   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21329   return get_die_type_at_offset (die_offset_sect, per_cu);
21330 }
21331
21332 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21333    On entry *REF_CU is the CU of SRC_DIE.
21334    On exit *REF_CU is the CU of the result.
21335    Returns NULL if the referenced DIE isn't found.  */
21336
21337 static struct die_info *
21338 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21339                   struct dwarf2_cu **ref_cu)
21340 {
21341   struct die_info temp_die;
21342   struct dwarf2_cu *sig_cu;
21343   struct die_info *die;
21344
21345   /* While it might be nice to assert sig_type->type == NULL here,
21346      we can get here for DW_AT_imported_declaration where we need
21347      the DIE not the type.  */
21348
21349   /* If necessary, add it to the queue and load its DIEs.  */
21350
21351   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21352     read_signatured_type (sig_type);
21353
21354   sig_cu = sig_type->per_cu.cu;
21355   gdb_assert (sig_cu != NULL);
21356   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21357   temp_die.sect_off = sig_type->type_offset_in_section;
21358   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21359                                                  to_underlying (temp_die.sect_off));
21360   if (die)
21361     {
21362       /* For .gdb_index version 7 keep track of included TUs.
21363          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21364       if (dwarf2_per_objfile->index_table != NULL
21365           && dwarf2_per_objfile->index_table->version <= 7)
21366         {
21367           VEC_safe_push (dwarf2_per_cu_ptr,
21368                          (*ref_cu)->per_cu->imported_symtabs,
21369                          sig_cu->per_cu);
21370         }
21371
21372       *ref_cu = sig_cu;
21373       return die;
21374     }
21375
21376   return NULL;
21377 }
21378
21379 /* Follow signatured type referenced by ATTR in SRC_DIE.
21380    On entry *REF_CU is the CU of SRC_DIE.
21381    On exit *REF_CU is the CU of the result.
21382    The result is the DIE of the type.
21383    If the referenced type cannot be found an error is thrown.  */
21384
21385 static struct die_info *
21386 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21387                 struct dwarf2_cu **ref_cu)
21388 {
21389   ULONGEST signature = DW_SIGNATURE (attr);
21390   struct signatured_type *sig_type;
21391   struct die_info *die;
21392
21393   gdb_assert (attr->form == DW_FORM_ref_sig8);
21394
21395   sig_type = lookup_signatured_type (*ref_cu, signature);
21396   /* sig_type will be NULL if the signatured type is missing from
21397      the debug info.  */
21398   if (sig_type == NULL)
21399     {
21400       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21401                " from DIE at 0x%x [in module %s]"),
21402              hex_string (signature), to_underlying (src_die->sect_off),
21403              objfile_name ((*ref_cu)->objfile));
21404     }
21405
21406   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21407   if (die == NULL)
21408     {
21409       dump_die_for_error (src_die);
21410       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21411                " from DIE at 0x%x [in module %s]"),
21412              hex_string (signature), to_underlying (src_die->sect_off),
21413              objfile_name ((*ref_cu)->objfile));
21414     }
21415
21416   return die;
21417 }
21418
21419 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21420    reading in and processing the type unit if necessary.  */
21421
21422 static struct type *
21423 get_signatured_type (struct die_info *die, ULONGEST signature,
21424                      struct dwarf2_cu *cu)
21425 {
21426   struct signatured_type *sig_type;
21427   struct dwarf2_cu *type_cu;
21428   struct die_info *type_die;
21429   struct type *type;
21430
21431   sig_type = lookup_signatured_type (cu, signature);
21432   /* sig_type will be NULL if the signatured type is missing from
21433      the debug info.  */
21434   if (sig_type == NULL)
21435     {
21436       complaint (&symfile_complaints,
21437                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21438                    " from DIE at 0x%x [in module %s]"),
21439                  hex_string (signature), to_underlying (die->sect_off),
21440                  objfile_name (dwarf2_per_objfile->objfile));
21441       return build_error_marker_type (cu, die);
21442     }
21443
21444   /* If we already know the type we're done.  */
21445   if (sig_type->type != NULL)
21446     return sig_type->type;
21447
21448   type_cu = cu;
21449   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21450   if (type_die != NULL)
21451     {
21452       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21453          is created.  This is important, for example, because for c++ classes
21454          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21455       type = read_type_die (type_die, type_cu);
21456       if (type == NULL)
21457         {
21458           complaint (&symfile_complaints,
21459                      _("Dwarf Error: Cannot build signatured type %s"
21460                        " referenced from DIE at 0x%x [in module %s]"),
21461                      hex_string (signature), to_underlying (die->sect_off),
21462                      objfile_name (dwarf2_per_objfile->objfile));
21463           type = build_error_marker_type (cu, die);
21464         }
21465     }
21466   else
21467     {
21468       complaint (&symfile_complaints,
21469                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21470                    " from DIE at 0x%x [in module %s]"),
21471                  hex_string (signature), to_underlying (die->sect_off),
21472                  objfile_name (dwarf2_per_objfile->objfile));
21473       type = build_error_marker_type (cu, die);
21474     }
21475   sig_type->type = type;
21476
21477   return type;
21478 }
21479
21480 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21481    reading in and processing the type unit if necessary.  */
21482
21483 static struct type *
21484 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21485                           struct dwarf2_cu *cu) /* ARI: editCase function */
21486 {
21487   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21488   if (attr_form_is_ref (attr))
21489     {
21490       struct dwarf2_cu *type_cu = cu;
21491       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21492
21493       return read_type_die (type_die, type_cu);
21494     }
21495   else if (attr->form == DW_FORM_ref_sig8)
21496     {
21497       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21498     }
21499   else
21500     {
21501       complaint (&symfile_complaints,
21502                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21503                    " at 0x%x [in module %s]"),
21504                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21505                  objfile_name (dwarf2_per_objfile->objfile));
21506       return build_error_marker_type (cu, die);
21507     }
21508 }
21509
21510 /* Load the DIEs associated with type unit PER_CU into memory.  */
21511
21512 static void
21513 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21514 {
21515   struct signatured_type *sig_type;
21516
21517   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21518   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21519
21520   /* We have the per_cu, but we need the signatured_type.
21521      Fortunately this is an easy translation.  */
21522   gdb_assert (per_cu->is_debug_types);
21523   sig_type = (struct signatured_type *) per_cu;
21524
21525   gdb_assert (per_cu->cu == NULL);
21526
21527   read_signatured_type (sig_type);
21528
21529   gdb_assert (per_cu->cu != NULL);
21530 }
21531
21532 /* die_reader_func for read_signatured_type.
21533    This is identical to load_full_comp_unit_reader,
21534    but is kept separate for now.  */
21535
21536 static void
21537 read_signatured_type_reader (const struct die_reader_specs *reader,
21538                              const gdb_byte *info_ptr,
21539                              struct die_info *comp_unit_die,
21540                              int has_children,
21541                              void *data)
21542 {
21543   struct dwarf2_cu *cu = reader->cu;
21544
21545   gdb_assert (cu->die_hash == NULL);
21546   cu->die_hash =
21547     htab_create_alloc_ex (cu->header.length / 12,
21548                           die_hash,
21549                           die_eq,
21550                           NULL,
21551                           &cu->comp_unit_obstack,
21552                           hashtab_obstack_allocate,
21553                           dummy_obstack_deallocate);
21554
21555   if (has_children)
21556     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21557                                                   &info_ptr, comp_unit_die);
21558   cu->dies = comp_unit_die;
21559   /* comp_unit_die is not stored in die_hash, no need.  */
21560
21561   /* We try not to read any attributes in this function, because not
21562      all CUs needed for references have been loaded yet, and symbol
21563      table processing isn't initialized.  But we have to set the CU language,
21564      or we won't be able to build types correctly.
21565      Similarly, if we do not read the producer, we can not apply
21566      producer-specific interpretation.  */
21567   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21568 }
21569
21570 /* Read in a signatured type and build its CU and DIEs.
21571    If the type is a stub for the real type in a DWO file,
21572    read in the real type from the DWO file as well.  */
21573
21574 static void
21575 read_signatured_type (struct signatured_type *sig_type)
21576 {
21577   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21578
21579   gdb_assert (per_cu->is_debug_types);
21580   gdb_assert (per_cu->cu == NULL);
21581
21582   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21583                            read_signatured_type_reader, NULL);
21584   sig_type->per_cu.tu_read = 1;
21585 }
21586
21587 /* Decode simple location descriptions.
21588    Given a pointer to a dwarf block that defines a location, compute
21589    the location and return the value.
21590
21591    NOTE drow/2003-11-18: This function is called in two situations
21592    now: for the address of static or global variables (partial symbols
21593    only) and for offsets into structures which are expected to be
21594    (more or less) constant.  The partial symbol case should go away,
21595    and only the constant case should remain.  That will let this
21596    function complain more accurately.  A few special modes are allowed
21597    without complaint for global variables (for instance, global
21598    register values and thread-local values).
21599
21600    A location description containing no operations indicates that the
21601    object is optimized out.  The return value is 0 for that case.
21602    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21603    callers will only want a very basic result and this can become a
21604    complaint.
21605
21606    Note that stack[0] is unused except as a default error return.  */
21607
21608 static CORE_ADDR
21609 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21610 {
21611   struct objfile *objfile = cu->objfile;
21612   size_t i;
21613   size_t size = blk->size;
21614   const gdb_byte *data = blk->data;
21615   CORE_ADDR stack[64];
21616   int stacki;
21617   unsigned int bytes_read, unsnd;
21618   gdb_byte op;
21619
21620   i = 0;
21621   stacki = 0;
21622   stack[stacki] = 0;
21623   stack[++stacki] = 0;
21624
21625   while (i < size)
21626     {
21627       op = data[i++];
21628       switch (op)
21629         {
21630         case DW_OP_lit0:
21631         case DW_OP_lit1:
21632         case DW_OP_lit2:
21633         case DW_OP_lit3:
21634         case DW_OP_lit4:
21635         case DW_OP_lit5:
21636         case DW_OP_lit6:
21637         case DW_OP_lit7:
21638         case DW_OP_lit8:
21639         case DW_OP_lit9:
21640         case DW_OP_lit10:
21641         case DW_OP_lit11:
21642         case DW_OP_lit12:
21643         case DW_OP_lit13:
21644         case DW_OP_lit14:
21645         case DW_OP_lit15:
21646         case DW_OP_lit16:
21647         case DW_OP_lit17:
21648         case DW_OP_lit18:
21649         case DW_OP_lit19:
21650         case DW_OP_lit20:
21651         case DW_OP_lit21:
21652         case DW_OP_lit22:
21653         case DW_OP_lit23:
21654         case DW_OP_lit24:
21655         case DW_OP_lit25:
21656         case DW_OP_lit26:
21657         case DW_OP_lit27:
21658         case DW_OP_lit28:
21659         case DW_OP_lit29:
21660         case DW_OP_lit30:
21661         case DW_OP_lit31:
21662           stack[++stacki] = op - DW_OP_lit0;
21663           break;
21664
21665         case DW_OP_reg0:
21666         case DW_OP_reg1:
21667         case DW_OP_reg2:
21668         case DW_OP_reg3:
21669         case DW_OP_reg4:
21670         case DW_OP_reg5:
21671         case DW_OP_reg6:
21672         case DW_OP_reg7:
21673         case DW_OP_reg8:
21674         case DW_OP_reg9:
21675         case DW_OP_reg10:
21676         case DW_OP_reg11:
21677         case DW_OP_reg12:
21678         case DW_OP_reg13:
21679         case DW_OP_reg14:
21680         case DW_OP_reg15:
21681         case DW_OP_reg16:
21682         case DW_OP_reg17:
21683         case DW_OP_reg18:
21684         case DW_OP_reg19:
21685         case DW_OP_reg20:
21686         case DW_OP_reg21:
21687         case DW_OP_reg22:
21688         case DW_OP_reg23:
21689         case DW_OP_reg24:
21690         case DW_OP_reg25:
21691         case DW_OP_reg26:
21692         case DW_OP_reg27:
21693         case DW_OP_reg28:
21694         case DW_OP_reg29:
21695         case DW_OP_reg30:
21696         case DW_OP_reg31:
21697           stack[++stacki] = op - DW_OP_reg0;
21698           if (i < size)
21699             dwarf2_complex_location_expr_complaint ();
21700           break;
21701
21702         case DW_OP_regx:
21703           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21704           i += bytes_read;
21705           stack[++stacki] = unsnd;
21706           if (i < size)
21707             dwarf2_complex_location_expr_complaint ();
21708           break;
21709
21710         case DW_OP_addr:
21711           stack[++stacki] = read_address (objfile->obfd, &data[i],
21712                                           cu, &bytes_read);
21713           i += bytes_read;
21714           break;
21715
21716         case DW_OP_const1u:
21717           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21718           i += 1;
21719           break;
21720
21721         case DW_OP_const1s:
21722           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21723           i += 1;
21724           break;
21725
21726         case DW_OP_const2u:
21727           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21728           i += 2;
21729           break;
21730
21731         case DW_OP_const2s:
21732           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21733           i += 2;
21734           break;
21735
21736         case DW_OP_const4u:
21737           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21738           i += 4;
21739           break;
21740
21741         case DW_OP_const4s:
21742           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21743           i += 4;
21744           break;
21745
21746         case DW_OP_const8u:
21747           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21748           i += 8;
21749           break;
21750
21751         case DW_OP_constu:
21752           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21753                                                   &bytes_read);
21754           i += bytes_read;
21755           break;
21756
21757         case DW_OP_consts:
21758           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21759           i += bytes_read;
21760           break;
21761
21762         case DW_OP_dup:
21763           stack[stacki + 1] = stack[stacki];
21764           stacki++;
21765           break;
21766
21767         case DW_OP_plus:
21768           stack[stacki - 1] += stack[stacki];
21769           stacki--;
21770           break;
21771
21772         case DW_OP_plus_uconst:
21773           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21774                                                  &bytes_read);
21775           i += bytes_read;
21776           break;
21777
21778         case DW_OP_minus:
21779           stack[stacki - 1] -= stack[stacki];
21780           stacki--;
21781           break;
21782
21783         case DW_OP_deref:
21784           /* If we're not the last op, then we definitely can't encode
21785              this using GDB's address_class enum.  This is valid for partial
21786              global symbols, although the variable's address will be bogus
21787              in the psymtab.  */
21788           if (i < size)
21789             dwarf2_complex_location_expr_complaint ();
21790           break;
21791
21792         case DW_OP_GNU_push_tls_address:
21793         case DW_OP_form_tls_address:
21794           /* The top of the stack has the offset from the beginning
21795              of the thread control block at which the variable is located.  */
21796           /* Nothing should follow this operator, so the top of stack would
21797              be returned.  */
21798           /* This is valid for partial global symbols, but the variable's
21799              address will be bogus in the psymtab.  Make it always at least
21800              non-zero to not look as a variable garbage collected by linker
21801              which have DW_OP_addr 0.  */
21802           if (i < size)
21803             dwarf2_complex_location_expr_complaint ();
21804           stack[stacki]++;
21805           break;
21806
21807         case DW_OP_GNU_uninit:
21808           break;
21809
21810         case DW_OP_GNU_addr_index:
21811         case DW_OP_GNU_const_index:
21812           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21813                                                          &bytes_read);
21814           i += bytes_read;
21815           break;
21816
21817         default:
21818           {
21819             const char *name = get_DW_OP_name (op);
21820
21821             if (name)
21822               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21823                          name);
21824             else
21825               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21826                          op);
21827           }
21828
21829           return (stack[stacki]);
21830         }
21831
21832       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21833          outside of the allocated space.  Also enforce minimum>0.  */
21834       if (stacki >= ARRAY_SIZE (stack) - 1)
21835         {
21836           complaint (&symfile_complaints,
21837                      _("location description stack overflow"));
21838           return 0;
21839         }
21840
21841       if (stacki <= 0)
21842         {
21843           complaint (&symfile_complaints,
21844                      _("location description stack underflow"));
21845           return 0;
21846         }
21847     }
21848   return (stack[stacki]);
21849 }
21850
21851 /* memory allocation interface */
21852
21853 static struct dwarf_block *
21854 dwarf_alloc_block (struct dwarf2_cu *cu)
21855 {
21856   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21857 }
21858
21859 static struct die_info *
21860 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21861 {
21862   struct die_info *die;
21863   size_t size = sizeof (struct die_info);
21864
21865   if (num_attrs > 1)
21866     size += (num_attrs - 1) * sizeof (struct attribute);
21867
21868   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21869   memset (die, 0, sizeof (struct die_info));
21870   return (die);
21871 }
21872
21873 \f
21874 /* Macro support.  */
21875
21876 /* Return file name relative to the compilation directory of file number I in
21877    *LH's file name table.  The result is allocated using xmalloc; the caller is
21878    responsible for freeing it.  */
21879
21880 static char *
21881 file_file_name (int file, struct line_header *lh)
21882 {
21883   /* Is the file number a valid index into the line header's file name
21884      table?  Remember that file numbers start with one, not zero.  */
21885   if (1 <= file && file <= lh->file_names.size ())
21886     {
21887       const file_entry &fe = lh->file_names[file - 1];
21888
21889       if (!IS_ABSOLUTE_PATH (fe.name))
21890         {
21891           const char *dir = fe.include_dir (lh);
21892           if (dir != NULL)
21893             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21894         }
21895       return xstrdup (fe.name);
21896     }
21897   else
21898     {
21899       /* The compiler produced a bogus file number.  We can at least
21900          record the macro definitions made in the file, even if we
21901          won't be able to find the file by name.  */
21902       char fake_name[80];
21903
21904       xsnprintf (fake_name, sizeof (fake_name),
21905                  "<bad macro file number %d>", file);
21906
21907       complaint (&symfile_complaints,
21908                  _("bad file number in macro information (%d)"),
21909                  file);
21910
21911       return xstrdup (fake_name);
21912     }
21913 }
21914
21915 /* Return the full name of file number I in *LH's file name table.
21916    Use COMP_DIR as the name of the current directory of the
21917    compilation.  The result is allocated using xmalloc; the caller is
21918    responsible for freeing it.  */
21919 static char *
21920 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21921 {
21922   /* Is the file number a valid index into the line header's file name
21923      table?  Remember that file numbers start with one, not zero.  */
21924   if (1 <= file && file <= lh->file_names.size ())
21925     {
21926       char *relative = file_file_name (file, lh);
21927
21928       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21929         return relative;
21930       return reconcat (relative, comp_dir, SLASH_STRING,
21931                        relative, (char *) NULL);
21932     }
21933   else
21934     return file_file_name (file, lh);
21935 }
21936
21937
21938 static struct macro_source_file *
21939 macro_start_file (int file, int line,
21940                   struct macro_source_file *current_file,
21941                   struct line_header *lh)
21942 {
21943   /* File name relative to the compilation directory of this source file.  */
21944   char *file_name = file_file_name (file, lh);
21945
21946   if (! current_file)
21947     {
21948       /* Note: We don't create a macro table for this compilation unit
21949          at all until we actually get a filename.  */
21950       struct macro_table *macro_table = get_macro_table ();
21951
21952       /* If we have no current file, then this must be the start_file
21953          directive for the compilation unit's main source file.  */
21954       current_file = macro_set_main (macro_table, file_name);
21955       macro_define_special (macro_table);
21956     }
21957   else
21958     current_file = macro_include (current_file, line, file_name);
21959
21960   xfree (file_name);
21961
21962   return current_file;
21963 }
21964
21965 static const char *
21966 consume_improper_spaces (const char *p, const char *body)
21967 {
21968   if (*p == ' ')
21969     {
21970       complaint (&symfile_complaints,
21971                  _("macro definition contains spaces "
21972                    "in formal argument list:\n`%s'"),
21973                  body);
21974
21975       while (*p == ' ')
21976         p++;
21977     }
21978
21979   return p;
21980 }
21981
21982
21983 static void
21984 parse_macro_definition (struct macro_source_file *file, int line,
21985                         const char *body)
21986 {
21987   const char *p;
21988
21989   /* The body string takes one of two forms.  For object-like macro
21990      definitions, it should be:
21991
21992         <macro name> " " <definition>
21993
21994      For function-like macro definitions, it should be:
21995
21996         <macro name> "() " <definition>
21997      or
21998         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21999
22000      Spaces may appear only where explicitly indicated, and in the
22001      <definition>.
22002
22003      The Dwarf 2 spec says that an object-like macro's name is always
22004      followed by a space, but versions of GCC around March 2002 omit
22005      the space when the macro's definition is the empty string.
22006
22007      The Dwarf 2 spec says that there should be no spaces between the
22008      formal arguments in a function-like macro's formal argument list,
22009      but versions of GCC around March 2002 include spaces after the
22010      commas.  */
22011
22012
22013   /* Find the extent of the macro name.  The macro name is terminated
22014      by either a space or null character (for an object-like macro) or
22015      an opening paren (for a function-like macro).  */
22016   for (p = body; *p; p++)
22017     if (*p == ' ' || *p == '(')
22018       break;
22019
22020   if (*p == ' ' || *p == '\0')
22021     {
22022       /* It's an object-like macro.  */
22023       int name_len = p - body;
22024       char *name = savestring (body, name_len);
22025       const char *replacement;
22026
22027       if (*p == ' ')
22028         replacement = body + name_len + 1;
22029       else
22030         {
22031           dwarf2_macro_malformed_definition_complaint (body);
22032           replacement = body + name_len;
22033         }
22034
22035       macro_define_object (file, line, name, replacement);
22036
22037       xfree (name);
22038     }
22039   else if (*p == '(')
22040     {
22041       /* It's a function-like macro.  */
22042       char *name = savestring (body, p - body);
22043       int argc = 0;
22044       int argv_size = 1;
22045       char **argv = XNEWVEC (char *, argv_size);
22046
22047       p++;
22048
22049       p = consume_improper_spaces (p, body);
22050
22051       /* Parse the formal argument list.  */
22052       while (*p && *p != ')')
22053         {
22054           /* Find the extent of the current argument name.  */
22055           const char *arg_start = p;
22056
22057           while (*p && *p != ',' && *p != ')' && *p != ' ')
22058             p++;
22059
22060           if (! *p || p == arg_start)
22061             dwarf2_macro_malformed_definition_complaint (body);
22062           else
22063             {
22064               /* Make sure argv has room for the new argument.  */
22065               if (argc >= argv_size)
22066                 {
22067                   argv_size *= 2;
22068                   argv = XRESIZEVEC (char *, argv, argv_size);
22069                 }
22070
22071               argv[argc++] = savestring (arg_start, p - arg_start);
22072             }
22073
22074           p = consume_improper_spaces (p, body);
22075
22076           /* Consume the comma, if present.  */
22077           if (*p == ',')
22078             {
22079               p++;
22080
22081               p = consume_improper_spaces (p, body);
22082             }
22083         }
22084
22085       if (*p == ')')
22086         {
22087           p++;
22088
22089           if (*p == ' ')
22090             /* Perfectly formed definition, no complaints.  */
22091             macro_define_function (file, line, name,
22092                                    argc, (const char **) argv,
22093                                    p + 1);
22094           else if (*p == '\0')
22095             {
22096               /* Complain, but do define it.  */
22097               dwarf2_macro_malformed_definition_complaint (body);
22098               macro_define_function (file, line, name,
22099                                      argc, (const char **) argv,
22100                                      p);
22101             }
22102           else
22103             /* Just complain.  */
22104             dwarf2_macro_malformed_definition_complaint (body);
22105         }
22106       else
22107         /* Just complain.  */
22108         dwarf2_macro_malformed_definition_complaint (body);
22109
22110       xfree (name);
22111       {
22112         int i;
22113
22114         for (i = 0; i < argc; i++)
22115           xfree (argv[i]);
22116       }
22117       xfree (argv);
22118     }
22119   else
22120     dwarf2_macro_malformed_definition_complaint (body);
22121 }
22122
22123 /* Skip some bytes from BYTES according to the form given in FORM.
22124    Returns the new pointer.  */
22125
22126 static const gdb_byte *
22127 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22128                  enum dwarf_form form,
22129                  unsigned int offset_size,
22130                  struct dwarf2_section_info *section)
22131 {
22132   unsigned int bytes_read;
22133
22134   switch (form)
22135     {
22136     case DW_FORM_data1:
22137     case DW_FORM_flag:
22138       ++bytes;
22139       break;
22140
22141     case DW_FORM_data2:
22142       bytes += 2;
22143       break;
22144
22145     case DW_FORM_data4:
22146       bytes += 4;
22147       break;
22148
22149     case DW_FORM_data8:
22150       bytes += 8;
22151       break;
22152
22153     case DW_FORM_data16:
22154       bytes += 16;
22155       break;
22156
22157     case DW_FORM_string:
22158       read_direct_string (abfd, bytes, &bytes_read);
22159       bytes += bytes_read;
22160       break;
22161
22162     case DW_FORM_sec_offset:
22163     case DW_FORM_strp:
22164     case DW_FORM_GNU_strp_alt:
22165       bytes += offset_size;
22166       break;
22167
22168     case DW_FORM_block:
22169       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22170       bytes += bytes_read;
22171       break;
22172
22173     case DW_FORM_block1:
22174       bytes += 1 + read_1_byte (abfd, bytes);
22175       break;
22176     case DW_FORM_block2:
22177       bytes += 2 + read_2_bytes (abfd, bytes);
22178       break;
22179     case DW_FORM_block4:
22180       bytes += 4 + read_4_bytes (abfd, bytes);
22181       break;
22182
22183     case DW_FORM_sdata:
22184     case DW_FORM_udata:
22185     case DW_FORM_GNU_addr_index:
22186     case DW_FORM_GNU_str_index:
22187       bytes = gdb_skip_leb128 (bytes, buffer_end);
22188       if (bytes == NULL)
22189         {
22190           dwarf2_section_buffer_overflow_complaint (section);
22191           return NULL;
22192         }
22193       break;
22194
22195     case DW_FORM_implicit_const:
22196       break;
22197
22198     default:
22199       {
22200       complain:
22201         complaint (&symfile_complaints,
22202                    _("invalid form 0x%x in `%s'"),
22203                    form, get_section_name (section));
22204         return NULL;
22205       }
22206     }
22207
22208   return bytes;
22209 }
22210
22211 /* A helper for dwarf_decode_macros that handles skipping an unknown
22212    opcode.  Returns an updated pointer to the macro data buffer; or,
22213    on error, issues a complaint and returns NULL.  */
22214
22215 static const gdb_byte *
22216 skip_unknown_opcode (unsigned int opcode,
22217                      const gdb_byte **opcode_definitions,
22218                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22219                      bfd *abfd,
22220                      unsigned int offset_size,
22221                      struct dwarf2_section_info *section)
22222 {
22223   unsigned int bytes_read, i;
22224   unsigned long arg;
22225   const gdb_byte *defn;
22226
22227   if (opcode_definitions[opcode] == NULL)
22228     {
22229       complaint (&symfile_complaints,
22230                  _("unrecognized DW_MACFINO opcode 0x%x"),
22231                  opcode);
22232       return NULL;
22233     }
22234
22235   defn = opcode_definitions[opcode];
22236   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22237   defn += bytes_read;
22238
22239   for (i = 0; i < arg; ++i)
22240     {
22241       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22242                                  (enum dwarf_form) defn[i], offset_size,
22243                                  section);
22244       if (mac_ptr == NULL)
22245         {
22246           /* skip_form_bytes already issued the complaint.  */
22247           return NULL;
22248         }
22249     }
22250
22251   return mac_ptr;
22252 }
22253
22254 /* A helper function which parses the header of a macro section.
22255    If the macro section is the extended (for now called "GNU") type,
22256    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22257    the header, or issues a complaint and returns NULL on error.  */
22258
22259 static const gdb_byte *
22260 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22261                           bfd *abfd,
22262                           const gdb_byte *mac_ptr,
22263                           unsigned int *offset_size,
22264                           int section_is_gnu)
22265 {
22266   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22267
22268   if (section_is_gnu)
22269     {
22270       unsigned int version, flags;
22271
22272       version = read_2_bytes (abfd, mac_ptr);
22273       if (version != 4 && version != 5)
22274         {
22275           complaint (&symfile_complaints,
22276                      _("unrecognized version `%d' in .debug_macro section"),
22277                      version);
22278           return NULL;
22279         }
22280       mac_ptr += 2;
22281
22282       flags = read_1_byte (abfd, mac_ptr);
22283       ++mac_ptr;
22284       *offset_size = (flags & 1) ? 8 : 4;
22285
22286       if ((flags & 2) != 0)
22287         /* We don't need the line table offset.  */
22288         mac_ptr += *offset_size;
22289
22290       /* Vendor opcode descriptions.  */
22291       if ((flags & 4) != 0)
22292         {
22293           unsigned int i, count;
22294
22295           count = read_1_byte (abfd, mac_ptr);
22296           ++mac_ptr;
22297           for (i = 0; i < count; ++i)
22298             {
22299               unsigned int opcode, bytes_read;
22300               unsigned long arg;
22301
22302               opcode = read_1_byte (abfd, mac_ptr);
22303               ++mac_ptr;
22304               opcode_definitions[opcode] = mac_ptr;
22305               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22306               mac_ptr += bytes_read;
22307               mac_ptr += arg;
22308             }
22309         }
22310     }
22311
22312   return mac_ptr;
22313 }
22314
22315 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22316    including DW_MACRO_import.  */
22317
22318 static void
22319 dwarf_decode_macro_bytes (bfd *abfd,
22320                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22321                           struct macro_source_file *current_file,
22322                           struct line_header *lh,
22323                           struct dwarf2_section_info *section,
22324                           int section_is_gnu, int section_is_dwz,
22325                           unsigned int offset_size,
22326                           htab_t include_hash)
22327 {
22328   struct objfile *objfile = dwarf2_per_objfile->objfile;
22329   enum dwarf_macro_record_type macinfo_type;
22330   int at_commandline;
22331   const gdb_byte *opcode_definitions[256];
22332
22333   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22334                                       &offset_size, section_is_gnu);
22335   if (mac_ptr == NULL)
22336     {
22337       /* We already issued a complaint.  */
22338       return;
22339     }
22340
22341   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22342      GDB is still reading the definitions from command line.  First
22343      DW_MACINFO_start_file will need to be ignored as it was already executed
22344      to create CURRENT_FILE for the main source holding also the command line
22345      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22346      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22347
22348   at_commandline = 1;
22349
22350   do
22351     {
22352       /* Do we at least have room for a macinfo type byte?  */
22353       if (mac_ptr >= mac_end)
22354         {
22355           dwarf2_section_buffer_overflow_complaint (section);
22356           break;
22357         }
22358
22359       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22360       mac_ptr++;
22361
22362       /* Note that we rely on the fact that the corresponding GNU and
22363          DWARF constants are the same.  */
22364       switch (macinfo_type)
22365         {
22366           /* A zero macinfo type indicates the end of the macro
22367              information.  */
22368         case 0:
22369           break;
22370
22371         case DW_MACRO_define:
22372         case DW_MACRO_undef:
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             int line;
22380             const char *body;
22381             int is_define;
22382
22383             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22384             mac_ptr += bytes_read;
22385
22386             if (macinfo_type == DW_MACRO_define
22387                 || macinfo_type == DW_MACRO_undef)
22388               {
22389                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22390                 mac_ptr += bytes_read;
22391               }
22392             else
22393               {
22394                 LONGEST str_offset;
22395
22396                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22397                 mac_ptr += offset_size;
22398
22399                 if (macinfo_type == DW_MACRO_define_sup
22400                     || macinfo_type == DW_MACRO_undef_sup
22401                     || section_is_dwz)
22402                   {
22403                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22404
22405                     body = read_indirect_string_from_dwz (dwz, str_offset);
22406                   }
22407                 else
22408                   body = read_indirect_string_at_offset (abfd, str_offset);
22409               }
22410
22411             is_define = (macinfo_type == DW_MACRO_define
22412                          || macinfo_type == DW_MACRO_define_strp
22413                          || macinfo_type == DW_MACRO_define_sup);
22414             if (! current_file)
22415               {
22416                 /* DWARF violation as no main source is present.  */
22417                 complaint (&symfile_complaints,
22418                            _("debug info with no main source gives macro %s "
22419                              "on line %d: %s"),
22420                            is_define ? _("definition") : _("undefinition"),
22421                            line, body);
22422                 break;
22423               }
22424             if ((line == 0 && !at_commandline)
22425                 || (line != 0 && at_commandline))
22426               complaint (&symfile_complaints,
22427                          _("debug info gives %s macro %s with %s line %d: %s"),
22428                          at_commandline ? _("command-line") : _("in-file"),
22429                          is_define ? _("definition") : _("undefinition"),
22430                          line == 0 ? _("zero") : _("non-zero"), line, body);
22431
22432             if (is_define)
22433               parse_macro_definition (current_file, line, body);
22434             else
22435               {
22436                 gdb_assert (macinfo_type == DW_MACRO_undef
22437                             || macinfo_type == DW_MACRO_undef_strp
22438                             || macinfo_type == DW_MACRO_undef_sup);
22439                 macro_undef (current_file, line, body);
22440               }
22441           }
22442           break;
22443
22444         case DW_MACRO_start_file:
22445           {
22446             unsigned int bytes_read;
22447             int line, file;
22448
22449             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22450             mac_ptr += bytes_read;
22451             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22452             mac_ptr += bytes_read;
22453
22454             if ((line == 0 && !at_commandline)
22455                 || (line != 0 && at_commandline))
22456               complaint (&symfile_complaints,
22457                          _("debug info gives source %d included "
22458                            "from %s at %s line %d"),
22459                          file, at_commandline ? _("command-line") : _("file"),
22460                          line == 0 ? _("zero") : _("non-zero"), line);
22461
22462             if (at_commandline)
22463               {
22464                 /* This DW_MACRO_start_file was executed in the
22465                    pass one.  */
22466                 at_commandline = 0;
22467               }
22468             else
22469               current_file = macro_start_file (file, line, current_file, lh);
22470           }
22471           break;
22472
22473         case DW_MACRO_end_file:
22474           if (! current_file)
22475             complaint (&symfile_complaints,
22476                        _("macro debug info has an unmatched "
22477                          "`close_file' directive"));
22478           else
22479             {
22480               current_file = current_file->included_by;
22481               if (! current_file)
22482                 {
22483                   enum dwarf_macro_record_type next_type;
22484
22485                   /* GCC circa March 2002 doesn't produce the zero
22486                      type byte marking the end of the compilation
22487                      unit.  Complain if it's not there, but exit no
22488                      matter what.  */
22489
22490                   /* Do we at least have room for a macinfo type byte?  */
22491                   if (mac_ptr >= mac_end)
22492                     {
22493                       dwarf2_section_buffer_overflow_complaint (section);
22494                       return;
22495                     }
22496
22497                   /* We don't increment mac_ptr here, so this is just
22498                      a look-ahead.  */
22499                   next_type
22500                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22501                                                                   mac_ptr);
22502                   if (next_type != 0)
22503                     complaint (&symfile_complaints,
22504                                _("no terminating 0-type entry for "
22505                                  "macros in `.debug_macinfo' section"));
22506
22507                   return;
22508                 }
22509             }
22510           break;
22511
22512         case DW_MACRO_import:
22513         case DW_MACRO_import_sup:
22514           {
22515             LONGEST offset;
22516             void **slot;
22517             bfd *include_bfd = abfd;
22518             struct dwarf2_section_info *include_section = section;
22519             const gdb_byte *include_mac_end = mac_end;
22520             int is_dwz = section_is_dwz;
22521             const gdb_byte *new_mac_ptr;
22522
22523             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22524             mac_ptr += offset_size;
22525
22526             if (macinfo_type == DW_MACRO_import_sup)
22527               {
22528                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22529
22530                 dwarf2_read_section (objfile, &dwz->macro);
22531
22532                 include_section = &dwz->macro;
22533                 include_bfd = get_section_bfd_owner (include_section);
22534                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22535                 is_dwz = 1;
22536               }
22537
22538             new_mac_ptr = include_section->buffer + offset;
22539             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22540
22541             if (*slot != NULL)
22542               {
22543                 /* This has actually happened; see
22544                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22545                 complaint (&symfile_complaints,
22546                            _("recursive DW_MACRO_import in "
22547                              ".debug_macro section"));
22548               }
22549             else
22550               {
22551                 *slot = (void *) new_mac_ptr;
22552
22553                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22554                                           include_mac_end, current_file, lh,
22555                                           section, section_is_gnu, is_dwz,
22556                                           offset_size, include_hash);
22557
22558                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22559               }
22560           }
22561           break;
22562
22563         case DW_MACINFO_vendor_ext:
22564           if (!section_is_gnu)
22565             {
22566               unsigned int bytes_read;
22567
22568               /* This reads the constant, but since we don't recognize
22569                  any vendor extensions, we ignore it.  */
22570               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22571               mac_ptr += bytes_read;
22572               read_direct_string (abfd, mac_ptr, &bytes_read);
22573               mac_ptr += bytes_read;
22574
22575               /* We don't recognize any vendor extensions.  */
22576               break;
22577             }
22578           /* FALLTHROUGH */
22579
22580         default:
22581           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22582                                          mac_ptr, mac_end, abfd, offset_size,
22583                                          section);
22584           if (mac_ptr == NULL)
22585             return;
22586           break;
22587         }
22588     } while (macinfo_type != 0);
22589 }
22590
22591 static void
22592 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22593                      int section_is_gnu)
22594 {
22595   struct objfile *objfile = dwarf2_per_objfile->objfile;
22596   struct line_header *lh = cu->line_header;
22597   bfd *abfd;
22598   const gdb_byte *mac_ptr, *mac_end;
22599   struct macro_source_file *current_file = 0;
22600   enum dwarf_macro_record_type macinfo_type;
22601   unsigned int offset_size = cu->header.offset_size;
22602   const gdb_byte *opcode_definitions[256];
22603   void **slot;
22604   struct dwarf2_section_info *section;
22605   const char *section_name;
22606
22607   if (cu->dwo_unit != NULL)
22608     {
22609       if (section_is_gnu)
22610         {
22611           section = &cu->dwo_unit->dwo_file->sections.macro;
22612           section_name = ".debug_macro.dwo";
22613         }
22614       else
22615         {
22616           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22617           section_name = ".debug_macinfo.dwo";
22618         }
22619     }
22620   else
22621     {
22622       if (section_is_gnu)
22623         {
22624           section = &dwarf2_per_objfile->macro;
22625           section_name = ".debug_macro";
22626         }
22627       else
22628         {
22629           section = &dwarf2_per_objfile->macinfo;
22630           section_name = ".debug_macinfo";
22631         }
22632     }
22633
22634   dwarf2_read_section (objfile, section);
22635   if (section->buffer == NULL)
22636     {
22637       complaint (&symfile_complaints, _("missing %s section"), section_name);
22638       return;
22639     }
22640   abfd = get_section_bfd_owner (section);
22641
22642   /* First pass: Find the name of the base filename.
22643      This filename is needed in order to process all macros whose definition
22644      (or undefinition) comes from the command line.  These macros are defined
22645      before the first DW_MACINFO_start_file entry, and yet still need to be
22646      associated to the base file.
22647
22648      To determine the base file name, we scan the macro definitions until we
22649      reach the first DW_MACINFO_start_file entry.  We then initialize
22650      CURRENT_FILE accordingly so that any macro definition found before the
22651      first DW_MACINFO_start_file can still be associated to the base file.  */
22652
22653   mac_ptr = section->buffer + offset;
22654   mac_end = section->buffer + section->size;
22655
22656   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22657                                       &offset_size, section_is_gnu);
22658   if (mac_ptr == NULL)
22659     {
22660       /* We already issued a complaint.  */
22661       return;
22662     }
22663
22664   do
22665     {
22666       /* Do we at least have room for a macinfo type byte?  */
22667       if (mac_ptr >= mac_end)
22668         {
22669           /* Complaint is printed during the second pass as GDB will probably
22670              stop the first pass earlier upon finding
22671              DW_MACINFO_start_file.  */
22672           break;
22673         }
22674
22675       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22676       mac_ptr++;
22677
22678       /* Note that we rely on the fact that the corresponding GNU and
22679          DWARF constants are the same.  */
22680       switch (macinfo_type)
22681         {
22682           /* A zero macinfo type indicates the end of the macro
22683              information.  */
22684         case 0:
22685           break;
22686
22687         case DW_MACRO_define:
22688         case DW_MACRO_undef:
22689           /* Only skip the data by MAC_PTR.  */
22690           {
22691             unsigned int bytes_read;
22692
22693             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22694             mac_ptr += bytes_read;
22695             read_direct_string (abfd, mac_ptr, &bytes_read);
22696             mac_ptr += bytes_read;
22697           }
22698           break;
22699
22700         case DW_MACRO_start_file:
22701           {
22702             unsigned int bytes_read;
22703             int line, file;
22704
22705             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22706             mac_ptr += bytes_read;
22707             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22708             mac_ptr += bytes_read;
22709
22710             current_file = macro_start_file (file, line, current_file, lh);
22711           }
22712           break;
22713
22714         case DW_MACRO_end_file:
22715           /* No data to skip by MAC_PTR.  */
22716           break;
22717
22718         case DW_MACRO_define_strp:
22719         case DW_MACRO_undef_strp:
22720         case DW_MACRO_define_sup:
22721         case DW_MACRO_undef_sup:
22722           {
22723             unsigned int bytes_read;
22724
22725             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22726             mac_ptr += bytes_read;
22727             mac_ptr += offset_size;
22728           }
22729           break;
22730
22731         case DW_MACRO_import:
22732         case DW_MACRO_import_sup:
22733           /* Note that, according to the spec, a transparent include
22734              chain cannot call DW_MACRO_start_file.  So, we can just
22735              skip this opcode.  */
22736           mac_ptr += offset_size;
22737           break;
22738
22739         case DW_MACINFO_vendor_ext:
22740           /* Only skip the data by MAC_PTR.  */
22741           if (!section_is_gnu)
22742             {
22743               unsigned int bytes_read;
22744
22745               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22746               mac_ptr += bytes_read;
22747               read_direct_string (abfd, mac_ptr, &bytes_read);
22748               mac_ptr += bytes_read;
22749             }
22750           /* FALLTHROUGH */
22751
22752         default:
22753           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22754                                          mac_ptr, mac_end, abfd, offset_size,
22755                                          section);
22756           if (mac_ptr == NULL)
22757             return;
22758           break;
22759         }
22760     } while (macinfo_type != 0 && current_file == NULL);
22761
22762   /* Second pass: Process all entries.
22763
22764      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22765      command-line macro definitions/undefinitions.  This flag is unset when we
22766      reach the first DW_MACINFO_start_file entry.  */
22767
22768   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22769                                            htab_eq_pointer,
22770                                            NULL, xcalloc, xfree));
22771   mac_ptr = section->buffer + offset;
22772   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22773   *slot = (void *) mac_ptr;
22774   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22775                             current_file, lh, section,
22776                             section_is_gnu, 0, offset_size,
22777                             include_hash.get ());
22778 }
22779
22780 /* Check if the attribute's form is a DW_FORM_block*
22781    if so return true else false.  */
22782
22783 static int
22784 attr_form_is_block (const struct attribute *attr)
22785 {
22786   return (attr == NULL ? 0 :
22787       attr->form == DW_FORM_block1
22788       || attr->form == DW_FORM_block2
22789       || attr->form == DW_FORM_block4
22790       || attr->form == DW_FORM_block
22791       || attr->form == DW_FORM_exprloc);
22792 }
22793
22794 /* Return non-zero if ATTR's value is a section offset --- classes
22795    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22796    You may use DW_UNSND (attr) to retrieve such offsets.
22797
22798    Section 7.5.4, "Attribute Encodings", explains that no attribute
22799    may have a value that belongs to more than one of these classes; it
22800    would be ambiguous if we did, because we use the same forms for all
22801    of them.  */
22802
22803 static int
22804 attr_form_is_section_offset (const struct attribute *attr)
22805 {
22806   return (attr->form == DW_FORM_data4
22807           || attr->form == DW_FORM_data8
22808           || attr->form == DW_FORM_sec_offset);
22809 }
22810
22811 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22812    zero otherwise.  When this function returns true, you can apply
22813    dwarf2_get_attr_constant_value to it.
22814
22815    However, note that for some attributes you must check
22816    attr_form_is_section_offset before using this test.  DW_FORM_data4
22817    and DW_FORM_data8 are members of both the constant class, and of
22818    the classes that contain offsets into other debug sections
22819    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22820    that, if an attribute's can be either a constant or one of the
22821    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22822    taken as section offsets, not constants.
22823
22824    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22825    cannot handle that.  */
22826
22827 static int
22828 attr_form_is_constant (const struct attribute *attr)
22829 {
22830   switch (attr->form)
22831     {
22832     case DW_FORM_sdata:
22833     case DW_FORM_udata:
22834     case DW_FORM_data1:
22835     case DW_FORM_data2:
22836     case DW_FORM_data4:
22837     case DW_FORM_data8:
22838     case DW_FORM_implicit_const:
22839       return 1;
22840     default:
22841       return 0;
22842     }
22843 }
22844
22845
22846 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22847    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22848
22849 static int
22850 attr_form_is_ref (const struct attribute *attr)
22851 {
22852   switch (attr->form)
22853     {
22854     case DW_FORM_ref_addr:
22855     case DW_FORM_ref1:
22856     case DW_FORM_ref2:
22857     case DW_FORM_ref4:
22858     case DW_FORM_ref8:
22859     case DW_FORM_ref_udata:
22860     case DW_FORM_GNU_ref_alt:
22861       return 1;
22862     default:
22863       return 0;
22864     }
22865 }
22866
22867 /* Return the .debug_loc section to use for CU.
22868    For DWO files use .debug_loc.dwo.  */
22869
22870 static struct dwarf2_section_info *
22871 cu_debug_loc_section (struct dwarf2_cu *cu)
22872 {
22873   if (cu->dwo_unit)
22874     {
22875       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22876       
22877       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22878     }
22879   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22880                                   : &dwarf2_per_objfile->loc);
22881 }
22882
22883 /* A helper function that fills in a dwarf2_loclist_baton.  */
22884
22885 static void
22886 fill_in_loclist_baton (struct dwarf2_cu *cu,
22887                        struct dwarf2_loclist_baton *baton,
22888                        const struct attribute *attr)
22889 {
22890   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22891
22892   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22893
22894   baton->per_cu = cu->per_cu;
22895   gdb_assert (baton->per_cu);
22896   /* We don't know how long the location list is, but make sure we
22897      don't run off the edge of the section.  */
22898   baton->size = section->size - DW_UNSND (attr);
22899   baton->data = section->buffer + DW_UNSND (attr);
22900   baton->base_address = cu->base_address;
22901   baton->from_dwo = cu->dwo_unit != NULL;
22902 }
22903
22904 static void
22905 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22906                              struct dwarf2_cu *cu, int is_block)
22907 {
22908   struct objfile *objfile = dwarf2_per_objfile->objfile;
22909   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22910
22911   if (attr_form_is_section_offset (attr)
22912       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22913          the section.  If so, fall through to the complaint in the
22914          other branch.  */
22915       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22916     {
22917       struct dwarf2_loclist_baton *baton;
22918
22919       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22920
22921       fill_in_loclist_baton (cu, baton, attr);
22922
22923       if (cu->base_known == 0)
22924         complaint (&symfile_complaints,
22925                    _("Location list used without "
22926                      "specifying the CU base address."));
22927
22928       SYMBOL_ACLASS_INDEX (sym) = (is_block
22929                                    ? dwarf2_loclist_block_index
22930                                    : dwarf2_loclist_index);
22931       SYMBOL_LOCATION_BATON (sym) = baton;
22932     }
22933   else
22934     {
22935       struct dwarf2_locexpr_baton *baton;
22936
22937       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22938       baton->per_cu = cu->per_cu;
22939       gdb_assert (baton->per_cu);
22940
22941       if (attr_form_is_block (attr))
22942         {
22943           /* Note that we're just copying the block's data pointer
22944              here, not the actual data.  We're still pointing into the
22945              info_buffer for SYM's objfile; right now we never release
22946              that buffer, but when we do clean up properly this may
22947              need to change.  */
22948           baton->size = DW_BLOCK (attr)->size;
22949           baton->data = DW_BLOCK (attr)->data;
22950         }
22951       else
22952         {
22953           dwarf2_invalid_attrib_class_complaint ("location description",
22954                                                  SYMBOL_NATURAL_NAME (sym));
22955           baton->size = 0;
22956         }
22957
22958       SYMBOL_ACLASS_INDEX (sym) = (is_block
22959                                    ? dwarf2_locexpr_block_index
22960                                    : dwarf2_locexpr_index);
22961       SYMBOL_LOCATION_BATON (sym) = baton;
22962     }
22963 }
22964
22965 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22966    came from a separate debuginfo file, then the master objfile is
22967    returned.  */
22968
22969 struct objfile *
22970 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22971 {
22972   struct objfile *objfile = per_cu->objfile;
22973
22974   /* Return the master objfile, so that we can report and look up the
22975      correct file containing this variable.  */
22976   if (objfile->separate_debug_objfile_backlink)
22977     objfile = objfile->separate_debug_objfile_backlink;
22978
22979   return objfile;
22980 }
22981
22982 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22983    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22984    CU_HEADERP first.  */
22985
22986 static const struct comp_unit_head *
22987 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22988                        struct dwarf2_per_cu_data *per_cu)
22989 {
22990   const gdb_byte *info_ptr;
22991
22992   if (per_cu->cu)
22993     return &per_cu->cu->header;
22994
22995   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22996
22997   memset (cu_headerp, 0, sizeof (*cu_headerp));
22998   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22999                        rcuh_kind::COMPILE);
23000
23001   return cu_headerp;
23002 }
23003
23004 /* Return the address size given in the compilation unit header for CU.  */
23005
23006 int
23007 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
23008 {
23009   struct comp_unit_head cu_header_local;
23010   const struct comp_unit_head *cu_headerp;
23011
23012   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23013
23014   return cu_headerp->addr_size;
23015 }
23016
23017 /* Return the offset size given in the compilation unit header for CU.  */
23018
23019 int
23020 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23021 {
23022   struct comp_unit_head cu_header_local;
23023   const struct comp_unit_head *cu_headerp;
23024
23025   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23026
23027   return cu_headerp->offset_size;
23028 }
23029
23030 /* See its dwarf2loc.h declaration.  */
23031
23032 int
23033 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23034 {
23035   struct comp_unit_head cu_header_local;
23036   const struct comp_unit_head *cu_headerp;
23037
23038   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23039
23040   if (cu_headerp->version == 2)
23041     return cu_headerp->addr_size;
23042   else
23043     return cu_headerp->offset_size;
23044 }
23045
23046 /* Return the text offset of the CU.  The returned offset comes from
23047    this CU's objfile.  If this objfile came from a separate debuginfo
23048    file, then the offset may be different from the corresponding
23049    offset in the parent objfile.  */
23050
23051 CORE_ADDR
23052 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23053 {
23054   struct objfile *objfile = per_cu->objfile;
23055
23056   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23057 }
23058
23059 /* Return DWARF version number of PER_CU.  */
23060
23061 short
23062 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23063 {
23064   return per_cu->dwarf_version;
23065 }
23066
23067 /* Locate the .debug_info compilation unit from CU's objfile which contains
23068    the DIE at OFFSET.  Raises an error on failure.  */
23069
23070 static struct dwarf2_per_cu_data *
23071 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23072                                   unsigned int offset_in_dwz,
23073                                   struct objfile *objfile)
23074 {
23075   struct dwarf2_per_cu_data *this_cu;
23076   int low, high;
23077   const sect_offset *cu_off;
23078
23079   low = 0;
23080   high = dwarf2_per_objfile->n_comp_units - 1;
23081   while (high > low)
23082     {
23083       struct dwarf2_per_cu_data *mid_cu;
23084       int mid = low + (high - low) / 2;
23085
23086       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23087       cu_off = &mid_cu->sect_off;
23088       if (mid_cu->is_dwz > offset_in_dwz
23089           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23090         high = mid;
23091       else
23092         low = mid + 1;
23093     }
23094   gdb_assert (low == high);
23095   this_cu = dwarf2_per_objfile->all_comp_units[low];
23096   cu_off = &this_cu->sect_off;
23097   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23098     {
23099       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23100         error (_("Dwarf Error: could not find partial DIE containing "
23101                "offset 0x%x [in module %s]"),
23102                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23103
23104       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23105                   <= sect_off);
23106       return dwarf2_per_objfile->all_comp_units[low-1];
23107     }
23108   else
23109     {
23110       this_cu = dwarf2_per_objfile->all_comp_units[low];
23111       if (low == dwarf2_per_objfile->n_comp_units - 1
23112           && sect_off >= this_cu->sect_off + this_cu->length)
23113         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23114       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23115       return this_cu;
23116     }
23117 }
23118
23119 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23120
23121 static void
23122 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23123 {
23124   memset (cu, 0, sizeof (*cu));
23125   per_cu->cu = cu;
23126   cu->per_cu = per_cu;
23127   cu->objfile = per_cu->objfile;
23128   obstack_init (&cu->comp_unit_obstack);
23129 }
23130
23131 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23132
23133 static void
23134 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23135                        enum language pretend_language)
23136 {
23137   struct attribute *attr;
23138
23139   /* Set the language we're debugging.  */
23140   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23141   if (attr)
23142     set_cu_language (DW_UNSND (attr), cu);
23143   else
23144     {
23145       cu->language = pretend_language;
23146       cu->language_defn = language_def (cu->language);
23147     }
23148
23149   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23150 }
23151
23152 /* Release one cached compilation unit, CU.  We unlink it from the tree
23153    of compilation units, but we don't remove it from the read_in_chain;
23154    the caller is responsible for that.
23155    NOTE: DATA is a void * because this function is also used as a
23156    cleanup routine.  */
23157
23158 static void
23159 free_heap_comp_unit (void *data)
23160 {
23161   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23162
23163   gdb_assert (cu->per_cu != NULL);
23164   cu->per_cu->cu = NULL;
23165   cu->per_cu = NULL;
23166
23167   obstack_free (&cu->comp_unit_obstack, NULL);
23168
23169   xfree (cu);
23170 }
23171
23172 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23173    when we're finished with it.  We can't free the pointer itself, but be
23174    sure to unlink it from the cache.  Also release any associated storage.  */
23175
23176 static void
23177 free_stack_comp_unit (void *data)
23178 {
23179   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23180
23181   gdb_assert (cu->per_cu != NULL);
23182   cu->per_cu->cu = NULL;
23183   cu->per_cu = NULL;
23184
23185   obstack_free (&cu->comp_unit_obstack, NULL);
23186   cu->partial_dies = NULL;
23187 }
23188
23189 /* Free all cached compilation units.  */
23190
23191 static void
23192 free_cached_comp_units (void *data)
23193 {
23194   dwarf2_per_objfile->free_cached_comp_units ();
23195 }
23196
23197 /* Increase the age counter on each cached compilation unit, and free
23198    any that are too old.  */
23199
23200 static void
23201 age_cached_comp_units (void)
23202 {
23203   struct dwarf2_per_cu_data *per_cu, **last_chain;
23204
23205   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23206   per_cu = dwarf2_per_objfile->read_in_chain;
23207   while (per_cu != NULL)
23208     {
23209       per_cu->cu->last_used ++;
23210       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23211         dwarf2_mark (per_cu->cu);
23212       per_cu = per_cu->cu->read_in_chain;
23213     }
23214
23215   per_cu = dwarf2_per_objfile->read_in_chain;
23216   last_chain = &dwarf2_per_objfile->read_in_chain;
23217   while (per_cu != NULL)
23218     {
23219       struct dwarf2_per_cu_data *next_cu;
23220
23221       next_cu = per_cu->cu->read_in_chain;
23222
23223       if (!per_cu->cu->mark)
23224         {
23225           free_heap_comp_unit (per_cu->cu);
23226           *last_chain = next_cu;
23227         }
23228       else
23229         last_chain = &per_cu->cu->read_in_chain;
23230
23231       per_cu = next_cu;
23232     }
23233 }
23234
23235 /* Remove a single compilation unit from the cache.  */
23236
23237 static void
23238 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23239 {
23240   struct dwarf2_per_cu_data *per_cu, **last_chain;
23241
23242   per_cu = dwarf2_per_objfile->read_in_chain;
23243   last_chain = &dwarf2_per_objfile->read_in_chain;
23244   while (per_cu != NULL)
23245     {
23246       struct dwarf2_per_cu_data *next_cu;
23247
23248       next_cu = per_cu->cu->read_in_chain;
23249
23250       if (per_cu == target_per_cu)
23251         {
23252           free_heap_comp_unit (per_cu->cu);
23253           per_cu->cu = NULL;
23254           *last_chain = next_cu;
23255           break;
23256         }
23257       else
23258         last_chain = &per_cu->cu->read_in_chain;
23259
23260       per_cu = next_cu;
23261     }
23262 }
23263
23264 /* Release all extra memory associated with OBJFILE.  */
23265
23266 void
23267 dwarf2_free_objfile (struct objfile *objfile)
23268 {
23269   dwarf2_per_objfile
23270     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23271                                                   dwarf2_objfile_data_key);
23272
23273   if (dwarf2_per_objfile == NULL)
23274     return;
23275
23276   dwarf2_per_objfile->~dwarf2_per_objfile ();
23277 }
23278
23279 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23280    We store these in a hash table separate from the DIEs, and preserve them
23281    when the DIEs are flushed out of cache.
23282
23283    The CU "per_cu" pointer is needed because offset alone is not enough to
23284    uniquely identify the type.  A file may have multiple .debug_types sections,
23285    or the type may come from a DWO file.  Furthermore, while it's more logical
23286    to use per_cu->section+offset, with Fission the section with the data is in
23287    the DWO file but we don't know that section at the point we need it.
23288    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23289    because we can enter the lookup routine, get_die_type_at_offset, from
23290    outside this file, and thus won't necessarily have PER_CU->cu.
23291    Fortunately, PER_CU is stable for the life of the objfile.  */
23292
23293 struct dwarf2_per_cu_offset_and_type
23294 {
23295   const struct dwarf2_per_cu_data *per_cu;
23296   sect_offset sect_off;
23297   struct type *type;
23298 };
23299
23300 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23301
23302 static hashval_t
23303 per_cu_offset_and_type_hash (const void *item)
23304 {
23305   const struct dwarf2_per_cu_offset_and_type *ofs
23306     = (const struct dwarf2_per_cu_offset_and_type *) item;
23307
23308   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23309 }
23310
23311 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23312
23313 static int
23314 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23315 {
23316   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23317     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23318   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23319     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23320
23321   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23322           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23323 }
23324
23325 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23326    table if necessary.  For convenience, return TYPE.
23327
23328    The DIEs reading must have careful ordering to:
23329     * Not cause infite loops trying to read in DIEs as a prerequisite for
23330       reading current DIE.
23331     * Not trying to dereference contents of still incompletely read in types
23332       while reading in other DIEs.
23333     * Enable referencing still incompletely read in types just by a pointer to
23334       the type without accessing its fields.
23335
23336    Therefore caller should follow these rules:
23337      * Try to fetch any prerequisite types we may need to build this DIE type
23338        before building the type and calling set_die_type.
23339      * After building type call set_die_type for current DIE as soon as
23340        possible before fetching more types to complete the current type.
23341      * Make the type as complete as possible before fetching more types.  */
23342
23343 static struct type *
23344 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23345 {
23346   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23347   struct objfile *objfile = cu->objfile;
23348   struct attribute *attr;
23349   struct dynamic_prop prop;
23350
23351   /* For Ada types, make sure that the gnat-specific data is always
23352      initialized (if not already set).  There are a few types where
23353      we should not be doing so, because the type-specific area is
23354      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23355      where the type-specific area is used to store the floatformat).
23356      But this is not a problem, because the gnat-specific information
23357      is actually not needed for these types.  */
23358   if (need_gnat_info (cu)
23359       && TYPE_CODE (type) != TYPE_CODE_FUNC
23360       && TYPE_CODE (type) != TYPE_CODE_FLT
23361       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23362       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23363       && TYPE_CODE (type) != TYPE_CODE_METHOD
23364       && !HAVE_GNAT_AUX_INFO (type))
23365     INIT_GNAT_SPECIFIC (type);
23366
23367   /* Read DW_AT_allocated and set in type.  */
23368   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23369   if (attr_form_is_block (attr))
23370     {
23371       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23372         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23373     }
23374   else if (attr != NULL)
23375     {
23376       complaint (&symfile_complaints,
23377                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23378                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23379                  to_underlying (die->sect_off));
23380     }
23381
23382   /* Read DW_AT_associated and set in type.  */
23383   attr = dwarf2_attr (die, DW_AT_associated, cu);
23384   if (attr_form_is_block (attr))
23385     {
23386       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23387         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23388     }
23389   else if (attr != NULL)
23390     {
23391       complaint (&symfile_complaints,
23392                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23393                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23394                  to_underlying (die->sect_off));
23395     }
23396
23397   /* Read DW_AT_data_location and set in type.  */
23398   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23399   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23400     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23401
23402   if (dwarf2_per_objfile->die_type_hash == NULL)
23403     {
23404       dwarf2_per_objfile->die_type_hash =
23405         htab_create_alloc_ex (127,
23406                               per_cu_offset_and_type_hash,
23407                               per_cu_offset_and_type_eq,
23408                               NULL,
23409                               &objfile->objfile_obstack,
23410                               hashtab_obstack_allocate,
23411                               dummy_obstack_deallocate);
23412     }
23413
23414   ofs.per_cu = cu->per_cu;
23415   ofs.sect_off = die->sect_off;
23416   ofs.type = type;
23417   slot = (struct dwarf2_per_cu_offset_and_type **)
23418     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23419   if (*slot)
23420     complaint (&symfile_complaints,
23421                _("A problem internal to GDB: DIE 0x%x has type already set"),
23422                to_underlying (die->sect_off));
23423   *slot = XOBNEW (&objfile->objfile_obstack,
23424                   struct dwarf2_per_cu_offset_and_type);
23425   **slot = ofs;
23426   return type;
23427 }
23428
23429 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23430    or return NULL if the die does not have a saved type.  */
23431
23432 static struct type *
23433 get_die_type_at_offset (sect_offset sect_off,
23434                         struct dwarf2_per_cu_data *per_cu)
23435 {
23436   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23437
23438   if (dwarf2_per_objfile->die_type_hash == NULL)
23439     return NULL;
23440
23441   ofs.per_cu = per_cu;
23442   ofs.sect_off = sect_off;
23443   slot = ((struct dwarf2_per_cu_offset_and_type *)
23444           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23445   if (slot)
23446     return slot->type;
23447   else
23448     return NULL;
23449 }
23450
23451 /* Look up the type for DIE in CU in die_type_hash,
23452    or return NULL if DIE does not have a saved type.  */
23453
23454 static struct type *
23455 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23456 {
23457   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23458 }
23459
23460 /* Add a dependence relationship from CU to REF_PER_CU.  */
23461
23462 static void
23463 dwarf2_add_dependence (struct dwarf2_cu *cu,
23464                        struct dwarf2_per_cu_data *ref_per_cu)
23465 {
23466   void **slot;
23467
23468   if (cu->dependencies == NULL)
23469     cu->dependencies
23470       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23471                               NULL, &cu->comp_unit_obstack,
23472                               hashtab_obstack_allocate,
23473                               dummy_obstack_deallocate);
23474
23475   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23476   if (*slot == NULL)
23477     *slot = ref_per_cu;
23478 }
23479
23480 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23481    Set the mark field in every compilation unit in the
23482    cache that we must keep because we are keeping CU.  */
23483
23484 static int
23485 dwarf2_mark_helper (void **slot, void *data)
23486 {
23487   struct dwarf2_per_cu_data *per_cu;
23488
23489   per_cu = (struct dwarf2_per_cu_data *) *slot;
23490
23491   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23492      reading of the chain.  As such dependencies remain valid it is not much
23493      useful to track and undo them during QUIT cleanups.  */
23494   if (per_cu->cu == NULL)
23495     return 1;
23496
23497   if (per_cu->cu->mark)
23498     return 1;
23499   per_cu->cu->mark = 1;
23500
23501   if (per_cu->cu->dependencies != NULL)
23502     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23503
23504   return 1;
23505 }
23506
23507 /* Set the mark field in CU and in every other compilation unit in the
23508    cache that we must keep because we are keeping CU.  */
23509
23510 static void
23511 dwarf2_mark (struct dwarf2_cu *cu)
23512 {
23513   if (cu->mark)
23514     return;
23515   cu->mark = 1;
23516   if (cu->dependencies != NULL)
23517     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23518 }
23519
23520 static void
23521 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23522 {
23523   while (per_cu)
23524     {
23525       per_cu->cu->mark = 0;
23526       per_cu = per_cu->cu->read_in_chain;
23527     }
23528 }
23529
23530 /* Trivial hash function for partial_die_info: the hash value of a DIE
23531    is its offset in .debug_info for this objfile.  */
23532
23533 static hashval_t
23534 partial_die_hash (const void *item)
23535 {
23536   const struct partial_die_info *part_die
23537     = (const struct partial_die_info *) item;
23538
23539   return to_underlying (part_die->sect_off);
23540 }
23541
23542 /* Trivial comparison function for partial_die_info structures: two DIEs
23543    are equal if they have the same offset.  */
23544
23545 static int
23546 partial_die_eq (const void *item_lhs, const void *item_rhs)
23547 {
23548   const struct partial_die_info *part_die_lhs
23549     = (const struct partial_die_info *) item_lhs;
23550   const struct partial_die_info *part_die_rhs
23551     = (const struct partial_die_info *) item_rhs;
23552
23553   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23554 }
23555
23556 static struct cmd_list_element *set_dwarf_cmdlist;
23557 static struct cmd_list_element *show_dwarf_cmdlist;
23558
23559 static void
23560 set_dwarf_cmd (const char *args, int from_tty)
23561 {
23562   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23563              gdb_stdout);
23564 }
23565
23566 static void
23567 show_dwarf_cmd (const char *args, int from_tty)
23568 {
23569   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23570 }
23571
23572 /* Free data associated with OBJFILE, if necessary.  */
23573
23574 static void
23575 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23576 {
23577   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23578   int ix;
23579
23580   /* Make sure we don't accidentally use dwarf2_per_objfile while
23581      cleaning up.  */
23582   dwarf2_per_objfile = NULL;
23583
23584   for (ix = 0; ix < data->n_comp_units; ++ix)
23585    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23586
23587   for (ix = 0; ix < data->n_type_units; ++ix)
23588     VEC_free (dwarf2_per_cu_ptr,
23589               data->all_type_units[ix]->per_cu.imported_symtabs);
23590   xfree (data->all_type_units);
23591
23592   VEC_free (dwarf2_section_info_def, data->types);
23593
23594   if (data->dwo_files)
23595     free_dwo_files (data->dwo_files, objfile);
23596   if (data->dwp_file)
23597     gdb_bfd_unref (data->dwp_file->dbfd);
23598
23599   if (data->dwz_file && data->dwz_file->dwz_bfd)
23600     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23601
23602   if (data->index_table != NULL)
23603     data->index_table->~mapped_index ();
23604 }
23605
23606 \f
23607 /* The "save gdb-index" command.  */
23608
23609 /* In-memory buffer to prepare data to be written later to a file.  */
23610 class data_buf
23611 {
23612 public:
23613   /* Copy DATA to the end of the buffer.  */
23614   template<typename T>
23615   void append_data (const T &data)
23616   {
23617     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23618                reinterpret_cast<const gdb_byte *> (&data + 1),
23619                grow (sizeof (data)));
23620   }
23621
23622   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23623      terminating zero is appended too.  */
23624   void append_cstr0 (const char *cstr)
23625   {
23626     const size_t size = strlen (cstr) + 1;
23627     std::copy (cstr, cstr + size, grow (size));
23628   }
23629
23630   /* Accept a host-format integer in VAL and append it to the buffer
23631      as a target-format integer which is LEN bytes long.  */
23632   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23633   {
23634     ::store_unsigned_integer (grow (len), len, byte_order, val);
23635   }
23636
23637   /* Return the size of the buffer.  */
23638   size_t size () const
23639   {
23640     return m_vec.size ();
23641   }
23642
23643   /* Write the buffer to FILE.  */
23644   void file_write (FILE *file) const
23645   {
23646     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23647       error (_("couldn't write data to file"));
23648   }
23649
23650 private:
23651   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23652      the start of the new block.  */
23653   gdb_byte *grow (size_t size)
23654   {
23655     m_vec.resize (m_vec.size () + size);
23656     return &*m_vec.end () - size;
23657   }
23658
23659   gdb::byte_vector m_vec;
23660 };
23661
23662 /* An entry in the symbol table.  */
23663 struct symtab_index_entry
23664 {
23665   /* The name of the symbol.  */
23666   const char *name;
23667   /* The offset of the name in the constant pool.  */
23668   offset_type index_offset;
23669   /* A sorted vector of the indices of all the CUs that hold an object
23670      of this name.  */
23671   std::vector<offset_type> cu_indices;
23672 };
23673
23674 /* The symbol table.  This is a power-of-2-sized hash table.  */
23675 struct mapped_symtab
23676 {
23677   mapped_symtab ()
23678   {
23679     data.resize (1024);
23680   }
23681
23682   offset_type n_elements = 0;
23683   std::vector<symtab_index_entry> data;
23684 };
23685
23686 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23687    the slot.
23688    
23689    Function is used only during write_hash_table so no index format backward
23690    compatibility is needed.  */
23691
23692 static symtab_index_entry &
23693 find_slot (struct mapped_symtab *symtab, const char *name)
23694 {
23695   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23696
23697   index = hash & (symtab->data.size () - 1);
23698   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23699
23700   for (;;)
23701     {
23702       if (symtab->data[index].name == NULL
23703           || strcmp (name, symtab->data[index].name) == 0)
23704         return symtab->data[index];
23705       index = (index + step) & (symtab->data.size () - 1);
23706     }
23707 }
23708
23709 /* Expand SYMTAB's hash table.  */
23710
23711 static void
23712 hash_expand (struct mapped_symtab *symtab)
23713 {
23714   auto old_entries = std::move (symtab->data);
23715
23716   symtab->data.clear ();
23717   symtab->data.resize (old_entries.size () * 2);
23718
23719   for (auto &it : old_entries)
23720     if (it.name != NULL)
23721       {
23722         auto &ref = find_slot (symtab, it.name);
23723         ref = std::move (it);
23724       }
23725 }
23726
23727 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23728    CU_INDEX is the index of the CU in which the symbol appears.
23729    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23730
23731 static void
23732 add_index_entry (struct mapped_symtab *symtab, const char *name,
23733                  int is_static, gdb_index_symbol_kind kind,
23734                  offset_type cu_index)
23735 {
23736   offset_type cu_index_and_attrs;
23737
23738   ++symtab->n_elements;
23739   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23740     hash_expand (symtab);
23741
23742   symtab_index_entry &slot = find_slot (symtab, name);
23743   if (slot.name == NULL)
23744     {
23745       slot.name = name;
23746       /* index_offset is set later.  */
23747     }
23748
23749   cu_index_and_attrs = 0;
23750   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23751   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23752   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23753
23754   /* We don't want to record an index value twice as we want to avoid the
23755      duplication.
23756      We process all global symbols and then all static symbols
23757      (which would allow us to avoid the duplication by only having to check
23758      the last entry pushed), but a symbol could have multiple kinds in one CU.
23759      To keep things simple we don't worry about the duplication here and
23760      sort and uniqufy the list after we've processed all symbols.  */
23761   slot.cu_indices.push_back (cu_index_and_attrs);
23762 }
23763
23764 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23765
23766 static void
23767 uniquify_cu_indices (struct mapped_symtab *symtab)
23768 {
23769   for (auto &entry : symtab->data)
23770     {
23771       if (entry.name != NULL && !entry.cu_indices.empty ())
23772         {
23773           auto &cu_indices = entry.cu_indices;
23774           std::sort (cu_indices.begin (), cu_indices.end ());
23775           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23776           cu_indices.erase (from, cu_indices.end ());
23777         }
23778     }
23779 }
23780
23781 /* A form of 'const char *' suitable for container keys.  Only the
23782    pointer is stored.  The strings themselves are compared, not the
23783    pointers.  */
23784 class c_str_view
23785 {
23786 public:
23787   c_str_view (const char *cstr)
23788     : m_cstr (cstr)
23789   {}
23790
23791   bool operator== (const c_str_view &other) const
23792   {
23793     return strcmp (m_cstr, other.m_cstr) == 0;
23794   }
23795
23796 private:
23797   friend class c_str_view_hasher;
23798   const char *const m_cstr;
23799 };
23800
23801 /* A std::unordered_map::hasher for c_str_view that uses the right
23802    hash function for strings in a mapped index.  */
23803 class c_str_view_hasher
23804 {
23805 public:
23806   size_t operator () (const c_str_view &x) const
23807   {
23808     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23809   }
23810 };
23811
23812 /* A std::unordered_map::hasher for std::vector<>.  */
23813 template<typename T>
23814 class vector_hasher
23815 {
23816 public:
23817   size_t operator () (const std::vector<T> &key) const
23818   {
23819     return iterative_hash (key.data (),
23820                            sizeof (key.front ()) * key.size (), 0);
23821   }
23822 };
23823
23824 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23825    constant pool entries going into the data buffer CPOOL.  */
23826
23827 static void
23828 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23829 {
23830   {
23831     /* Elements are sorted vectors of the indices of all the CUs that
23832        hold an object of this name.  */
23833     std::unordered_map<std::vector<offset_type>, offset_type,
23834                        vector_hasher<offset_type>>
23835       symbol_hash_table;
23836
23837     /* We add all the index vectors to the constant pool first, to
23838        ensure alignment is ok.  */
23839     for (symtab_index_entry &entry : symtab->data)
23840       {
23841         if (entry.name == NULL)
23842           continue;
23843         gdb_assert (entry.index_offset == 0);
23844
23845         /* Finding before inserting is faster than always trying to
23846            insert, because inserting always allocates a node, does the
23847            lookup, and then destroys the new node if another node
23848            already had the same key.  C++17 try_emplace will avoid
23849            this.  */
23850         const auto found
23851           = symbol_hash_table.find (entry.cu_indices);
23852         if (found != symbol_hash_table.end ())
23853           {
23854             entry.index_offset = found->second;
23855             continue;
23856           }
23857
23858         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23859         entry.index_offset = cpool.size ();
23860         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23861         for (const auto index : entry.cu_indices)
23862           cpool.append_data (MAYBE_SWAP (index));
23863       }
23864   }
23865
23866   /* Now write out the hash table.  */
23867   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23868   for (const auto &entry : symtab->data)
23869     {
23870       offset_type str_off, vec_off;
23871
23872       if (entry.name != NULL)
23873         {
23874           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23875           if (insertpair.second)
23876             cpool.append_cstr0 (entry.name);
23877           str_off = insertpair.first->second;
23878           vec_off = entry.index_offset;
23879         }
23880       else
23881         {
23882           /* While 0 is a valid constant pool index, it is not valid
23883              to have 0 for both offsets.  */
23884           str_off = 0;
23885           vec_off = 0;
23886         }
23887
23888       output.append_data (MAYBE_SWAP (str_off));
23889       output.append_data (MAYBE_SWAP (vec_off));
23890     }
23891 }
23892
23893 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23894
23895 /* Helper struct for building the address table.  */
23896 struct addrmap_index_data
23897 {
23898   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23899     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23900   {}
23901
23902   struct objfile *objfile;
23903   data_buf &addr_vec;
23904   psym_index_map &cu_index_htab;
23905
23906   /* Non-zero if the previous_* fields are valid.
23907      We can't write an entry until we see the next entry (since it is only then
23908      that we know the end of the entry).  */
23909   int previous_valid;
23910   /* Index of the CU in the table of all CUs in the index file.  */
23911   unsigned int previous_cu_index;
23912   /* Start address of the CU.  */
23913   CORE_ADDR previous_cu_start;
23914 };
23915
23916 /* Write an address entry to ADDR_VEC.  */
23917
23918 static void
23919 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23920                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23921 {
23922   CORE_ADDR baseaddr;
23923
23924   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23925
23926   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23927   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23928   addr_vec.append_data (MAYBE_SWAP (cu_index));
23929 }
23930
23931 /* Worker function for traversing an addrmap to build the address table.  */
23932
23933 static int
23934 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23935 {
23936   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23937   struct partial_symtab *pst = (struct partial_symtab *) obj;
23938
23939   if (data->previous_valid)
23940     add_address_entry (data->objfile, data->addr_vec,
23941                        data->previous_cu_start, start_addr,
23942                        data->previous_cu_index);
23943
23944   data->previous_cu_start = start_addr;
23945   if (pst != NULL)
23946     {
23947       const auto it = data->cu_index_htab.find (pst);
23948       gdb_assert (it != data->cu_index_htab.cend ());
23949       data->previous_cu_index = it->second;
23950       data->previous_valid = 1;
23951     }
23952   else
23953     data->previous_valid = 0;
23954
23955   return 0;
23956 }
23957
23958 /* Write OBJFILE's address map to ADDR_VEC.
23959    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23960    in the index file.  */
23961
23962 static void
23963 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23964                    psym_index_map &cu_index_htab)
23965 {
23966   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23967
23968   /* When writing the address table, we have to cope with the fact that
23969      the addrmap iterator only provides the start of a region; we have to
23970      wait until the next invocation to get the start of the next region.  */
23971
23972   addrmap_index_data.objfile = objfile;
23973   addrmap_index_data.previous_valid = 0;
23974
23975   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23976                    &addrmap_index_data);
23977
23978   /* It's highly unlikely the last entry (end address = 0xff...ff)
23979      is valid, but we should still handle it.
23980      The end address is recorded as the start of the next region, but that
23981      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23982      anyway.  */
23983   if (addrmap_index_data.previous_valid)
23984     add_address_entry (objfile, addr_vec,
23985                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23986                        addrmap_index_data.previous_cu_index);
23987 }
23988
23989 /* Return the symbol kind of PSYM.  */
23990
23991 static gdb_index_symbol_kind
23992 symbol_kind (struct partial_symbol *psym)
23993 {
23994   domain_enum domain = PSYMBOL_DOMAIN (psym);
23995   enum address_class aclass = PSYMBOL_CLASS (psym);
23996
23997   switch (domain)
23998     {
23999     case VAR_DOMAIN:
24000       switch (aclass)
24001         {
24002         case LOC_BLOCK:
24003           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
24004         case LOC_TYPEDEF:
24005           return GDB_INDEX_SYMBOL_KIND_TYPE;
24006         case LOC_COMPUTED:
24007         case LOC_CONST_BYTES:
24008         case LOC_OPTIMIZED_OUT:
24009         case LOC_STATIC:
24010           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24011         case LOC_CONST:
24012           /* Note: It's currently impossible to recognize psyms as enum values
24013              short of reading the type info.  For now punt.  */
24014           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24015         default:
24016           /* There are other LOC_FOO values that one might want to classify
24017              as variables, but dwarf2read.c doesn't currently use them.  */
24018           return GDB_INDEX_SYMBOL_KIND_OTHER;
24019         }
24020     case STRUCT_DOMAIN:
24021       return GDB_INDEX_SYMBOL_KIND_TYPE;
24022     default:
24023       return GDB_INDEX_SYMBOL_KIND_OTHER;
24024     }
24025 }
24026
24027 /* Add a list of partial symbols to SYMTAB.  */
24028
24029 static void
24030 write_psymbols (struct mapped_symtab *symtab,
24031                 std::unordered_set<partial_symbol *> &psyms_seen,
24032                 struct partial_symbol **psymp,
24033                 int count,
24034                 offset_type cu_index,
24035                 int is_static)
24036 {
24037   for (; count-- > 0; ++psymp)
24038     {
24039       struct partial_symbol *psym = *psymp;
24040
24041       if (SYMBOL_LANGUAGE (psym) == language_ada)
24042         error (_("Ada is not currently supported by the index"));
24043
24044       /* Only add a given psymbol once.  */
24045       if (psyms_seen.insert (psym).second)
24046         {
24047           gdb_index_symbol_kind kind = symbol_kind (psym);
24048
24049           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24050                            is_static, kind, cu_index);
24051         }
24052     }
24053 }
24054
24055 /* A helper struct used when iterating over debug_types.  */
24056 struct signatured_type_index_data
24057 {
24058   signatured_type_index_data (data_buf &types_list_,
24059                               std::unordered_set<partial_symbol *> &psyms_seen_)
24060     : types_list (types_list_), psyms_seen (psyms_seen_)
24061   {}
24062
24063   struct objfile *objfile;
24064   struct mapped_symtab *symtab;
24065   data_buf &types_list;
24066   std::unordered_set<partial_symbol *> &psyms_seen;
24067   int cu_index;
24068 };
24069
24070 /* A helper function that writes a single signatured_type to an
24071    obstack.  */
24072
24073 static int
24074 write_one_signatured_type (void **slot, void *d)
24075 {
24076   struct signatured_type_index_data *info
24077     = (struct signatured_type_index_data *) d;
24078   struct signatured_type *entry = (struct signatured_type *) *slot;
24079   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24080
24081   write_psymbols (info->symtab,
24082                   info->psyms_seen,
24083                   &info->objfile->global_psymbols[psymtab->globals_offset],
24084                   psymtab->n_global_syms, info->cu_index,
24085                   0);
24086   write_psymbols (info->symtab,
24087                   info->psyms_seen,
24088                   &info->objfile->static_psymbols[psymtab->statics_offset],
24089                   psymtab->n_static_syms, info->cu_index,
24090                   1);
24091
24092   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24093                                 to_underlying (entry->per_cu.sect_off));
24094   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24095                                 to_underlying (entry->type_offset_in_tu));
24096   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24097
24098   ++info->cu_index;
24099
24100   return 1;
24101 }
24102
24103 /* Recurse into all "included" dependencies and count their symbols as
24104    if they appeared in this psymtab.  */
24105
24106 static void
24107 recursively_count_psymbols (struct partial_symtab *psymtab,
24108                             size_t &psyms_seen)
24109 {
24110   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24111     if (psymtab->dependencies[i]->user != NULL)
24112       recursively_count_psymbols (psymtab->dependencies[i],
24113                                   psyms_seen);
24114
24115   psyms_seen += psymtab->n_global_syms;
24116   psyms_seen += psymtab->n_static_syms;
24117 }
24118
24119 /* Recurse into all "included" dependencies and write their symbols as
24120    if they appeared in this psymtab.  */
24121
24122 static void
24123 recursively_write_psymbols (struct objfile *objfile,
24124                             struct partial_symtab *psymtab,
24125                             struct mapped_symtab *symtab,
24126                             std::unordered_set<partial_symbol *> &psyms_seen,
24127                             offset_type cu_index)
24128 {
24129   int i;
24130
24131   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24132     if (psymtab->dependencies[i]->user != NULL)
24133       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24134                                   symtab, psyms_seen, cu_index);
24135
24136   write_psymbols (symtab,
24137                   psyms_seen,
24138                   &objfile->global_psymbols[psymtab->globals_offset],
24139                   psymtab->n_global_syms, cu_index,
24140                   0);
24141   write_psymbols (symtab,
24142                   psyms_seen,
24143                   &objfile->static_psymbols[psymtab->statics_offset],
24144                   psymtab->n_static_syms, cu_index,
24145                   1);
24146 }
24147
24148 /* Create an index file for OBJFILE in the directory DIR.  */
24149
24150 static void
24151 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
24152 {
24153   if (dwarf2_per_objfile->using_index)
24154     error (_("Cannot use an index to create the index"));
24155
24156   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
24157     error (_("Cannot make an index when the file has multiple .debug_types sections"));
24158
24159   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
24160     return;
24161
24162   struct stat st;
24163   if (stat (objfile_name (objfile), &st) < 0)
24164     perror_with_name (objfile_name (objfile));
24165
24166   std::string filename (std::string (dir) + SLASH_STRING
24167                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
24168
24169   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
24170   if (!out_file)
24171     error (_("Can't open `%s' for writing"), filename.c_str ());
24172
24173   /* Order matters here; we want FILE to be closed before FILENAME is
24174      unlinked, because on MS-Windows one cannot delete a file that is
24175      still open.  (Don't call anything here that might throw until
24176      file_closer is created.)  */
24177   gdb::unlinker unlink_file (filename.c_str ());
24178   gdb_file_up close_out_file (out_file);
24179
24180   mapped_symtab symtab;
24181   data_buf cu_list;
24182
24183   /* While we're scanning CU's create a table that maps a psymtab pointer
24184      (which is what addrmap records) to its index (which is what is recorded
24185      in the index file).  This will later be needed to write the address
24186      table.  */
24187   psym_index_map cu_index_htab;
24188   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
24189
24190   /* The CU list is already sorted, so we don't need to do additional
24191      work here.  Also, the debug_types entries do not appear in
24192      all_comp_units, but only in their own hash table.  */
24193
24194   /* The psyms_seen set is potentially going to be largish (~40k
24195      elements when indexing a -g3 build of GDB itself).  Estimate the
24196      number of elements in order to avoid too many rehashes, which
24197      require rebuilding buckets and thus many trips to
24198      malloc/free.  */
24199   size_t psyms_count = 0;
24200   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24201     {
24202       struct dwarf2_per_cu_data *per_cu
24203         = dwarf2_per_objfile->all_comp_units[i];
24204       struct partial_symtab *psymtab = per_cu->v.psymtab;
24205
24206       if (psymtab != NULL && psymtab->user == NULL)
24207         recursively_count_psymbols (psymtab, psyms_count);
24208     }
24209   /* Generating an index for gdb itself shows a ratio of
24210      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
24211   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
24212   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24213     {
24214       struct dwarf2_per_cu_data *per_cu
24215         = dwarf2_per_objfile->all_comp_units[i];
24216       struct partial_symtab *psymtab = per_cu->v.psymtab;
24217
24218       /* CU of a shared file from 'dwz -m' may be unused by this main file.
24219          It may be referenced from a local scope but in such case it does not
24220          need to be present in .gdb_index.  */
24221       if (psymtab == NULL)
24222         continue;
24223
24224       if (psymtab->user == NULL)
24225         recursively_write_psymbols (objfile, psymtab, &symtab,
24226                                     psyms_seen, i);
24227
24228       const auto insertpair = cu_index_htab.emplace (psymtab, i);
24229       gdb_assert (insertpair.second);
24230
24231       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
24232                            to_underlying (per_cu->sect_off));
24233       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
24234     }
24235
24236   /* Dump the address map.  */
24237   data_buf addr_vec;
24238   write_address_map (objfile, addr_vec, cu_index_htab);
24239
24240   /* Write out the .debug_type entries, if any.  */
24241   data_buf types_cu_list;
24242   if (dwarf2_per_objfile->signatured_types)
24243     {
24244       signatured_type_index_data sig_data (types_cu_list,
24245                                            psyms_seen);
24246
24247       sig_data.objfile = objfile;
24248       sig_data.symtab = &symtab;
24249       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
24250       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
24251                               write_one_signatured_type, &sig_data);
24252     }
24253
24254   /* Now that we've processed all symbols we can shrink their cu_indices
24255      lists.  */
24256   uniquify_cu_indices (&symtab);
24257
24258   data_buf symtab_vec, constant_pool;
24259   write_hash_table (&symtab, symtab_vec, constant_pool);
24260
24261   data_buf contents;
24262   const offset_type size_of_contents = 6 * sizeof (offset_type);
24263   offset_type total_len = size_of_contents;
24264
24265   /* The version number.  */
24266   contents.append_data (MAYBE_SWAP (8));
24267
24268   /* The offset of the CU list from the start of the file.  */
24269   contents.append_data (MAYBE_SWAP (total_len));
24270   total_len += cu_list.size ();
24271
24272   /* The offset of the types CU list from the start of the file.  */
24273   contents.append_data (MAYBE_SWAP (total_len));
24274   total_len += types_cu_list.size ();
24275
24276   /* The offset of the address table from the start of the file.  */
24277   contents.append_data (MAYBE_SWAP (total_len));
24278   total_len += addr_vec.size ();
24279
24280   /* The offset of the symbol table from the start of the file.  */
24281   contents.append_data (MAYBE_SWAP (total_len));
24282   total_len += symtab_vec.size ();
24283
24284   /* The offset of the constant pool from the start of the file.  */
24285   contents.append_data (MAYBE_SWAP (total_len));
24286   total_len += constant_pool.size ();
24287
24288   gdb_assert (contents.size () == size_of_contents);
24289
24290   contents.file_write (out_file);
24291   cu_list.file_write (out_file);
24292   types_cu_list.file_write (out_file);
24293   addr_vec.file_write (out_file);
24294   symtab_vec.file_write (out_file);
24295   constant_pool.file_write (out_file);
24296
24297   /* We want to keep the file.  */
24298   unlink_file.keep ();
24299 }
24300
24301 /* Implementation of the `save gdb-index' command.
24302    
24303    Note that the file format used by this command is documented in the
24304    GDB manual.  Any changes here must be documented there.  */
24305
24306 static void
24307 save_gdb_index_command (const char *arg, int from_tty)
24308 {
24309   struct objfile *objfile;
24310
24311   if (!arg || !*arg)
24312     error (_("usage: save gdb-index DIRECTORY"));
24313
24314   ALL_OBJFILES (objfile)
24315   {
24316     struct stat st;
24317
24318     /* If the objfile does not correspond to an actual file, skip it.  */
24319     if (stat (objfile_name (objfile), &st) < 0)
24320       continue;
24321
24322     dwarf2_per_objfile
24323       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24324                                                     dwarf2_objfile_data_key);
24325     if (dwarf2_per_objfile)
24326       {
24327
24328         TRY
24329           {
24330             write_psymtabs_to_index (objfile, arg);
24331           }
24332         CATCH (except, RETURN_MASK_ERROR)
24333           {
24334             exception_fprintf (gdb_stderr, except,
24335                                _("Error while writing index for `%s': "),
24336                                objfile_name (objfile));
24337           }
24338         END_CATCH
24339       }
24340   }
24341 }
24342
24343 \f
24344
24345 int dwarf_always_disassemble;
24346
24347 static void
24348 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24349                                struct cmd_list_element *c, const char *value)
24350 {
24351   fprintf_filtered (file,
24352                     _("Whether to always disassemble "
24353                       "DWARF expressions is %s.\n"),
24354                     value);
24355 }
24356
24357 static void
24358 show_check_physname (struct ui_file *file, int from_tty,
24359                      struct cmd_list_element *c, const char *value)
24360 {
24361   fprintf_filtered (file,
24362                     _("Whether to check \"physname\" is %s.\n"),
24363                     value);
24364 }
24365
24366 void
24367 _initialize_dwarf2_read (void)
24368 {
24369   struct cmd_list_element *c;
24370
24371   dwarf2_objfile_data_key
24372     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24373
24374   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24375 Set DWARF specific variables.\n\
24376 Configure DWARF variables such as the cache size"),
24377                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24378                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24379
24380   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24381 Show DWARF specific variables\n\
24382 Show DWARF variables such as the cache size"),
24383                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24384                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24385
24386   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24387                             &dwarf_max_cache_age, _("\
24388 Set the upper bound on the age of cached DWARF compilation units."), _("\
24389 Show the upper bound on the age of cached DWARF compilation units."), _("\
24390 A higher limit means that cached compilation units will be stored\n\
24391 in memory longer, and more total memory will be used.  Zero disables\n\
24392 caching, which can slow down startup."),
24393                             NULL,
24394                             show_dwarf_max_cache_age,
24395                             &set_dwarf_cmdlist,
24396                             &show_dwarf_cmdlist);
24397
24398   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24399                            &dwarf_always_disassemble, _("\
24400 Set whether `info address' always disassembles DWARF expressions."), _("\
24401 Show whether `info address' always disassembles DWARF expressions."), _("\
24402 When enabled, DWARF expressions are always printed in an assembly-like\n\
24403 syntax.  When disabled, expressions will be printed in a more\n\
24404 conversational style, when possible."),
24405                            NULL,
24406                            show_dwarf_always_disassemble,
24407                            &set_dwarf_cmdlist,
24408                            &show_dwarf_cmdlist);
24409
24410   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24411 Set debugging of the DWARF reader."), _("\
24412 Show debugging of the DWARF reader."), _("\
24413 When enabled (non-zero), debugging messages are printed during DWARF\n\
24414 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24415 information.  A value greater than 1 provides more verbose information."),
24416                             NULL,
24417                             NULL,
24418                             &setdebuglist, &showdebuglist);
24419
24420   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24421 Set debugging of the DWARF DIE reader."), _("\
24422 Show debugging of the DWARF DIE reader."), _("\
24423 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24424 The value is the maximum depth to print."),
24425                              NULL,
24426                              NULL,
24427                              &setdebuglist, &showdebuglist);
24428
24429   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24430 Set debugging of the dwarf line reader."), _("\
24431 Show debugging of the dwarf line reader."), _("\
24432 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24433 A value of 1 (one) provides basic information.\n\
24434 A value greater than 1 provides more verbose information."),
24435                              NULL,
24436                              NULL,
24437                              &setdebuglist, &showdebuglist);
24438
24439   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24440 Set cross-checking of \"physname\" code against demangler."), _("\
24441 Show cross-checking of \"physname\" code against demangler."), _("\
24442 When enabled, GDB's internal \"physname\" code is checked against\n\
24443 the demangler."),
24444                            NULL, show_check_physname,
24445                            &setdebuglist, &showdebuglist);
24446
24447   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24448                            no_class, &use_deprecated_index_sections, _("\
24449 Set whether to use deprecated gdb_index sections."), _("\
24450 Show whether to use deprecated gdb_index sections."), _("\
24451 When enabled, deprecated .gdb_index sections are used anyway.\n\
24452 Normally they are ignored either because of a missing feature or\n\
24453 performance issue.\n\
24454 Warning: This option must be enabled before gdb reads the file."),
24455                            NULL,
24456                            NULL,
24457                            &setlist, &showlist);
24458
24459   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24460                _("\
24461 Save a gdb-index file.\n\
24462 Usage: save gdb-index DIRECTORY"),
24463                &save_cmdlist);
24464   set_cmd_completer (c, filename_completer);
24465
24466   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24467                                                         &dwarf2_locexpr_funcs);
24468   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24469                                                         &dwarf2_loclist_funcs);
24470
24471   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24472                                         &dwarf2_block_frame_base_locexpr_funcs);
24473   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24474                                         &dwarf2_block_frame_base_loclist_funcs);
24475 }