DWARF-5: .debug_names index producer
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "filename-seen-cache.h"
78 #include "producer.h"
79 #include <fcntl.h>
80 #include <sys/types.h>
81 #include <algorithm>
82 #include <unordered_set>
83 #include <unordered_map>
84 #include "selftest.h"
85 #include <cmath>
86 #include <set>
87 #include <forward_list>
88
89 typedef struct symbol *symbolp;
90 DEF_VEC_P (symbolp);
91
92 /* When == 1, print basic high level tracing messages.
93    When > 1, be more verbose.
94    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
95 static unsigned int dwarf_read_debug = 0;
96
97 /* When non-zero, dump DIEs after they are read in.  */
98 static unsigned int dwarf_die_debug = 0;
99
100 /* When non-zero, dump line number entries as they are read in.  */
101 static unsigned int dwarf_line_debug = 0;
102
103 /* When non-zero, cross-check physname against demangler.  */
104 static int check_physname = 0;
105
106 /* When non-zero, do not reject deprecated .gdb_index sections.  */
107 static int use_deprecated_index_sections = 0;
108
109 static const struct objfile_data *dwarf2_objfile_data_key;
110
111 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
112
113 static int dwarf2_locexpr_index;
114 static int dwarf2_loclist_index;
115 static int dwarf2_locexpr_block_index;
116 static int dwarf2_loclist_block_index;
117
118 /* A descriptor for dwarf sections.
119
120    S.ASECTION, SIZE are typically initialized when the objfile is first
121    scanned.  BUFFER, READIN are filled in later when the section is read.
122    If the section contained compressed data then SIZE is updated to record
123    the uncompressed size of the section.
124
125    DWP file format V2 introduces a wrinkle that is easiest to handle by
126    creating the concept of virtual sections contained within a real section.
127    In DWP V2 the sections of the input DWO files are concatenated together
128    into one section, but section offsets are kept relative to the original
129    input section.
130    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
131    the real section this "virtual" section is contained in, and BUFFER,SIZE
132    describe the virtual section.  */
133
134 struct dwarf2_section_info
135 {
136   union
137   {
138     /* If this is a real section, the bfd section.  */
139     asection *section;
140     /* If this is a virtual section, pointer to the containing ("real")
141        section.  */
142     struct dwarf2_section_info *containing_section;
143   } s;
144   /* Pointer to section data, only valid if readin.  */
145   const gdb_byte *buffer;
146   /* The size of the section, real or virtual.  */
147   bfd_size_type size;
148   /* If this is a virtual section, the offset in the real section.
149      Only valid if is_virtual.  */
150   bfd_size_type virtual_offset;
151   /* True if we have tried to read this section.  */
152   char readin;
153   /* True if this is a virtual section, False otherwise.
154      This specifies which of s.section and s.containing_section to use.  */
155   char is_virtual;
156 };
157
158 typedef struct dwarf2_section_info dwarf2_section_info_def;
159 DEF_VEC_O (dwarf2_section_info_def);
160
161 /* All offsets in the index are of this type.  It must be
162    architecture-independent.  */
163 typedef uint32_t offset_type;
164
165 DEF_VEC_I (offset_type);
166
167 /* Ensure only legit values are used.  */
168 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
169   do { \
170     gdb_assert ((unsigned int) (value) <= 1); \
171     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
172   } while (0)
173
174 /* Ensure only legit values are used.  */
175 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
176   do { \
177     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
178                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
179     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
180   } while (0)
181
182 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
183 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
184   do { \
185     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
186     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
187   } while (0)
188
189 #if WORDS_BIGENDIAN
190
191 /* Convert VALUE between big- and little-endian.  */
192
193 static offset_type
194 byte_swap (offset_type value)
195 {
196   offset_type result;
197
198   result = (value & 0xff) << 24;
199   result |= (value & 0xff00) << 8;
200   result |= (value & 0xff0000) >> 8;
201   result |= (value & 0xff000000) >> 24;
202   return result;
203 }
204
205 #define MAYBE_SWAP(V)  byte_swap (V)
206
207 #else
208 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
209 #endif /* WORDS_BIGENDIAN */
210
211 /* An index into a (C++) symbol name component in a symbol name as
212    recorded in the mapped_index's symbol table.  For each C++ symbol
213    in the symbol table, we record one entry for the start of each
214    component in the symbol in a table of name components, and then
215    sort the table, in order to be able to binary search symbol names,
216    ignoring leading namespaces, both completion and regular look up.
217    For example, for symbol "A::B::C", we'll have an entry that points
218    to "A::B::C", another that points to "B::C", and another for "C".
219    Note that function symbols in GDB index have no parameter
220    information, just the function/method names.  You can convert a
221    name_component to a "const char *" using the
222    'mapped_index::symbol_name_at(offset_type)' method.  */
223
224 struct name_component
225 {
226   /* Offset in the symbol name where the component starts.  Stored as
227      a (32-bit) offset instead of a pointer to save memory and improve
228      locality on 64-bit architectures.  */
229   offset_type name_offset;
230
231   /* The symbol's index in the symbol and constant pool tables of a
232      mapped_index.  */
233   offset_type idx;
234 };
235
236 /* A description of the mapped index.  The file format is described in
237    a comment by the code that writes the index.  */
238 struct mapped_index
239 {
240   /* Index data format version.  */
241   int version;
242
243   /* The total length of the buffer.  */
244   off_t total_size;
245
246   /* A pointer to the address table data.  */
247   const gdb_byte *address_table;
248
249   /* Size of the address table data in bytes.  */
250   offset_type address_table_size;
251
252   /* The symbol table, implemented as a hash table.  */
253   const offset_type *symbol_table;
254
255   /* Size in slots, each slot is 2 offset_types.  */
256   offset_type symbol_table_slots;
257
258   /* A pointer to the constant pool.  */
259   const char *constant_pool;
260
261   /* The name_component table (a sorted vector).  See name_component's
262      description above.  */
263   std::vector<name_component> name_components;
264
265   /* How NAME_COMPONENTS is sorted.  */
266   enum case_sensitivity name_components_casing;
267
268   /* Convenience method to get at the name of the symbol at IDX in the
269      symbol table.  */
270   const char *symbol_name_at (offset_type idx) const
271   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
272
273   /* Build the symbol name component sorted vector, if we haven't
274      yet.  */
275   void build_name_components ();
276
277   /* Returns the lower (inclusive) and upper (exclusive) bounds of the
278      possible matches for LN_NO_PARAMS in the name component
279      vector.  */
280   std::pair<std::vector<name_component>::const_iterator,
281             std::vector<name_component>::const_iterator>
282     find_name_components_bounds (const lookup_name_info &ln_no_params) const;
283 };
284
285 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
286 DEF_VEC_P (dwarf2_per_cu_ptr);
287
288 struct tu_stats
289 {
290   int nr_uniq_abbrev_tables;
291   int nr_symtabs;
292   int nr_symtab_sharers;
293   int nr_stmt_less_type_units;
294   int nr_all_type_units_reallocs;
295 };
296
297 /* Collection of data recorded per objfile.
298    This hangs off of dwarf2_objfile_data_key.  */
299
300 struct dwarf2_per_objfile
301 {
302   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
303      dwarf2 section names, or is NULL if the standard ELF names are
304      used.  */
305   dwarf2_per_objfile (struct objfile *objfile,
306                       const dwarf2_debug_sections *names);
307
308   ~dwarf2_per_objfile ();
309
310   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
311
312   /* Free all cached compilation units.  */
313   void free_cached_comp_units ();
314 private:
315   /* This function is mapped across the sections and remembers the
316      offset and size of each of the debugging sections we are
317      interested in.  */
318   void locate_sections (bfd *abfd, asection *sectp,
319                         const dwarf2_debug_sections &names);
320
321 public:
322   dwarf2_section_info info {};
323   dwarf2_section_info abbrev {};
324   dwarf2_section_info line {};
325   dwarf2_section_info loc {};
326   dwarf2_section_info loclists {};
327   dwarf2_section_info macinfo {};
328   dwarf2_section_info macro {};
329   dwarf2_section_info str {};
330   dwarf2_section_info line_str {};
331   dwarf2_section_info ranges {};
332   dwarf2_section_info rnglists {};
333   dwarf2_section_info addr {};
334   dwarf2_section_info frame {};
335   dwarf2_section_info eh_frame {};
336   dwarf2_section_info gdb_index {};
337
338   VEC (dwarf2_section_info_def) *types = NULL;
339
340   /* Back link.  */
341   struct objfile *objfile = NULL;
342
343   /* Table of all the compilation units.  This is used to locate
344      the target compilation unit of a particular reference.  */
345   struct dwarf2_per_cu_data **all_comp_units = NULL;
346
347   /* The number of compilation units in ALL_COMP_UNITS.  */
348   int n_comp_units = 0;
349
350   /* The number of .debug_types-related CUs.  */
351   int n_type_units = 0;
352
353   /* The number of elements allocated in all_type_units.
354      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
355   int n_allocated_type_units = 0;
356
357   /* The .debug_types-related CUs (TUs).
358      This is stored in malloc space because we may realloc it.  */
359   struct signatured_type **all_type_units = NULL;
360
361   /* Table of struct type_unit_group objects.
362      The hash key is the DW_AT_stmt_list value.  */
363   htab_t type_unit_groups {};
364
365   /* A table mapping .debug_types signatures to its signatured_type entry.
366      This is NULL if the .debug_types section hasn't been read in yet.  */
367   htab_t signatured_types {};
368
369   /* Type unit statistics, to see how well the scaling improvements
370      are doing.  */
371   struct tu_stats tu_stats {};
372
373   /* A chain of compilation units that are currently read in, so that
374      they can be freed later.  */
375   dwarf2_per_cu_data *read_in_chain = NULL;
376
377   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
378      This is NULL if the table hasn't been allocated yet.  */
379   htab_t dwo_files {};
380
381   /* True if we've checked for whether there is a DWP file.  */
382   bool dwp_checked = false;
383
384   /* The DWP file if there is one, or NULL.  */
385   struct dwp_file *dwp_file = NULL;
386
387   /* The shared '.dwz' file, if one exists.  This is used when the
388      original data was compressed using 'dwz -m'.  */
389   struct dwz_file *dwz_file = NULL;
390
391   /* A flag indicating whether this objfile has a section loaded at a
392      VMA of 0.  */
393   bool has_section_at_zero = false;
394
395   /* True if we are using the mapped index,
396      or we are faking it for OBJF_READNOW's sake.  */
397   bool using_index = false;
398
399   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
400   mapped_index *index_table = NULL;
401
402   /* When using index_table, this keeps track of all quick_file_names entries.
403      TUs typically share line table entries with a CU, so we maintain a
404      separate table of all line table entries to support the sharing.
405      Note that while there can be way more TUs than CUs, we've already
406      sorted all the TUs into "type unit groups", grouped by their
407      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
408      CU and its associated TU group if there is one.  */
409   htab_t quick_file_names_table {};
410
411   /* Set during partial symbol reading, to prevent queueing of full
412      symbols.  */
413   bool reading_partial_symbols = false;
414
415   /* Table mapping type DIEs to their struct type *.
416      This is NULL if not allocated yet.
417      The mapping is done via (CU/TU + DIE offset) -> type.  */
418   htab_t die_type_hash {};
419
420   /* The CUs we recently read.  */
421   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
422
423   /* Table containing line_header indexed by offset and offset_in_dwz.  */
424   htab_t line_header_hash {};
425
426   /* Table containing all filenames.  This is an optional because the
427      table is lazily constructed on first access.  */
428   gdb::optional<filename_seen_cache> filenames_cache;
429 };
430
431 static struct dwarf2_per_objfile *dwarf2_per_objfile;
432
433 /* Default names of the debugging sections.  */
434
435 /* Note that if the debugging section has been compressed, it might
436    have a name like .zdebug_info.  */
437
438 static const struct dwarf2_debug_sections dwarf2_elf_names =
439 {
440   { ".debug_info", ".zdebug_info" },
441   { ".debug_abbrev", ".zdebug_abbrev" },
442   { ".debug_line", ".zdebug_line" },
443   { ".debug_loc", ".zdebug_loc" },
444   { ".debug_loclists", ".zdebug_loclists" },
445   { ".debug_macinfo", ".zdebug_macinfo" },
446   { ".debug_macro", ".zdebug_macro" },
447   { ".debug_str", ".zdebug_str" },
448   { ".debug_line_str", ".zdebug_line_str" },
449   { ".debug_ranges", ".zdebug_ranges" },
450   { ".debug_rnglists", ".zdebug_rnglists" },
451   { ".debug_types", ".zdebug_types" },
452   { ".debug_addr", ".zdebug_addr" },
453   { ".debug_frame", ".zdebug_frame" },
454   { ".eh_frame", NULL },
455   { ".gdb_index", ".zgdb_index" },
456   23
457 };
458
459 /* List of DWO/DWP sections.  */
460
461 static const struct dwop_section_names
462 {
463   struct dwarf2_section_names abbrev_dwo;
464   struct dwarf2_section_names info_dwo;
465   struct dwarf2_section_names line_dwo;
466   struct dwarf2_section_names loc_dwo;
467   struct dwarf2_section_names loclists_dwo;
468   struct dwarf2_section_names macinfo_dwo;
469   struct dwarf2_section_names macro_dwo;
470   struct dwarf2_section_names str_dwo;
471   struct dwarf2_section_names str_offsets_dwo;
472   struct dwarf2_section_names types_dwo;
473   struct dwarf2_section_names cu_index;
474   struct dwarf2_section_names tu_index;
475 }
476 dwop_section_names =
477 {
478   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
479   { ".debug_info.dwo", ".zdebug_info.dwo" },
480   { ".debug_line.dwo", ".zdebug_line.dwo" },
481   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
482   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
483   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
484   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
485   { ".debug_str.dwo", ".zdebug_str.dwo" },
486   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
487   { ".debug_types.dwo", ".zdebug_types.dwo" },
488   { ".debug_cu_index", ".zdebug_cu_index" },
489   { ".debug_tu_index", ".zdebug_tu_index" },
490 };
491
492 /* local data types */
493
494 /* The data in a compilation unit header, after target2host
495    translation, looks like this.  */
496 struct comp_unit_head
497 {
498   unsigned int length;
499   short version;
500   unsigned char addr_size;
501   unsigned char signed_addr_p;
502   sect_offset abbrev_sect_off;
503
504   /* Size of file offsets; either 4 or 8.  */
505   unsigned int offset_size;
506
507   /* Size of the length field; either 4 or 12.  */
508   unsigned int initial_length_size;
509
510   enum dwarf_unit_type unit_type;
511
512   /* Offset to the first byte of this compilation unit header in the
513      .debug_info section, for resolving relative reference dies.  */
514   sect_offset sect_off;
515
516   /* Offset to first die in this cu from the start of the cu.
517      This will be the first byte following the compilation unit header.  */
518   cu_offset first_die_cu_offset;
519
520   /* 64-bit signature of this type unit - it is valid only for
521      UNIT_TYPE DW_UT_type.  */
522   ULONGEST signature;
523
524   /* For types, offset in the type's DIE of the type defined by this TU.  */
525   cu_offset type_cu_offset_in_tu;
526 };
527
528 /* Type used for delaying computation of method physnames.
529    See comments for compute_delayed_physnames.  */
530 struct delayed_method_info
531 {
532   /* The type to which the method is attached, i.e., its parent class.  */
533   struct type *type;
534
535   /* The index of the method in the type's function fieldlists.  */
536   int fnfield_index;
537
538   /* The index of the method in the fieldlist.  */
539   int index;
540
541   /* The name of the DIE.  */
542   const char *name;
543
544   /*  The DIE associated with this method.  */
545   struct die_info *die;
546 };
547
548 typedef struct delayed_method_info delayed_method_info;
549 DEF_VEC_O (delayed_method_info);
550
551 /* Internal state when decoding a particular compilation unit.  */
552 struct dwarf2_cu
553 {
554   /* The objfile containing this compilation unit.  */
555   struct objfile *objfile;
556
557   /* The header of the compilation unit.  */
558   struct comp_unit_head header;
559
560   /* Base address of this compilation unit.  */
561   CORE_ADDR base_address;
562
563   /* Non-zero if base_address has been set.  */
564   int base_known;
565
566   /* The language we are debugging.  */
567   enum language language;
568   const struct language_defn *language_defn;
569
570   const char *producer;
571
572   /* The generic symbol table building routines have separate lists for
573      file scope symbols and all all other scopes (local scopes).  So
574      we need to select the right one to pass to add_symbol_to_list().
575      We do it by keeping a pointer to the correct list in list_in_scope.
576
577      FIXME: The original dwarf code just treated the file scope as the
578      first local scope, and all other local scopes as nested local
579      scopes, and worked fine.  Check to see if we really need to
580      distinguish these in buildsym.c.  */
581   struct pending **list_in_scope;
582
583   /* The abbrev table for this CU.
584      Normally this points to the abbrev table in the objfile.
585      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
586   struct abbrev_table *abbrev_table;
587
588   /* Hash table holding all the loaded partial DIEs
589      with partial_die->offset.SECT_OFF as hash.  */
590   htab_t partial_dies;
591
592   /* Storage for things with the same lifetime as this read-in compilation
593      unit, including partial DIEs.  */
594   struct obstack comp_unit_obstack;
595
596   /* When multiple dwarf2_cu structures are living in memory, this field
597      chains them all together, so that they can be released efficiently.
598      We will probably also want a generation counter so that most-recently-used
599      compilation units are cached...  */
600   struct dwarf2_per_cu_data *read_in_chain;
601
602   /* Backlink to our per_cu entry.  */
603   struct dwarf2_per_cu_data *per_cu;
604
605   /* How many compilation units ago was this CU last referenced?  */
606   int last_used;
607
608   /* A hash table of DIE cu_offset for following references with
609      die_info->offset.sect_off as hash.  */
610   htab_t die_hash;
611
612   /* Full DIEs if read in.  */
613   struct die_info *dies;
614
615   /* A set of pointers to dwarf2_per_cu_data objects for compilation
616      units referenced by this one.  Only set during full symbol processing;
617      partial symbol tables do not have dependencies.  */
618   htab_t dependencies;
619
620   /* Header data from the line table, during full symbol processing.  */
621   struct line_header *line_header;
622   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
623      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
624      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
625      to the line header as long as this DIE is being processed.  See
626      process_die_scope.  */
627   die_info *line_header_die_owner;
628
629   /* A list of methods which need to have physnames computed
630      after all type information has been read.  */
631   VEC (delayed_method_info) *method_list;
632
633   /* To be copied to symtab->call_site_htab.  */
634   htab_t call_site_htab;
635
636   /* Non-NULL if this CU came from a DWO file.
637      There is an invariant here that is important to remember:
638      Except for attributes copied from the top level DIE in the "main"
639      (or "stub") file in preparation for reading the DWO file
640      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
641      Either there isn't a DWO file (in which case this is NULL and the point
642      is moot), or there is and either we're not going to read it (in which
643      case this is NULL) or there is and we are reading it (in which case this
644      is non-NULL).  */
645   struct dwo_unit *dwo_unit;
646
647   /* The DW_AT_addr_base attribute if present, zero otherwise
648      (zero is a valid value though).
649      Note this value comes from the Fission stub CU/TU's DIE.  */
650   ULONGEST addr_base;
651
652   /* The DW_AT_ranges_base attribute if present, zero otherwise
653      (zero is a valid value though).
654      Note this value comes from the Fission stub CU/TU's DIE.
655      Also note that the value is zero in the non-DWO case so this value can
656      be used without needing to know whether DWO files are in use or not.
657      N.B. This does not apply to DW_AT_ranges appearing in
658      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
659      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
660      DW_AT_ranges_base *would* have to be applied, and we'd have to care
661      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
662   ULONGEST ranges_base;
663
664   /* Mark used when releasing cached dies.  */
665   unsigned int mark : 1;
666
667   /* This CU references .debug_loc.  See the symtab->locations_valid field.
668      This test is imperfect as there may exist optimized debug code not using
669      any location list and still facing inlining issues if handled as
670      unoptimized code.  For a future better test see GCC PR other/32998.  */
671   unsigned int has_loclist : 1;
672
673   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
674      if all the producer_is_* fields are valid.  This information is cached
675      because profiling CU expansion showed excessive time spent in
676      producer_is_gxx_lt_4_6.  */
677   unsigned int checked_producer : 1;
678   unsigned int producer_is_gxx_lt_4_6 : 1;
679   unsigned int producer_is_gcc_lt_4_3 : 1;
680   unsigned int producer_is_icc_lt_14 : 1;
681
682   /* When set, the file that we're processing is known to have
683      debugging info for C++ namespaces.  GCC 3.3.x did not produce
684      this information, but later versions do.  */
685
686   unsigned int processing_has_namespace_info : 1;
687 };
688
689 /* Persistent data held for a compilation unit, even when not
690    processing it.  We put a pointer to this structure in the
691    read_symtab_private field of the psymtab.  */
692
693 struct dwarf2_per_cu_data
694 {
695   /* The start offset and length of this compilation unit.
696      NOTE: Unlike comp_unit_head.length, this length includes
697      initial_length_size.
698      If the DIE refers to a DWO file, this is always of the original die,
699      not the DWO file.  */
700   sect_offset sect_off;
701   unsigned int length;
702
703   /* DWARF standard version this data has been read from (such as 4 or 5).  */
704   short dwarf_version;
705
706   /* Flag indicating this compilation unit will be read in before
707      any of the current compilation units are processed.  */
708   unsigned int queued : 1;
709
710   /* This flag will be set when reading partial DIEs if we need to load
711      absolutely all DIEs for this compilation unit, instead of just the ones
712      we think are interesting.  It gets set if we look for a DIE in the
713      hash table and don't find it.  */
714   unsigned int load_all_dies : 1;
715
716   /* Non-zero if this CU is from .debug_types.
717      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
718      this is non-zero.  */
719   unsigned int is_debug_types : 1;
720
721   /* Non-zero if this CU is from the .dwz file.  */
722   unsigned int is_dwz : 1;
723
724   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
725      This flag is only valid if is_debug_types is true.
726      We can't read a CU directly from a DWO file: There are required
727      attributes in the stub.  */
728   unsigned int reading_dwo_directly : 1;
729
730   /* Non-zero if the TU has been read.
731      This is used to assist the "Stay in DWO Optimization" for Fission:
732      When reading a DWO, it's faster to read TUs from the DWO instead of
733      fetching them from random other DWOs (due to comdat folding).
734      If the TU has already been read, the optimization is unnecessary
735      (and unwise - we don't want to change where gdb thinks the TU lives
736      "midflight").
737      This flag is only valid if is_debug_types is true.  */
738   unsigned int tu_read : 1;
739
740   /* The section this CU/TU lives in.
741      If the DIE refers to a DWO file, this is always the original die,
742      not the DWO file.  */
743   struct dwarf2_section_info *section;
744
745   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
746      of the CU cache it gets reset to NULL again.  This is left as NULL for
747      dummy CUs (a CU header, but nothing else).  */
748   struct dwarf2_cu *cu;
749
750   /* The corresponding objfile.
751      Normally we can get the objfile from dwarf2_per_objfile.
752      However we can enter this file with just a "per_cu" handle.  */
753   struct objfile *objfile;
754
755   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
756      is active.  Otherwise, the 'psymtab' field is active.  */
757   union
758   {
759     /* The partial symbol table associated with this compilation unit,
760        or NULL for unread partial units.  */
761     struct partial_symtab *psymtab;
762
763     /* Data needed by the "quick" functions.  */
764     struct dwarf2_per_cu_quick_data *quick;
765   } v;
766
767   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
768      while reading psymtabs, used to compute the psymtab dependencies,
769      and then cleared.  Then it is filled in again while reading full
770      symbols, and only deleted when the objfile is destroyed.
771
772      This is also used to work around a difference between the way gold
773      generates .gdb_index version <=7 and the way gdb does.  Arguably this
774      is a gold bug.  For symbols coming from TUs, gold records in the index
775      the CU that includes the TU instead of the TU itself.  This breaks
776      dw2_lookup_symbol: It assumes that if the index says symbol X lives
777      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
778      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
779      we need to look in TU Z to find X.  Fortunately, this is akin to
780      DW_TAG_imported_unit, so we just use the same mechanism: For
781      .gdb_index version <=7 this also records the TUs that the CU referred
782      to.  Concurrently with this change gdb was modified to emit version 8
783      indices so we only pay a price for gold generated indices.
784      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
785   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
786 };
787
788 /* Entry in the signatured_types hash table.  */
789
790 struct signatured_type
791 {
792   /* The "per_cu" object of this type.
793      This struct is used iff per_cu.is_debug_types.
794      N.B.: This is the first member so that it's easy to convert pointers
795      between them.  */
796   struct dwarf2_per_cu_data per_cu;
797
798   /* The type's signature.  */
799   ULONGEST signature;
800
801   /* Offset in the TU of the type's DIE, as read from the TU header.
802      If this TU is a DWO stub and the definition lives in a DWO file
803      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
804   cu_offset type_offset_in_tu;
805
806   /* Offset in the section of the type's DIE.
807      If the definition lives in a DWO file, this is the offset in the
808      .debug_types.dwo section.
809      The value is zero until the actual value is known.
810      Zero is otherwise not a valid section offset.  */
811   sect_offset type_offset_in_section;
812
813   /* Type units are grouped by their DW_AT_stmt_list entry so that they
814      can share them.  This points to the containing symtab.  */
815   struct type_unit_group *type_unit_group;
816
817   /* The type.
818      The first time we encounter this type we fully read it in and install it
819      in the symbol tables.  Subsequent times we only need the type.  */
820   struct type *type;
821
822   /* Containing DWO unit.
823      This field is valid iff per_cu.reading_dwo_directly.  */
824   struct dwo_unit *dwo_unit;
825 };
826
827 typedef struct signatured_type *sig_type_ptr;
828 DEF_VEC_P (sig_type_ptr);
829
830 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
831    This includes type_unit_group and quick_file_names.  */
832
833 struct stmt_list_hash
834 {
835   /* The DWO unit this table is from or NULL if there is none.  */
836   struct dwo_unit *dwo_unit;
837
838   /* Offset in .debug_line or .debug_line.dwo.  */
839   sect_offset line_sect_off;
840 };
841
842 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
843    an object of this type.  */
844
845 struct type_unit_group
846 {
847   /* dwarf2read.c's main "handle" on a TU symtab.
848      To simplify things we create an artificial CU that "includes" all the
849      type units using this stmt_list so that the rest of the code still has
850      a "per_cu" handle on the symtab.
851      This PER_CU is recognized by having no section.  */
852 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
853   struct dwarf2_per_cu_data per_cu;
854
855   /* The TUs that share this DW_AT_stmt_list entry.
856      This is added to while parsing type units to build partial symtabs,
857      and is deleted afterwards and not used again.  */
858   VEC (sig_type_ptr) *tus;
859
860   /* The compunit symtab.
861      Type units in a group needn't all be defined in the same source file,
862      so we create an essentially anonymous symtab as the compunit symtab.  */
863   struct compunit_symtab *compunit_symtab;
864
865   /* The data used to construct the hash key.  */
866   struct stmt_list_hash hash;
867
868   /* The number of symtabs from the line header.
869      The value here must match line_header.num_file_names.  */
870   unsigned int num_symtabs;
871
872   /* The symbol tables for this TU (obtained from the files listed in
873      DW_AT_stmt_list).
874      WARNING: The order of entries here must match the order of entries
875      in the line header.  After the first TU using this type_unit_group, the
876      line header for the subsequent TUs is recreated from this.  This is done
877      because we need to use the same symtabs for each TU using the same
878      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
879      there's no guarantee the line header doesn't have duplicate entries.  */
880   struct symtab **symtabs;
881 };
882
883 /* These sections are what may appear in a (real or virtual) DWO file.  */
884
885 struct dwo_sections
886 {
887   struct dwarf2_section_info abbrev;
888   struct dwarf2_section_info line;
889   struct dwarf2_section_info loc;
890   struct dwarf2_section_info loclists;
891   struct dwarf2_section_info macinfo;
892   struct dwarf2_section_info macro;
893   struct dwarf2_section_info str;
894   struct dwarf2_section_info str_offsets;
895   /* In the case of a virtual DWO file, these two are unused.  */
896   struct dwarf2_section_info info;
897   VEC (dwarf2_section_info_def) *types;
898 };
899
900 /* CUs/TUs in DWP/DWO files.  */
901
902 struct dwo_unit
903 {
904   /* Backlink to the containing struct dwo_file.  */
905   struct dwo_file *dwo_file;
906
907   /* The "id" that distinguishes this CU/TU.
908      .debug_info calls this "dwo_id", .debug_types calls this "signature".
909      Since signatures came first, we stick with it for consistency.  */
910   ULONGEST signature;
911
912   /* The section this CU/TU lives in, in the DWO file.  */
913   struct dwarf2_section_info *section;
914
915   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
916   sect_offset sect_off;
917   unsigned int length;
918
919   /* For types, offset in the type's DIE of the type defined by this TU.  */
920   cu_offset type_offset_in_tu;
921 };
922
923 /* include/dwarf2.h defines the DWP section codes.
924    It defines a max value but it doesn't define a min value, which we
925    use for error checking, so provide one.  */
926
927 enum dwp_v2_section_ids
928 {
929   DW_SECT_MIN = 1
930 };
931
932 /* Data for one DWO file.
933
934    This includes virtual DWO files (a virtual DWO file is a DWO file as it
935    appears in a DWP file).  DWP files don't really have DWO files per se -
936    comdat folding of types "loses" the DWO file they came from, and from
937    a high level view DWP files appear to contain a mass of random types.
938    However, to maintain consistency with the non-DWP case we pretend DWP
939    files contain virtual DWO files, and we assign each TU with one virtual
940    DWO file (generally based on the line and abbrev section offsets -
941    a heuristic that seems to work in practice).  */
942
943 struct dwo_file
944 {
945   /* The DW_AT_GNU_dwo_name attribute.
946      For virtual DWO files the name is constructed from the section offsets
947      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
948      from related CU+TUs.  */
949   const char *dwo_name;
950
951   /* The DW_AT_comp_dir attribute.  */
952   const char *comp_dir;
953
954   /* The bfd, when the file is open.  Otherwise this is NULL.
955      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
956   bfd *dbfd;
957
958   /* The sections that make up this DWO file.
959      Remember that for virtual DWO files in DWP V2, these are virtual
960      sections (for lack of a better name).  */
961   struct dwo_sections sections;
962
963   /* The CUs in the file.
964      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
965      an extension to handle LLVM's Link Time Optimization output (where
966      multiple source files may be compiled into a single object/dwo pair). */
967   htab_t cus;
968
969   /* Table of TUs in the file.
970      Each element is a struct dwo_unit.  */
971   htab_t tus;
972 };
973
974 /* These sections are what may appear in a DWP file.  */
975
976 struct dwp_sections
977 {
978   /* These are used by both DWP version 1 and 2.  */
979   struct dwarf2_section_info str;
980   struct dwarf2_section_info cu_index;
981   struct dwarf2_section_info tu_index;
982
983   /* These are only used by DWP version 2 files.
984      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
985      sections are referenced by section number, and are not recorded here.
986      In DWP version 2 there is at most one copy of all these sections, each
987      section being (effectively) comprised of the concatenation of all of the
988      individual sections that exist in the version 1 format.
989      To keep the code simple we treat each of these concatenated pieces as a
990      section itself (a virtual section?).  */
991   struct dwarf2_section_info abbrev;
992   struct dwarf2_section_info info;
993   struct dwarf2_section_info line;
994   struct dwarf2_section_info loc;
995   struct dwarf2_section_info macinfo;
996   struct dwarf2_section_info macro;
997   struct dwarf2_section_info str_offsets;
998   struct dwarf2_section_info types;
999 };
1000
1001 /* These sections are what may appear in a virtual DWO file in DWP version 1.
1002    A virtual DWO file is a DWO file as it appears in a DWP file.  */
1003
1004 struct virtual_v1_dwo_sections
1005 {
1006   struct dwarf2_section_info abbrev;
1007   struct dwarf2_section_info line;
1008   struct dwarf2_section_info loc;
1009   struct dwarf2_section_info macinfo;
1010   struct dwarf2_section_info macro;
1011   struct dwarf2_section_info str_offsets;
1012   /* Each DWP hash table entry records one CU or one TU.
1013      That is recorded here, and copied to dwo_unit.section.  */
1014   struct dwarf2_section_info info_or_types;
1015 };
1016
1017 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1018    In version 2, the sections of the DWO files are concatenated together
1019    and stored in one section of that name.  Thus each ELF section contains
1020    several "virtual" sections.  */
1021
1022 struct virtual_v2_dwo_sections
1023 {
1024   bfd_size_type abbrev_offset;
1025   bfd_size_type abbrev_size;
1026
1027   bfd_size_type line_offset;
1028   bfd_size_type line_size;
1029
1030   bfd_size_type loc_offset;
1031   bfd_size_type loc_size;
1032
1033   bfd_size_type macinfo_offset;
1034   bfd_size_type macinfo_size;
1035
1036   bfd_size_type macro_offset;
1037   bfd_size_type macro_size;
1038
1039   bfd_size_type str_offsets_offset;
1040   bfd_size_type str_offsets_size;
1041
1042   /* Each DWP hash table entry records one CU or one TU.
1043      That is recorded here, and copied to dwo_unit.section.  */
1044   bfd_size_type info_or_types_offset;
1045   bfd_size_type info_or_types_size;
1046 };
1047
1048 /* Contents of DWP hash tables.  */
1049
1050 struct dwp_hash_table
1051 {
1052   uint32_t version, nr_columns;
1053   uint32_t nr_units, nr_slots;
1054   const gdb_byte *hash_table, *unit_table;
1055   union
1056   {
1057     struct
1058     {
1059       const gdb_byte *indices;
1060     } v1;
1061     struct
1062     {
1063       /* This is indexed by column number and gives the id of the section
1064          in that column.  */
1065 #define MAX_NR_V2_DWO_SECTIONS \
1066   (1 /* .debug_info or .debug_types */ \
1067    + 1 /* .debug_abbrev */ \
1068    + 1 /* .debug_line */ \
1069    + 1 /* .debug_loc */ \
1070    + 1 /* .debug_str_offsets */ \
1071    + 1 /* .debug_macro or .debug_macinfo */)
1072       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1073       const gdb_byte *offsets;
1074       const gdb_byte *sizes;
1075     } v2;
1076   } section_pool;
1077 };
1078
1079 /* Data for one DWP file.  */
1080
1081 struct dwp_file
1082 {
1083   /* Name of the file.  */
1084   const char *name;
1085
1086   /* File format version.  */
1087   int version;
1088
1089   /* The bfd.  */
1090   bfd *dbfd;
1091
1092   /* Section info for this file.  */
1093   struct dwp_sections sections;
1094
1095   /* Table of CUs in the file.  */
1096   const struct dwp_hash_table *cus;
1097
1098   /* Table of TUs in the file.  */
1099   const struct dwp_hash_table *tus;
1100
1101   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1102   htab_t loaded_cus;
1103   htab_t loaded_tus;
1104
1105   /* Table to map ELF section numbers to their sections.
1106      This is only needed for the DWP V1 file format.  */
1107   unsigned int num_sections;
1108   asection **elf_sections;
1109 };
1110
1111 /* This represents a '.dwz' file.  */
1112
1113 struct dwz_file
1114 {
1115   /* A dwz file can only contain a few sections.  */
1116   struct dwarf2_section_info abbrev;
1117   struct dwarf2_section_info info;
1118   struct dwarf2_section_info str;
1119   struct dwarf2_section_info line;
1120   struct dwarf2_section_info macro;
1121   struct dwarf2_section_info gdb_index;
1122
1123   /* The dwz's BFD.  */
1124   bfd *dwz_bfd;
1125 };
1126
1127 /* Struct used to pass misc. parameters to read_die_and_children, et
1128    al.  which are used for both .debug_info and .debug_types dies.
1129    All parameters here are unchanging for the life of the call.  This
1130    struct exists to abstract away the constant parameters of die reading.  */
1131
1132 struct die_reader_specs
1133 {
1134   /* The bfd of die_section.  */
1135   bfd* abfd;
1136
1137   /* The CU of the DIE we are parsing.  */
1138   struct dwarf2_cu *cu;
1139
1140   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1141   struct dwo_file *dwo_file;
1142
1143   /* The section the die comes from.
1144      This is either .debug_info or .debug_types, or the .dwo variants.  */
1145   struct dwarf2_section_info *die_section;
1146
1147   /* die_section->buffer.  */
1148   const gdb_byte *buffer;
1149
1150   /* The end of the buffer.  */
1151   const gdb_byte *buffer_end;
1152
1153   /* The value of the DW_AT_comp_dir attribute.  */
1154   const char *comp_dir;
1155 };
1156
1157 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1158 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1159                                       const gdb_byte *info_ptr,
1160                                       struct die_info *comp_unit_die,
1161                                       int has_children,
1162                                       void *data);
1163
1164 /* A 1-based directory index.  This is a strong typedef to prevent
1165    accidentally using a directory index as a 0-based index into an
1166    array/vector.  */
1167 enum class dir_index : unsigned int {};
1168
1169 /* Likewise, a 1-based file name index.  */
1170 enum class file_name_index : unsigned int {};
1171
1172 struct file_entry
1173 {
1174   file_entry () = default;
1175
1176   file_entry (const char *name_, dir_index d_index_,
1177               unsigned int mod_time_, unsigned int length_)
1178     : name (name_),
1179       d_index (d_index_),
1180       mod_time (mod_time_),
1181       length (length_)
1182   {}
1183
1184   /* Return the include directory at D_INDEX stored in LH.  Returns
1185      NULL if D_INDEX is out of bounds.  */
1186   const char *include_dir (const line_header *lh) const;
1187
1188   /* The file name.  Note this is an observing pointer.  The memory is
1189      owned by debug_line_buffer.  */
1190   const char *name {};
1191
1192   /* The directory index (1-based).  */
1193   dir_index d_index {};
1194
1195   unsigned int mod_time {};
1196
1197   unsigned int length {};
1198
1199   /* True if referenced by the Line Number Program.  */
1200   bool included_p {};
1201
1202   /* The associated symbol table, if any.  */
1203   struct symtab *symtab {};
1204 };
1205
1206 /* The line number information for a compilation unit (found in the
1207    .debug_line section) begins with a "statement program header",
1208    which contains the following information.  */
1209 struct line_header
1210 {
1211   line_header ()
1212     : offset_in_dwz {}
1213   {}
1214
1215   /* Add an entry to the include directory table.  */
1216   void add_include_dir (const char *include_dir);
1217
1218   /* Add an entry to the file name table.  */
1219   void add_file_name (const char *name, dir_index d_index,
1220                       unsigned int mod_time, unsigned int length);
1221
1222   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1223      is out of bounds.  */
1224   const char *include_dir_at (dir_index index) const
1225   {
1226     /* Convert directory index number (1-based) to vector index
1227        (0-based).  */
1228     size_t vec_index = to_underlying (index) - 1;
1229
1230     if (vec_index >= include_dirs.size ())
1231       return NULL;
1232     return include_dirs[vec_index];
1233   }
1234
1235   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1236      is out of bounds.  */
1237   file_entry *file_name_at (file_name_index index)
1238   {
1239     /* Convert file name index number (1-based) to vector index
1240        (0-based).  */
1241     size_t vec_index = to_underlying (index) - 1;
1242
1243     if (vec_index >= file_names.size ())
1244       return NULL;
1245     return &file_names[vec_index];
1246   }
1247
1248   /* Const version of the above.  */
1249   const file_entry *file_name_at (unsigned int index) const
1250   {
1251     if (index >= file_names.size ())
1252       return NULL;
1253     return &file_names[index];
1254   }
1255
1256   /* Offset of line number information in .debug_line section.  */
1257   sect_offset sect_off {};
1258
1259   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1260   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1261
1262   unsigned int total_length {};
1263   unsigned short version {};
1264   unsigned int header_length {};
1265   unsigned char minimum_instruction_length {};
1266   unsigned char maximum_ops_per_instruction {};
1267   unsigned char default_is_stmt {};
1268   int line_base {};
1269   unsigned char line_range {};
1270   unsigned char opcode_base {};
1271
1272   /* standard_opcode_lengths[i] is the number of operands for the
1273      standard opcode whose value is i.  This means that
1274      standard_opcode_lengths[0] is unused, and the last meaningful
1275      element is standard_opcode_lengths[opcode_base - 1].  */
1276   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1277
1278   /* The include_directories table.  Note these are observing
1279      pointers.  The memory is owned by debug_line_buffer.  */
1280   std::vector<const char *> include_dirs;
1281
1282   /* The file_names table.  */
1283   std::vector<file_entry> file_names;
1284
1285   /* The start and end of the statement program following this
1286      header.  These point into dwarf2_per_objfile->line_buffer.  */
1287   const gdb_byte *statement_program_start {}, *statement_program_end {};
1288 };
1289
1290 typedef std::unique_ptr<line_header> line_header_up;
1291
1292 const char *
1293 file_entry::include_dir (const line_header *lh) const
1294 {
1295   return lh->include_dir_at (d_index);
1296 }
1297
1298 /* When we construct a partial symbol table entry we only
1299    need this much information.  */
1300 struct partial_die_info
1301   {
1302     /* Offset of this DIE.  */
1303     sect_offset sect_off;
1304
1305     /* DWARF-2 tag for this DIE.  */
1306     ENUM_BITFIELD(dwarf_tag) tag : 16;
1307
1308     /* Assorted flags describing the data found in this DIE.  */
1309     unsigned int has_children : 1;
1310     unsigned int is_external : 1;
1311     unsigned int is_declaration : 1;
1312     unsigned int has_type : 1;
1313     unsigned int has_specification : 1;
1314     unsigned int has_pc_info : 1;
1315     unsigned int may_be_inlined : 1;
1316
1317     /* This DIE has been marked DW_AT_main_subprogram.  */
1318     unsigned int main_subprogram : 1;
1319
1320     /* Flag set if the SCOPE field of this structure has been
1321        computed.  */
1322     unsigned int scope_set : 1;
1323
1324     /* Flag set if the DIE has a byte_size attribute.  */
1325     unsigned int has_byte_size : 1;
1326
1327     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1328     unsigned int has_const_value : 1;
1329
1330     /* Flag set if any of the DIE's children are template arguments.  */
1331     unsigned int has_template_arguments : 1;
1332
1333     /* Flag set if fixup_partial_die has been called on this die.  */
1334     unsigned int fixup_called : 1;
1335
1336     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1337     unsigned int is_dwz : 1;
1338
1339     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1340     unsigned int spec_is_dwz : 1;
1341
1342     /* The name of this DIE.  Normally the value of DW_AT_name, but
1343        sometimes a default name for unnamed DIEs.  */
1344     const char *name;
1345
1346     /* The linkage name, if present.  */
1347     const char *linkage_name;
1348
1349     /* The scope to prepend to our children.  This is generally
1350        allocated on the comp_unit_obstack, so will disappear
1351        when this compilation unit leaves the cache.  */
1352     const char *scope;
1353
1354     /* Some data associated with the partial DIE.  The tag determines
1355        which field is live.  */
1356     union
1357     {
1358       /* The location description associated with this DIE, if any.  */
1359       struct dwarf_block *locdesc;
1360       /* The offset of an import, for DW_TAG_imported_unit.  */
1361       sect_offset sect_off;
1362     } d;
1363
1364     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1365     CORE_ADDR lowpc;
1366     CORE_ADDR highpc;
1367
1368     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1369        DW_AT_sibling, if any.  */
1370     /* NOTE: This member isn't strictly necessary, read_partial_die could
1371        return DW_AT_sibling values to its caller load_partial_dies.  */
1372     const gdb_byte *sibling;
1373
1374     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1375        DW_AT_specification (or DW_AT_abstract_origin or
1376        DW_AT_extension).  */
1377     sect_offset spec_offset;
1378
1379     /* Pointers to this DIE's parent, first child, and next sibling,
1380        if any.  */
1381     struct partial_die_info *die_parent, *die_child, *die_sibling;
1382   };
1383
1384 /* This data structure holds the information of an abbrev.  */
1385 struct abbrev_info
1386   {
1387     unsigned int number;        /* number identifying abbrev */
1388     enum dwarf_tag tag;         /* dwarf tag */
1389     unsigned short has_children;                /* boolean */
1390     unsigned short num_attrs;   /* number of attributes */
1391     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1392     struct abbrev_info *next;   /* next in chain */
1393   };
1394
1395 struct attr_abbrev
1396   {
1397     ENUM_BITFIELD(dwarf_attribute) name : 16;
1398     ENUM_BITFIELD(dwarf_form) form : 16;
1399
1400     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1401     LONGEST implicit_const;
1402   };
1403
1404 /* Size of abbrev_table.abbrev_hash_table.  */
1405 #define ABBREV_HASH_SIZE 121
1406
1407 /* Top level data structure to contain an abbreviation table.  */
1408
1409 struct abbrev_table
1410 {
1411   /* Where the abbrev table came from.
1412      This is used as a sanity check when the table is used.  */
1413   sect_offset sect_off;
1414
1415   /* Storage for the abbrev table.  */
1416   struct obstack abbrev_obstack;
1417
1418   /* Hash table of abbrevs.
1419      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1420      It could be statically allocated, but the previous code didn't so we
1421      don't either.  */
1422   struct abbrev_info **abbrevs;
1423 };
1424
1425 /* Attributes have a name and a value.  */
1426 struct attribute
1427   {
1428     ENUM_BITFIELD(dwarf_attribute) name : 16;
1429     ENUM_BITFIELD(dwarf_form) form : 15;
1430
1431     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1432        field should be in u.str (existing only for DW_STRING) but it is kept
1433        here for better struct attribute alignment.  */
1434     unsigned int string_is_canonical : 1;
1435
1436     union
1437       {
1438         const char *str;
1439         struct dwarf_block *blk;
1440         ULONGEST unsnd;
1441         LONGEST snd;
1442         CORE_ADDR addr;
1443         ULONGEST signature;
1444       }
1445     u;
1446   };
1447
1448 /* This data structure holds a complete die structure.  */
1449 struct die_info
1450   {
1451     /* DWARF-2 tag for this DIE.  */
1452     ENUM_BITFIELD(dwarf_tag) tag : 16;
1453
1454     /* Number of attributes */
1455     unsigned char num_attrs;
1456
1457     /* True if we're presently building the full type name for the
1458        type derived from this DIE.  */
1459     unsigned char building_fullname : 1;
1460
1461     /* True if this die is in process.  PR 16581.  */
1462     unsigned char in_process : 1;
1463
1464     /* Abbrev number */
1465     unsigned int abbrev;
1466
1467     /* Offset in .debug_info or .debug_types section.  */
1468     sect_offset sect_off;
1469
1470     /* The dies in a compilation unit form an n-ary tree.  PARENT
1471        points to this die's parent; CHILD points to the first child of
1472        this node; and all the children of a given node are chained
1473        together via their SIBLING fields.  */
1474     struct die_info *child;     /* Its first child, if any.  */
1475     struct die_info *sibling;   /* Its next sibling, if any.  */
1476     struct die_info *parent;    /* Its parent, if any.  */
1477
1478     /* An array of attributes, with NUM_ATTRS elements.  There may be
1479        zero, but it's not common and zero-sized arrays are not
1480        sufficiently portable C.  */
1481     struct attribute attrs[1];
1482   };
1483
1484 /* Get at parts of an attribute structure.  */
1485
1486 #define DW_STRING(attr)    ((attr)->u.str)
1487 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1488 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1489 #define DW_BLOCK(attr)     ((attr)->u.blk)
1490 #define DW_SND(attr)       ((attr)->u.snd)
1491 #define DW_ADDR(attr)      ((attr)->u.addr)
1492 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1493
1494 /* Blocks are a bunch of untyped bytes.  */
1495 struct dwarf_block
1496   {
1497     size_t size;
1498
1499     /* Valid only if SIZE is not zero.  */
1500     const gdb_byte *data;
1501   };
1502
1503 #ifndef ATTR_ALLOC_CHUNK
1504 #define ATTR_ALLOC_CHUNK 4
1505 #endif
1506
1507 /* Allocate fields for structs, unions and enums in this size.  */
1508 #ifndef DW_FIELD_ALLOC_CHUNK
1509 #define DW_FIELD_ALLOC_CHUNK 4
1510 #endif
1511
1512 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1513    but this would require a corresponding change in unpack_field_as_long
1514    and friends.  */
1515 static int bits_per_byte = 8;
1516
1517 struct nextfield
1518 {
1519   struct nextfield *next;
1520   int accessibility;
1521   int virtuality;
1522   struct field field;
1523 };
1524
1525 struct nextfnfield
1526 {
1527   struct nextfnfield *next;
1528   struct fn_field fnfield;
1529 };
1530
1531 struct fnfieldlist
1532 {
1533   const char *name;
1534   int length;
1535   struct nextfnfield *head;
1536 };
1537
1538 struct decl_field_list
1539 {
1540   struct decl_field field;
1541   struct decl_field_list *next;
1542 };
1543
1544 /* The routines that read and process dies for a C struct or C++ class
1545    pass lists of data member fields and lists of member function fields
1546    in an instance of a field_info structure, as defined below.  */
1547 struct field_info
1548   {
1549     /* List of data member and baseclasses fields.  */
1550     struct nextfield *fields, *baseclasses;
1551
1552     /* Number of fields (including baseclasses).  */
1553     int nfields;
1554
1555     /* Number of baseclasses.  */
1556     int nbaseclasses;
1557
1558     /* Set if the accesibility of one of the fields is not public.  */
1559     int non_public_fields;
1560
1561     /* Member function fieldlist array, contains name of possibly overloaded
1562        member function, number of overloaded member functions and a pointer
1563        to the head of the member function field chain.  */
1564     struct fnfieldlist *fnfieldlists;
1565
1566     /* Number of entries in the fnfieldlists array.  */
1567     int nfnfields;
1568
1569     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1570        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1571     struct decl_field_list *typedef_field_list;
1572     unsigned typedef_field_list_count;
1573
1574     /* Nested types defined by this class and the number of elements in this
1575        list.  */
1576     struct decl_field_list *nested_types_list;
1577     unsigned nested_types_list_count;
1578   };
1579
1580 /* One item on the queue of compilation units to read in full symbols
1581    for.  */
1582 struct dwarf2_queue_item
1583 {
1584   struct dwarf2_per_cu_data *per_cu;
1585   enum language pretend_language;
1586   struct dwarf2_queue_item *next;
1587 };
1588
1589 /* The current queue.  */
1590 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1591
1592 /* Loaded secondary compilation units are kept in memory until they
1593    have not been referenced for the processing of this many
1594    compilation units.  Set this to zero to disable caching.  Cache
1595    sizes of up to at least twenty will improve startup time for
1596    typical inter-CU-reference binaries, at an obvious memory cost.  */
1597 static int dwarf_max_cache_age = 5;
1598 static void
1599 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1600                           struct cmd_list_element *c, const char *value)
1601 {
1602   fprintf_filtered (file, _("The upper bound on the age of cached "
1603                             "DWARF compilation units is %s.\n"),
1604                     value);
1605 }
1606 \f
1607 /* local function prototypes */
1608
1609 static const char *get_section_name (const struct dwarf2_section_info *);
1610
1611 static const char *get_section_file_name (const struct dwarf2_section_info *);
1612
1613 static void dwarf2_find_base_address (struct die_info *die,
1614                                       struct dwarf2_cu *cu);
1615
1616 static struct partial_symtab *create_partial_symtab
1617   (struct dwarf2_per_cu_data *per_cu, const char *name);
1618
1619 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1620                                         const gdb_byte *info_ptr,
1621                                         struct die_info *type_unit_die,
1622                                         int has_children, void *data);
1623
1624 static void dwarf2_build_psymtabs_hard (struct objfile *);
1625
1626 static void scan_partial_symbols (struct partial_die_info *,
1627                                   CORE_ADDR *, CORE_ADDR *,
1628                                   int, struct dwarf2_cu *);
1629
1630 static void add_partial_symbol (struct partial_die_info *,
1631                                 struct dwarf2_cu *);
1632
1633 static void add_partial_namespace (struct partial_die_info *pdi,
1634                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1635                                    int set_addrmap, struct dwarf2_cu *cu);
1636
1637 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1638                                 CORE_ADDR *highpc, int set_addrmap,
1639                                 struct dwarf2_cu *cu);
1640
1641 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1642                                      struct dwarf2_cu *cu);
1643
1644 static void add_partial_subprogram (struct partial_die_info *pdi,
1645                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1646                                     int need_pc, struct dwarf2_cu *cu);
1647
1648 static void dwarf2_read_symtab (struct partial_symtab *,
1649                                 struct objfile *);
1650
1651 static void psymtab_to_symtab_1 (struct partial_symtab *);
1652
1653 static struct abbrev_info *abbrev_table_lookup_abbrev
1654   (const struct abbrev_table *, unsigned int);
1655
1656 static struct abbrev_table *abbrev_table_read_table
1657   (struct dwarf2_section_info *, sect_offset);
1658
1659 static void abbrev_table_free (struct abbrev_table *);
1660
1661 static void abbrev_table_free_cleanup (void *);
1662
1663 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1664                                  struct dwarf2_section_info *);
1665
1666 static void dwarf2_free_abbrev_table (void *);
1667
1668 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1669
1670 static struct partial_die_info *load_partial_dies
1671   (const struct die_reader_specs *, const gdb_byte *, int);
1672
1673 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1674                                          struct partial_die_info *,
1675                                          struct abbrev_info *,
1676                                          unsigned int,
1677                                          const gdb_byte *);
1678
1679 static struct partial_die_info *find_partial_die (sect_offset, int,
1680                                                   struct dwarf2_cu *);
1681
1682 static void fixup_partial_die (struct partial_die_info *,
1683                                struct dwarf2_cu *);
1684
1685 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1686                                        struct attribute *, struct attr_abbrev *,
1687                                        const gdb_byte *);
1688
1689 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1690
1691 static int read_1_signed_byte (bfd *, const gdb_byte *);
1692
1693 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1694
1695 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1696
1697 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1698
1699 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1700                                unsigned int *);
1701
1702 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1703
1704 static LONGEST read_checked_initial_length_and_offset
1705   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1706    unsigned int *, unsigned int *);
1707
1708 static LONGEST read_offset (bfd *, const gdb_byte *,
1709                             const struct comp_unit_head *,
1710                             unsigned int *);
1711
1712 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1713
1714 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1715                                        sect_offset);
1716
1717 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1718
1719 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1720
1721 static const char *read_indirect_string (bfd *, const gdb_byte *,
1722                                          const struct comp_unit_head *,
1723                                          unsigned int *);
1724
1725 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1726                                               const struct comp_unit_head *,
1727                                               unsigned int *);
1728
1729 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1730
1731 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1732
1733 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1734                                               const gdb_byte *,
1735                                               unsigned int *);
1736
1737 static const char *read_str_index (const struct die_reader_specs *reader,
1738                                    ULONGEST str_index);
1739
1740 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1741
1742 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1743                                       struct dwarf2_cu *);
1744
1745 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1746                                                 unsigned int);
1747
1748 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1749                                        struct dwarf2_cu *cu);
1750
1751 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1752                                struct dwarf2_cu *cu);
1753
1754 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1755
1756 static struct die_info *die_specification (struct die_info *die,
1757                                            struct dwarf2_cu **);
1758
1759 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1760                                                 struct dwarf2_cu *cu);
1761
1762 static void dwarf_decode_lines (struct line_header *, const char *,
1763                                 struct dwarf2_cu *, struct partial_symtab *,
1764                                 CORE_ADDR, int decode_mapping);
1765
1766 static void dwarf2_start_subfile (const char *, const char *);
1767
1768 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1769                                                     const char *, const char *,
1770                                                     CORE_ADDR);
1771
1772 static struct symbol *new_symbol (struct die_info *, struct type *,
1773                                   struct dwarf2_cu *);
1774
1775 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1776                                        struct dwarf2_cu *, struct symbol *);
1777
1778 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1779                                 struct dwarf2_cu *);
1780
1781 static void dwarf2_const_value_attr (const struct attribute *attr,
1782                                      struct type *type,
1783                                      const char *name,
1784                                      struct obstack *obstack,
1785                                      struct dwarf2_cu *cu, LONGEST *value,
1786                                      const gdb_byte **bytes,
1787                                      struct dwarf2_locexpr_baton **baton);
1788
1789 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1790
1791 static int need_gnat_info (struct dwarf2_cu *);
1792
1793 static struct type *die_descriptive_type (struct die_info *,
1794                                           struct dwarf2_cu *);
1795
1796 static void set_descriptive_type (struct type *, struct die_info *,
1797                                   struct dwarf2_cu *);
1798
1799 static struct type *die_containing_type (struct die_info *,
1800                                          struct dwarf2_cu *);
1801
1802 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1803                                      struct dwarf2_cu *);
1804
1805 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1806
1807 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1808
1809 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1810
1811 static char *typename_concat (struct obstack *obs, const char *prefix,
1812                               const char *suffix, int physname,
1813                               struct dwarf2_cu *cu);
1814
1815 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1816
1817 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1818
1819 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1820
1821 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1822
1823 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1824
1825 static void read_variable (struct die_info *die, struct dwarf2_cu *cu);
1826
1827 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1828                                struct dwarf2_cu *, struct partial_symtab *);
1829
1830 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1831    values.  Keep the items ordered with increasing constraints compliance.  */
1832 enum pc_bounds_kind
1833 {
1834   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1835   PC_BOUNDS_NOT_PRESENT,
1836
1837   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1838      were present but they do not form a valid range of PC addresses.  */
1839   PC_BOUNDS_INVALID,
1840
1841   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1842   PC_BOUNDS_RANGES,
1843
1844   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1845   PC_BOUNDS_HIGH_LOW,
1846 };
1847
1848 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1849                                                  CORE_ADDR *, CORE_ADDR *,
1850                                                  struct dwarf2_cu *,
1851                                                  struct partial_symtab *);
1852
1853 static void get_scope_pc_bounds (struct die_info *,
1854                                  CORE_ADDR *, CORE_ADDR *,
1855                                  struct dwarf2_cu *);
1856
1857 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1858                                         CORE_ADDR, struct dwarf2_cu *);
1859
1860 static void dwarf2_add_field (struct field_info *, struct die_info *,
1861                               struct dwarf2_cu *);
1862
1863 static void dwarf2_attach_fields_to_type (struct field_info *,
1864                                           struct type *, struct dwarf2_cu *);
1865
1866 static void dwarf2_add_member_fn (struct field_info *,
1867                                   struct die_info *, struct type *,
1868                                   struct dwarf2_cu *);
1869
1870 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1871                                              struct type *,
1872                                              struct dwarf2_cu *);
1873
1874 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1875
1876 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1877
1878 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1879
1880 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1881
1882 static struct using_direct **using_directives (enum language);
1883
1884 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1885
1886 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1887
1888 static struct type *read_module_type (struct die_info *die,
1889                                       struct dwarf2_cu *cu);
1890
1891 static const char *namespace_name (struct die_info *die,
1892                                    int *is_anonymous, struct dwarf2_cu *);
1893
1894 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1895
1896 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1897
1898 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1899                                                        struct dwarf2_cu *);
1900
1901 static struct die_info *read_die_and_siblings_1
1902   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1903    struct die_info *);
1904
1905 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1906                                                const gdb_byte *info_ptr,
1907                                                const gdb_byte **new_info_ptr,
1908                                                struct die_info *parent);
1909
1910 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1911                                         struct die_info **, const gdb_byte *,
1912                                         int *, int);
1913
1914 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1915                                       struct die_info **, const gdb_byte *,
1916                                       int *);
1917
1918 static void process_die (struct die_info *, struct dwarf2_cu *);
1919
1920 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1921                                              struct obstack *);
1922
1923 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1924
1925 static const char *dwarf2_full_name (const char *name,
1926                                      struct die_info *die,
1927                                      struct dwarf2_cu *cu);
1928
1929 static const char *dwarf2_physname (const char *name, struct die_info *die,
1930                                     struct dwarf2_cu *cu);
1931
1932 static struct die_info *dwarf2_extension (struct die_info *die,
1933                                           struct dwarf2_cu **);
1934
1935 static const char *dwarf_tag_name (unsigned int);
1936
1937 static const char *dwarf_attr_name (unsigned int);
1938
1939 static const char *dwarf_form_name (unsigned int);
1940
1941 static const char *dwarf_bool_name (unsigned int);
1942
1943 static const char *dwarf_type_encoding_name (unsigned int);
1944
1945 static struct die_info *sibling_die (struct die_info *);
1946
1947 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1948
1949 static void dump_die_for_error (struct die_info *);
1950
1951 static void dump_die_1 (struct ui_file *, int level, int max_level,
1952                         struct die_info *);
1953
1954 /*static*/ void dump_die (struct die_info *, int max_level);
1955
1956 static void store_in_ref_table (struct die_info *,
1957                                 struct dwarf2_cu *);
1958
1959 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1960
1961 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1962
1963 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1964                                                const struct attribute *,
1965                                                struct dwarf2_cu **);
1966
1967 static struct die_info *follow_die_ref (struct die_info *,
1968                                         const struct attribute *,
1969                                         struct dwarf2_cu **);
1970
1971 static struct die_info *follow_die_sig (struct die_info *,
1972                                         const struct attribute *,
1973                                         struct dwarf2_cu **);
1974
1975 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1976                                          struct dwarf2_cu *);
1977
1978 static struct type *get_DW_AT_signature_type (struct die_info *,
1979                                               const struct attribute *,
1980                                               struct dwarf2_cu *);
1981
1982 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1983
1984 static void read_signatured_type (struct signatured_type *);
1985
1986 static int attr_to_dynamic_prop (const struct attribute *attr,
1987                                  struct die_info *die, struct dwarf2_cu *cu,
1988                                  struct dynamic_prop *prop);
1989
1990 /* memory allocation interface */
1991
1992 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1993
1994 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1995
1996 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1997
1998 static int attr_form_is_block (const struct attribute *);
1999
2000 static int attr_form_is_section_offset (const struct attribute *);
2001
2002 static int attr_form_is_constant (const struct attribute *);
2003
2004 static int attr_form_is_ref (const struct attribute *);
2005
2006 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
2007                                    struct dwarf2_loclist_baton *baton,
2008                                    const struct attribute *attr);
2009
2010 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
2011                                          struct symbol *sym,
2012                                          struct dwarf2_cu *cu,
2013                                          int is_block);
2014
2015 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
2016                                      const gdb_byte *info_ptr,
2017                                      struct abbrev_info *abbrev);
2018
2019 static void free_stack_comp_unit (void *);
2020
2021 static hashval_t partial_die_hash (const void *item);
2022
2023 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
2024
2025 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2026   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2027
2028 static void init_one_comp_unit (struct dwarf2_cu *cu,
2029                                 struct dwarf2_per_cu_data *per_cu);
2030
2031 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2032                                    struct die_info *comp_unit_die,
2033                                    enum language pretend_language);
2034
2035 static void free_heap_comp_unit (void *);
2036
2037 static void free_cached_comp_units (void *);
2038
2039 static void age_cached_comp_units (void);
2040
2041 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2042
2043 static struct type *set_die_type (struct die_info *, struct type *,
2044                                   struct dwarf2_cu *);
2045
2046 static void create_all_comp_units (struct objfile *);
2047
2048 static int create_all_type_units (struct objfile *);
2049
2050 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2051                                  enum language);
2052
2053 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2054                                     enum language);
2055
2056 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2057                                     enum language);
2058
2059 static void dwarf2_add_dependence (struct dwarf2_cu *,
2060                                    struct dwarf2_per_cu_data *);
2061
2062 static void dwarf2_mark (struct dwarf2_cu *);
2063
2064 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2065
2066 static struct type *get_die_type_at_offset (sect_offset,
2067                                             struct dwarf2_per_cu_data *);
2068
2069 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2070
2071 static void dwarf2_release_queue (void *dummy);
2072
2073 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2074                              enum language pretend_language);
2075
2076 static void process_queue (void);
2077
2078 /* The return type of find_file_and_directory.  Note, the enclosed
2079    string pointers are only valid while this object is valid.  */
2080
2081 struct file_and_directory
2082 {
2083   /* The filename.  This is never NULL.  */
2084   const char *name;
2085
2086   /* The compilation directory.  NULL if not known.  If we needed to
2087      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2088      points directly to the DW_AT_comp_dir string attribute owned by
2089      the obstack that owns the DIE.  */
2090   const char *comp_dir;
2091
2092   /* If we needed to build a new string for comp_dir, this is what
2093      owns the storage.  */
2094   std::string comp_dir_storage;
2095 };
2096
2097 static file_and_directory find_file_and_directory (struct die_info *die,
2098                                                    struct dwarf2_cu *cu);
2099
2100 static char *file_full_name (int file, struct line_header *lh,
2101                              const char *comp_dir);
2102
2103 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2104 enum class rcuh_kind { COMPILE, TYPE };
2105
2106 static const gdb_byte *read_and_check_comp_unit_head
2107   (struct comp_unit_head *header,
2108    struct dwarf2_section_info *section,
2109    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2110    rcuh_kind section_kind);
2111
2112 static void init_cutu_and_read_dies
2113   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2114    int use_existing_cu, int keep,
2115    die_reader_func_ftype *die_reader_func, void *data);
2116
2117 static void init_cutu_and_read_dies_simple
2118   (struct dwarf2_per_cu_data *this_cu,
2119    die_reader_func_ftype *die_reader_func, void *data);
2120
2121 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2122
2123 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2124
2125 static struct dwo_unit *lookup_dwo_unit_in_dwp
2126   (struct dwp_file *dwp_file, const char *comp_dir,
2127    ULONGEST signature, int is_debug_types);
2128
2129 static struct dwp_file *get_dwp_file (void);
2130
2131 static struct dwo_unit *lookup_dwo_comp_unit
2132   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2133
2134 static struct dwo_unit *lookup_dwo_type_unit
2135   (struct signatured_type *, const char *, const char *);
2136
2137 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2138
2139 static void free_dwo_file_cleanup (void *);
2140
2141 static void process_cu_includes (void);
2142
2143 static void check_producer (struct dwarf2_cu *cu);
2144
2145 static void free_line_header_voidp (void *arg);
2146 \f
2147 /* Various complaints about symbol reading that don't abort the process.  */
2148
2149 static void
2150 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2151 {
2152   complaint (&symfile_complaints,
2153              _("statement list doesn't fit in .debug_line section"));
2154 }
2155
2156 static void
2157 dwarf2_debug_line_missing_file_complaint (void)
2158 {
2159   complaint (&symfile_complaints,
2160              _(".debug_line section has line data without a file"));
2161 }
2162
2163 static void
2164 dwarf2_debug_line_missing_end_sequence_complaint (void)
2165 {
2166   complaint (&symfile_complaints,
2167              _(".debug_line section has line "
2168                "program sequence without an end"));
2169 }
2170
2171 static void
2172 dwarf2_complex_location_expr_complaint (void)
2173 {
2174   complaint (&symfile_complaints, _("location expression too complex"));
2175 }
2176
2177 static void
2178 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2179                                               int arg3)
2180 {
2181   complaint (&symfile_complaints,
2182              _("const value length mismatch for '%s', got %d, expected %d"),
2183              arg1, arg2, arg3);
2184 }
2185
2186 static void
2187 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2188 {
2189   complaint (&symfile_complaints,
2190              _("debug info runs off end of %s section"
2191                " [in module %s]"),
2192              get_section_name (section),
2193              get_section_file_name (section));
2194 }
2195
2196 static void
2197 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2198 {
2199   complaint (&symfile_complaints,
2200              _("macro debug info contains a "
2201                "malformed macro definition:\n`%s'"),
2202              arg1);
2203 }
2204
2205 static void
2206 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2207 {
2208   complaint (&symfile_complaints,
2209              _("invalid attribute class or form for '%s' in '%s'"),
2210              arg1, arg2);
2211 }
2212
2213 /* Hash function for line_header_hash.  */
2214
2215 static hashval_t
2216 line_header_hash (const struct line_header *ofs)
2217 {
2218   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2219 }
2220
2221 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2222
2223 static hashval_t
2224 line_header_hash_voidp (const void *item)
2225 {
2226   const struct line_header *ofs = (const struct line_header *) item;
2227
2228   return line_header_hash (ofs);
2229 }
2230
2231 /* Equality function for line_header_hash.  */
2232
2233 static int
2234 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2235 {
2236   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2237   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2238
2239   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2240           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2241 }
2242
2243 \f
2244
2245 /* Read the given attribute value as an address, taking the attribute's
2246    form into account.  */
2247
2248 static CORE_ADDR
2249 attr_value_as_address (struct attribute *attr)
2250 {
2251   CORE_ADDR addr;
2252
2253   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2254     {
2255       /* Aside from a few clearly defined exceptions, attributes that
2256          contain an address must always be in DW_FORM_addr form.
2257          Unfortunately, some compilers happen to be violating this
2258          requirement by encoding addresses using other forms, such
2259          as DW_FORM_data4 for example.  For those broken compilers,
2260          we try to do our best, without any guarantee of success,
2261          to interpret the address correctly.  It would also be nice
2262          to generate a complaint, but that would require us to maintain
2263          a list of legitimate cases where a non-address form is allowed,
2264          as well as update callers to pass in at least the CU's DWARF
2265          version.  This is more overhead than what we're willing to
2266          expand for a pretty rare case.  */
2267       addr = DW_UNSND (attr);
2268     }
2269   else
2270     addr = DW_ADDR (attr);
2271
2272   return addr;
2273 }
2274
2275 /* The suffix for an index file.  */
2276 #define INDEX4_SUFFIX ".gdb-index"
2277 #define INDEX5_SUFFIX ".debug_names"
2278 #define DEBUG_STR_SUFFIX ".debug_str"
2279
2280 /* See declaration.  */
2281
2282 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2283                                         const dwarf2_debug_sections *names)
2284   : objfile (objfile_)
2285 {
2286   if (names == NULL)
2287     names = &dwarf2_elf_names;
2288
2289   bfd *obfd = objfile->obfd;
2290
2291   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2292     locate_sections (obfd, sec, *names);
2293 }
2294
2295 dwarf2_per_objfile::~dwarf2_per_objfile ()
2296 {
2297   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2298   free_cached_comp_units ();
2299
2300   if (quick_file_names_table)
2301     htab_delete (quick_file_names_table);
2302
2303   if (line_header_hash)
2304     htab_delete (line_header_hash);
2305
2306   /* Everything else should be on the objfile obstack.  */
2307 }
2308
2309 /* See declaration.  */
2310
2311 void
2312 dwarf2_per_objfile::free_cached_comp_units ()
2313 {
2314   dwarf2_per_cu_data *per_cu = read_in_chain;
2315   dwarf2_per_cu_data **last_chain = &read_in_chain;
2316   while (per_cu != NULL)
2317     {
2318       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2319
2320       free_heap_comp_unit (per_cu->cu);
2321       *last_chain = next_cu;
2322       per_cu = next_cu;
2323     }
2324 }
2325
2326 /* Try to locate the sections we need for DWARF 2 debugging
2327    information and return true if we have enough to do something.
2328    NAMES points to the dwarf2 section names, or is NULL if the standard
2329    ELF names are used.  */
2330
2331 int
2332 dwarf2_has_info (struct objfile *objfile,
2333                  const struct dwarf2_debug_sections *names)
2334 {
2335   if (objfile->flags & OBJF_READNEVER)
2336     return 0;
2337
2338   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2339                         objfile_data (objfile, dwarf2_objfile_data_key));
2340   if (!dwarf2_per_objfile)
2341     {
2342       /* Initialize per-objfile state.  */
2343       struct dwarf2_per_objfile *data
2344         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2345
2346       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2347       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2348     }
2349   return (!dwarf2_per_objfile->info.is_virtual
2350           && dwarf2_per_objfile->info.s.section != NULL
2351           && !dwarf2_per_objfile->abbrev.is_virtual
2352           && dwarf2_per_objfile->abbrev.s.section != NULL);
2353 }
2354
2355 /* Return the containing section of virtual section SECTION.  */
2356
2357 static struct dwarf2_section_info *
2358 get_containing_section (const struct dwarf2_section_info *section)
2359 {
2360   gdb_assert (section->is_virtual);
2361   return section->s.containing_section;
2362 }
2363
2364 /* Return the bfd owner of SECTION.  */
2365
2366 static struct bfd *
2367 get_section_bfd_owner (const struct dwarf2_section_info *section)
2368 {
2369   if (section->is_virtual)
2370     {
2371       section = get_containing_section (section);
2372       gdb_assert (!section->is_virtual);
2373     }
2374   return section->s.section->owner;
2375 }
2376
2377 /* Return the bfd section of SECTION.
2378    Returns NULL if the section is not present.  */
2379
2380 static asection *
2381 get_section_bfd_section (const struct dwarf2_section_info *section)
2382 {
2383   if (section->is_virtual)
2384     {
2385       section = get_containing_section (section);
2386       gdb_assert (!section->is_virtual);
2387     }
2388   return section->s.section;
2389 }
2390
2391 /* Return the name of SECTION.  */
2392
2393 static const char *
2394 get_section_name (const struct dwarf2_section_info *section)
2395 {
2396   asection *sectp = get_section_bfd_section (section);
2397
2398   gdb_assert (sectp != NULL);
2399   return bfd_section_name (get_section_bfd_owner (section), sectp);
2400 }
2401
2402 /* Return the name of the file SECTION is in.  */
2403
2404 static const char *
2405 get_section_file_name (const struct dwarf2_section_info *section)
2406 {
2407   bfd *abfd = get_section_bfd_owner (section);
2408
2409   return bfd_get_filename (abfd);
2410 }
2411
2412 /* Return the id of SECTION.
2413    Returns 0 if SECTION doesn't exist.  */
2414
2415 static int
2416 get_section_id (const struct dwarf2_section_info *section)
2417 {
2418   asection *sectp = get_section_bfd_section (section);
2419
2420   if (sectp == NULL)
2421     return 0;
2422   return sectp->id;
2423 }
2424
2425 /* Return the flags of SECTION.
2426    SECTION (or containing section if this is a virtual section) must exist.  */
2427
2428 static int
2429 get_section_flags (const struct dwarf2_section_info *section)
2430 {
2431   asection *sectp = get_section_bfd_section (section);
2432
2433   gdb_assert (sectp != NULL);
2434   return bfd_get_section_flags (sectp->owner, sectp);
2435 }
2436
2437 /* When loading sections, we look either for uncompressed section or for
2438    compressed section names.  */
2439
2440 static int
2441 section_is_p (const char *section_name,
2442               const struct dwarf2_section_names *names)
2443 {
2444   if (names->normal != NULL
2445       && strcmp (section_name, names->normal) == 0)
2446     return 1;
2447   if (names->compressed != NULL
2448       && strcmp (section_name, names->compressed) == 0)
2449     return 1;
2450   return 0;
2451 }
2452
2453 /* See declaration.  */
2454
2455 void
2456 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2457                                      const dwarf2_debug_sections &names)
2458 {
2459   flagword aflag = bfd_get_section_flags (abfd, sectp);
2460
2461   if ((aflag & SEC_HAS_CONTENTS) == 0)
2462     {
2463     }
2464   else if (section_is_p (sectp->name, &names.info))
2465     {
2466       this->info.s.section = sectp;
2467       this->info.size = bfd_get_section_size (sectp);
2468     }
2469   else if (section_is_p (sectp->name, &names.abbrev))
2470     {
2471       this->abbrev.s.section = sectp;
2472       this->abbrev.size = bfd_get_section_size (sectp);
2473     }
2474   else if (section_is_p (sectp->name, &names.line))
2475     {
2476       this->line.s.section = sectp;
2477       this->line.size = bfd_get_section_size (sectp);
2478     }
2479   else if (section_is_p (sectp->name, &names.loc))
2480     {
2481       this->loc.s.section = sectp;
2482       this->loc.size = bfd_get_section_size (sectp);
2483     }
2484   else if (section_is_p (sectp->name, &names.loclists))
2485     {
2486       this->loclists.s.section = sectp;
2487       this->loclists.size = bfd_get_section_size (sectp);
2488     }
2489   else if (section_is_p (sectp->name, &names.macinfo))
2490     {
2491       this->macinfo.s.section = sectp;
2492       this->macinfo.size = bfd_get_section_size (sectp);
2493     }
2494   else if (section_is_p (sectp->name, &names.macro))
2495     {
2496       this->macro.s.section = sectp;
2497       this->macro.size = bfd_get_section_size (sectp);
2498     }
2499   else if (section_is_p (sectp->name, &names.str))
2500     {
2501       this->str.s.section = sectp;
2502       this->str.size = bfd_get_section_size (sectp);
2503     }
2504   else if (section_is_p (sectp->name, &names.line_str))
2505     {
2506       this->line_str.s.section = sectp;
2507       this->line_str.size = bfd_get_section_size (sectp);
2508     }
2509   else if (section_is_p (sectp->name, &names.addr))
2510     {
2511       this->addr.s.section = sectp;
2512       this->addr.size = bfd_get_section_size (sectp);
2513     }
2514   else if (section_is_p (sectp->name, &names.frame))
2515     {
2516       this->frame.s.section = sectp;
2517       this->frame.size = bfd_get_section_size (sectp);
2518     }
2519   else if (section_is_p (sectp->name, &names.eh_frame))
2520     {
2521       this->eh_frame.s.section = sectp;
2522       this->eh_frame.size = bfd_get_section_size (sectp);
2523     }
2524   else if (section_is_p (sectp->name, &names.ranges))
2525     {
2526       this->ranges.s.section = sectp;
2527       this->ranges.size = bfd_get_section_size (sectp);
2528     }
2529   else if (section_is_p (sectp->name, &names.rnglists))
2530     {
2531       this->rnglists.s.section = sectp;
2532       this->rnglists.size = bfd_get_section_size (sectp);
2533     }
2534   else if (section_is_p (sectp->name, &names.types))
2535     {
2536       struct dwarf2_section_info type_section;
2537
2538       memset (&type_section, 0, sizeof (type_section));
2539       type_section.s.section = sectp;
2540       type_section.size = bfd_get_section_size (sectp);
2541
2542       VEC_safe_push (dwarf2_section_info_def, this->types,
2543                      &type_section);
2544     }
2545   else if (section_is_p (sectp->name, &names.gdb_index))
2546     {
2547       this->gdb_index.s.section = sectp;
2548       this->gdb_index.size = bfd_get_section_size (sectp);
2549     }
2550
2551   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2552       && bfd_section_vma (abfd, sectp) == 0)
2553     this->has_section_at_zero = true;
2554 }
2555
2556 /* A helper function that decides whether a section is empty,
2557    or not present.  */
2558
2559 static int
2560 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2561 {
2562   if (section->is_virtual)
2563     return section->size == 0;
2564   return section->s.section == NULL || section->size == 0;
2565 }
2566
2567 /* Read the contents of the section INFO.
2568    OBJFILE is the main object file, but not necessarily the file where
2569    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2570    of the DWO file.
2571    If the section is compressed, uncompress it before returning.  */
2572
2573 static void
2574 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2575 {
2576   asection *sectp;
2577   bfd *abfd;
2578   gdb_byte *buf, *retbuf;
2579
2580   if (info->readin)
2581     return;
2582   info->buffer = NULL;
2583   info->readin = 1;
2584
2585   if (dwarf2_section_empty_p (info))
2586     return;
2587
2588   sectp = get_section_bfd_section (info);
2589
2590   /* If this is a virtual section we need to read in the real one first.  */
2591   if (info->is_virtual)
2592     {
2593       struct dwarf2_section_info *containing_section =
2594         get_containing_section (info);
2595
2596       gdb_assert (sectp != NULL);
2597       if ((sectp->flags & SEC_RELOC) != 0)
2598         {
2599           error (_("Dwarf Error: DWP format V2 with relocations is not"
2600                    " supported in section %s [in module %s]"),
2601                  get_section_name (info), get_section_file_name (info));
2602         }
2603       dwarf2_read_section (objfile, containing_section);
2604       /* Other code should have already caught virtual sections that don't
2605          fit.  */
2606       gdb_assert (info->virtual_offset + info->size
2607                   <= containing_section->size);
2608       /* If the real section is empty or there was a problem reading the
2609          section we shouldn't get here.  */
2610       gdb_assert (containing_section->buffer != NULL);
2611       info->buffer = containing_section->buffer + info->virtual_offset;
2612       return;
2613     }
2614
2615   /* If the section has relocations, we must read it ourselves.
2616      Otherwise we attach it to the BFD.  */
2617   if ((sectp->flags & SEC_RELOC) == 0)
2618     {
2619       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2620       return;
2621     }
2622
2623   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2624   info->buffer = buf;
2625
2626   /* When debugging .o files, we may need to apply relocations; see
2627      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2628      We never compress sections in .o files, so we only need to
2629      try this when the section is not compressed.  */
2630   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2631   if (retbuf != NULL)
2632     {
2633       info->buffer = retbuf;
2634       return;
2635     }
2636
2637   abfd = get_section_bfd_owner (info);
2638   gdb_assert (abfd != NULL);
2639
2640   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2641       || bfd_bread (buf, info->size, abfd) != info->size)
2642     {
2643       error (_("Dwarf Error: Can't read DWARF data"
2644                " in section %s [in module %s]"),
2645              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2646     }
2647 }
2648
2649 /* A helper function that returns the size of a section in a safe way.
2650    If you are positive that the section has been read before using the
2651    size, then it is safe to refer to the dwarf2_section_info object's
2652    "size" field directly.  In other cases, you must call this
2653    function, because for compressed sections the size field is not set
2654    correctly until the section has been read.  */
2655
2656 static bfd_size_type
2657 dwarf2_section_size (struct objfile *objfile,
2658                      struct dwarf2_section_info *info)
2659 {
2660   if (!info->readin)
2661     dwarf2_read_section (objfile, info);
2662   return info->size;
2663 }
2664
2665 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2666    SECTION_NAME.  */
2667
2668 void
2669 dwarf2_get_section_info (struct objfile *objfile,
2670                          enum dwarf2_section_enum sect,
2671                          asection **sectp, const gdb_byte **bufp,
2672                          bfd_size_type *sizep)
2673 {
2674   struct dwarf2_per_objfile *data
2675     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2676                                                   dwarf2_objfile_data_key);
2677   struct dwarf2_section_info *info;
2678
2679   /* We may see an objfile without any DWARF, in which case we just
2680      return nothing.  */
2681   if (data == NULL)
2682     {
2683       *sectp = NULL;
2684       *bufp = NULL;
2685       *sizep = 0;
2686       return;
2687     }
2688   switch (sect)
2689     {
2690     case DWARF2_DEBUG_FRAME:
2691       info = &data->frame;
2692       break;
2693     case DWARF2_EH_FRAME:
2694       info = &data->eh_frame;
2695       break;
2696     default:
2697       gdb_assert_not_reached ("unexpected section");
2698     }
2699
2700   dwarf2_read_section (objfile, info);
2701
2702   *sectp = get_section_bfd_section (info);
2703   *bufp = info->buffer;
2704   *sizep = info->size;
2705 }
2706
2707 /* A helper function to find the sections for a .dwz file.  */
2708
2709 static void
2710 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2711 {
2712   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2713
2714   /* Note that we only support the standard ELF names, because .dwz
2715      is ELF-only (at the time of writing).  */
2716   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2717     {
2718       dwz_file->abbrev.s.section = sectp;
2719       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2720     }
2721   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2722     {
2723       dwz_file->info.s.section = sectp;
2724       dwz_file->info.size = bfd_get_section_size (sectp);
2725     }
2726   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2727     {
2728       dwz_file->str.s.section = sectp;
2729       dwz_file->str.size = bfd_get_section_size (sectp);
2730     }
2731   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2732     {
2733       dwz_file->line.s.section = sectp;
2734       dwz_file->line.size = bfd_get_section_size (sectp);
2735     }
2736   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2737     {
2738       dwz_file->macro.s.section = sectp;
2739       dwz_file->macro.size = bfd_get_section_size (sectp);
2740     }
2741   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2742     {
2743       dwz_file->gdb_index.s.section = sectp;
2744       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2745     }
2746 }
2747
2748 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2749    there is no .gnu_debugaltlink section in the file.  Error if there
2750    is such a section but the file cannot be found.  */
2751
2752 static struct dwz_file *
2753 dwarf2_get_dwz_file (void)
2754 {
2755   const char *filename;
2756   struct dwz_file *result;
2757   bfd_size_type buildid_len_arg;
2758   size_t buildid_len;
2759   bfd_byte *buildid;
2760
2761   if (dwarf2_per_objfile->dwz_file != NULL)
2762     return dwarf2_per_objfile->dwz_file;
2763
2764   bfd_set_error (bfd_error_no_error);
2765   gdb::unique_xmalloc_ptr<char> data
2766     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2767                                   &buildid_len_arg, &buildid));
2768   if (data == NULL)
2769     {
2770       if (bfd_get_error () == bfd_error_no_error)
2771         return NULL;
2772       error (_("could not read '.gnu_debugaltlink' section: %s"),
2773              bfd_errmsg (bfd_get_error ()));
2774     }
2775
2776   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2777
2778   buildid_len = (size_t) buildid_len_arg;
2779
2780   filename = data.get ();
2781
2782   std::string abs_storage;
2783   if (!IS_ABSOLUTE_PATH (filename))
2784     {
2785       gdb::unique_xmalloc_ptr<char> abs
2786         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2787
2788       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2789       filename = abs_storage.c_str ();
2790     }
2791
2792   /* First try the file name given in the section.  If that doesn't
2793      work, try to use the build-id instead.  */
2794   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2795   if (dwz_bfd != NULL)
2796     {
2797       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2798         dwz_bfd.release ();
2799     }
2800
2801   if (dwz_bfd == NULL)
2802     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2803
2804   if (dwz_bfd == NULL)
2805     error (_("could not find '.gnu_debugaltlink' file for %s"),
2806            objfile_name (dwarf2_per_objfile->objfile));
2807
2808   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2809                            struct dwz_file);
2810   result->dwz_bfd = dwz_bfd.release ();
2811
2812   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2813
2814   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2815   dwarf2_per_objfile->dwz_file = result;
2816   return result;
2817 }
2818 \f
2819 /* DWARF quick_symbols_functions support.  */
2820
2821 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2822    unique line tables, so we maintain a separate table of all .debug_line
2823    derived entries to support the sharing.
2824    All the quick functions need is the list of file names.  We discard the
2825    line_header when we're done and don't need to record it here.  */
2826 struct quick_file_names
2827 {
2828   /* The data used to construct the hash key.  */
2829   struct stmt_list_hash hash;
2830
2831   /* The number of entries in file_names, real_names.  */
2832   unsigned int num_file_names;
2833
2834   /* The file names from the line table, after being run through
2835      file_full_name.  */
2836   const char **file_names;
2837
2838   /* The file names from the line table after being run through
2839      gdb_realpath.  These are computed lazily.  */
2840   const char **real_names;
2841 };
2842
2843 /* When using the index (and thus not using psymtabs), each CU has an
2844    object of this type.  This is used to hold information needed by
2845    the various "quick" methods.  */
2846 struct dwarf2_per_cu_quick_data
2847 {
2848   /* The file table.  This can be NULL if there was no file table
2849      or it's currently not read in.
2850      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2851   struct quick_file_names *file_names;
2852
2853   /* The corresponding symbol table.  This is NULL if symbols for this
2854      CU have not yet been read.  */
2855   struct compunit_symtab *compunit_symtab;
2856
2857   /* A temporary mark bit used when iterating over all CUs in
2858      expand_symtabs_matching.  */
2859   unsigned int mark : 1;
2860
2861   /* True if we've tried to read the file table and found there isn't one.
2862      There will be no point in trying to read it again next time.  */
2863   unsigned int no_file_data : 1;
2864 };
2865
2866 /* Utility hash function for a stmt_list_hash.  */
2867
2868 static hashval_t
2869 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2870 {
2871   hashval_t v = 0;
2872
2873   if (stmt_list_hash->dwo_unit != NULL)
2874     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2875   v += to_underlying (stmt_list_hash->line_sect_off);
2876   return v;
2877 }
2878
2879 /* Utility equality function for a stmt_list_hash.  */
2880
2881 static int
2882 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2883                     const struct stmt_list_hash *rhs)
2884 {
2885   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2886     return 0;
2887   if (lhs->dwo_unit != NULL
2888       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2889     return 0;
2890
2891   return lhs->line_sect_off == rhs->line_sect_off;
2892 }
2893
2894 /* Hash function for a quick_file_names.  */
2895
2896 static hashval_t
2897 hash_file_name_entry (const void *e)
2898 {
2899   const struct quick_file_names *file_data
2900     = (const struct quick_file_names *) e;
2901
2902   return hash_stmt_list_entry (&file_data->hash);
2903 }
2904
2905 /* Equality function for a quick_file_names.  */
2906
2907 static int
2908 eq_file_name_entry (const void *a, const void *b)
2909 {
2910   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2911   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2912
2913   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2914 }
2915
2916 /* Delete function for a quick_file_names.  */
2917
2918 static void
2919 delete_file_name_entry (void *e)
2920 {
2921   struct quick_file_names *file_data = (struct quick_file_names *) e;
2922   int i;
2923
2924   for (i = 0; i < file_data->num_file_names; ++i)
2925     {
2926       xfree ((void*) file_data->file_names[i]);
2927       if (file_data->real_names)
2928         xfree ((void*) file_data->real_names[i]);
2929     }
2930
2931   /* The space for the struct itself lives on objfile_obstack,
2932      so we don't free it here.  */
2933 }
2934
2935 /* Create a quick_file_names hash table.  */
2936
2937 static htab_t
2938 create_quick_file_names_table (unsigned int nr_initial_entries)
2939 {
2940   return htab_create_alloc (nr_initial_entries,
2941                             hash_file_name_entry, eq_file_name_entry,
2942                             delete_file_name_entry, xcalloc, xfree);
2943 }
2944
2945 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2946    have to be created afterwards.  You should call age_cached_comp_units after
2947    processing PER_CU->CU.  dw2_setup must have been already called.  */
2948
2949 static void
2950 load_cu (struct dwarf2_per_cu_data *per_cu)
2951 {
2952   if (per_cu->is_debug_types)
2953     load_full_type_unit (per_cu);
2954   else
2955     load_full_comp_unit (per_cu, language_minimal);
2956
2957   if (per_cu->cu == NULL)
2958     return;  /* Dummy CU.  */
2959
2960   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2961 }
2962
2963 /* Read in the symbols for PER_CU.  */
2964
2965 static void
2966 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2967 {
2968   struct cleanup *back_to;
2969
2970   /* Skip type_unit_groups, reading the type units they contain
2971      is handled elsewhere.  */
2972   if (IS_TYPE_UNIT_GROUP (per_cu))
2973     return;
2974
2975   back_to = make_cleanup (dwarf2_release_queue, NULL);
2976
2977   if (dwarf2_per_objfile->using_index
2978       ? per_cu->v.quick->compunit_symtab == NULL
2979       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2980     {
2981       queue_comp_unit (per_cu, language_minimal);
2982       load_cu (per_cu);
2983
2984       /* If we just loaded a CU from a DWO, and we're working with an index
2985          that may badly handle TUs, load all the TUs in that DWO as well.
2986          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2987       if (!per_cu->is_debug_types
2988           && per_cu->cu != NULL
2989           && per_cu->cu->dwo_unit != NULL
2990           && dwarf2_per_objfile->index_table != NULL
2991           && dwarf2_per_objfile->index_table->version <= 7
2992           /* DWP files aren't supported yet.  */
2993           && get_dwp_file () == NULL)
2994         queue_and_load_all_dwo_tus (per_cu);
2995     }
2996
2997   process_queue ();
2998
2999   /* Age the cache, releasing compilation units that have not
3000      been used recently.  */
3001   age_cached_comp_units ();
3002
3003   do_cleanups (back_to);
3004 }
3005
3006 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
3007    the objfile from which this CU came.  Returns the resulting symbol
3008    table.  */
3009
3010 static struct compunit_symtab *
3011 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
3012 {
3013   gdb_assert (dwarf2_per_objfile->using_index);
3014   if (!per_cu->v.quick->compunit_symtab)
3015     {
3016       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
3017       scoped_restore decrementer = increment_reading_symtab ();
3018       dw2_do_instantiate_symtab (per_cu);
3019       process_cu_includes ();
3020       do_cleanups (back_to);
3021     }
3022
3023   return per_cu->v.quick->compunit_symtab;
3024 }
3025
3026 /* Return the CU/TU given its index.
3027
3028    This is intended for loops like:
3029
3030    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3031                     + dwarf2_per_objfile->n_type_units); ++i)
3032      {
3033        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3034
3035        ...;
3036      }
3037 */
3038
3039 static struct dwarf2_per_cu_data *
3040 dw2_get_cutu (int index)
3041 {
3042   if (index >= dwarf2_per_objfile->n_comp_units)
3043     {
3044       index -= dwarf2_per_objfile->n_comp_units;
3045       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3046       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3047     }
3048
3049   return dwarf2_per_objfile->all_comp_units[index];
3050 }
3051
3052 /* Return the CU given its index.
3053    This differs from dw2_get_cutu in that it's for when you know INDEX
3054    refers to a CU.  */
3055
3056 static struct dwarf2_per_cu_data *
3057 dw2_get_cu (int index)
3058 {
3059   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3060
3061   return dwarf2_per_objfile->all_comp_units[index];
3062 }
3063
3064 /* A helper for create_cus_from_index that handles a given list of
3065    CUs.  */
3066
3067 static void
3068 create_cus_from_index_list (struct objfile *objfile,
3069                             const gdb_byte *cu_list, offset_type n_elements,
3070                             struct dwarf2_section_info *section,
3071                             int is_dwz,
3072                             int base_offset)
3073 {
3074   offset_type i;
3075
3076   for (i = 0; i < n_elements; i += 2)
3077     {
3078       gdb_static_assert (sizeof (ULONGEST) >= 8);
3079
3080       sect_offset sect_off
3081         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3082       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3083       cu_list += 2 * 8;
3084
3085       dwarf2_per_cu_data *the_cu
3086         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3087                           struct dwarf2_per_cu_data);
3088       the_cu->sect_off = sect_off;
3089       the_cu->length = length;
3090       the_cu->objfile = objfile;
3091       the_cu->section = section;
3092       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3093                                         struct dwarf2_per_cu_quick_data);
3094       the_cu->is_dwz = is_dwz;
3095       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3096     }
3097 }
3098
3099 /* Read the CU list from the mapped index, and use it to create all
3100    the CU objects for this objfile.  */
3101
3102 static void
3103 create_cus_from_index (struct objfile *objfile,
3104                        const gdb_byte *cu_list, offset_type cu_list_elements,
3105                        const gdb_byte *dwz_list, offset_type dwz_elements)
3106 {
3107   struct dwz_file *dwz;
3108
3109   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3110   dwarf2_per_objfile->all_comp_units =
3111     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3112                dwarf2_per_objfile->n_comp_units);
3113
3114   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3115                               &dwarf2_per_objfile->info, 0, 0);
3116
3117   if (dwz_elements == 0)
3118     return;
3119
3120   dwz = dwarf2_get_dwz_file ();
3121   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3122                               cu_list_elements / 2);
3123 }
3124
3125 /* Create the signatured type hash table from the index.  */
3126
3127 static void
3128 create_signatured_type_table_from_index (struct objfile *objfile,
3129                                          struct dwarf2_section_info *section,
3130                                          const gdb_byte *bytes,
3131                                          offset_type elements)
3132 {
3133   offset_type i;
3134   htab_t sig_types_hash;
3135
3136   dwarf2_per_objfile->n_type_units
3137     = dwarf2_per_objfile->n_allocated_type_units
3138     = elements / 3;
3139   dwarf2_per_objfile->all_type_units =
3140     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3141
3142   sig_types_hash = allocate_signatured_type_table (objfile);
3143
3144   for (i = 0; i < elements; i += 3)
3145     {
3146       struct signatured_type *sig_type;
3147       ULONGEST signature;
3148       void **slot;
3149       cu_offset type_offset_in_tu;
3150
3151       gdb_static_assert (sizeof (ULONGEST) >= 8);
3152       sect_offset sect_off
3153         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3154       type_offset_in_tu
3155         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3156                                                 BFD_ENDIAN_LITTLE);
3157       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3158       bytes += 3 * 8;
3159
3160       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3161                                  struct signatured_type);
3162       sig_type->signature = signature;
3163       sig_type->type_offset_in_tu = type_offset_in_tu;
3164       sig_type->per_cu.is_debug_types = 1;
3165       sig_type->per_cu.section = section;
3166       sig_type->per_cu.sect_off = sect_off;
3167       sig_type->per_cu.objfile = objfile;
3168       sig_type->per_cu.v.quick
3169         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3170                           struct dwarf2_per_cu_quick_data);
3171
3172       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3173       *slot = sig_type;
3174
3175       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3176     }
3177
3178   dwarf2_per_objfile->signatured_types = sig_types_hash;
3179 }
3180
3181 /* Read the address map data from the mapped index, and use it to
3182    populate the objfile's psymtabs_addrmap.  */
3183
3184 static void
3185 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3186 {
3187   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3188   const gdb_byte *iter, *end;
3189   struct addrmap *mutable_map;
3190   CORE_ADDR baseaddr;
3191
3192   auto_obstack temp_obstack;
3193
3194   mutable_map = addrmap_create_mutable (&temp_obstack);
3195
3196   iter = index->address_table;
3197   end = iter + index->address_table_size;
3198
3199   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3200
3201   while (iter < end)
3202     {
3203       ULONGEST hi, lo, cu_index;
3204       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3205       iter += 8;
3206       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3207       iter += 8;
3208       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3209       iter += 4;
3210
3211       if (lo > hi)
3212         {
3213           complaint (&symfile_complaints,
3214                      _(".gdb_index address table has invalid range (%s - %s)"),
3215                      hex_string (lo), hex_string (hi));
3216           continue;
3217         }
3218
3219       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3220         {
3221           complaint (&symfile_complaints,
3222                      _(".gdb_index address table has invalid CU number %u"),
3223                      (unsigned) cu_index);
3224           continue;
3225         }
3226
3227       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3228       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3229       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3230     }
3231
3232   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3233                                                     &objfile->objfile_obstack);
3234 }
3235
3236 /* The hash function for strings in the mapped index.  This is the same as
3237    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3238    implementation.  This is necessary because the hash function is tied to the
3239    format of the mapped index file.  The hash values do not have to match with
3240    SYMBOL_HASH_NEXT.
3241    
3242    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3243
3244 static hashval_t
3245 mapped_index_string_hash (int index_version, const void *p)
3246 {
3247   const unsigned char *str = (const unsigned char *) p;
3248   hashval_t r = 0;
3249   unsigned char c;
3250
3251   while ((c = *str++) != 0)
3252     {
3253       if (index_version >= 5)
3254         c = tolower (c);
3255       r = r * 67 + c - 113;
3256     }
3257
3258   return r;
3259 }
3260
3261 /* Find a slot in the mapped index INDEX for the object named NAME.
3262    If NAME is found, set *VEC_OUT to point to the CU vector in the
3263    constant pool and return true.  If NAME cannot be found, return
3264    false.  */
3265
3266 static bool
3267 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3268                           offset_type **vec_out)
3269 {
3270   offset_type hash;
3271   offset_type slot, step;
3272   int (*cmp) (const char *, const char *);
3273
3274   gdb::unique_xmalloc_ptr<char> without_params;
3275   if (current_language->la_language == language_cplus
3276       || current_language->la_language == language_fortran
3277       || current_language->la_language == language_d)
3278     {
3279       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3280          not contain any.  */
3281
3282       if (strchr (name, '(') != NULL)
3283         {
3284           without_params = cp_remove_params (name);
3285
3286           if (without_params != NULL)
3287             name = without_params.get ();
3288         }
3289     }
3290
3291   /* Index version 4 did not support case insensitive searches.  But the
3292      indices for case insensitive languages are built in lowercase, therefore
3293      simulate our NAME being searched is also lowercased.  */
3294   hash = mapped_index_string_hash ((index->version == 4
3295                                     && case_sensitivity == case_sensitive_off
3296                                     ? 5 : index->version),
3297                                    name);
3298
3299   slot = hash & (index->symbol_table_slots - 1);
3300   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3301   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3302
3303   for (;;)
3304     {
3305       /* Convert a slot number to an offset into the table.  */
3306       offset_type i = 2 * slot;
3307       const char *str;
3308       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3309         return false;
3310
3311       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3312       if (!cmp (name, str))
3313         {
3314           *vec_out = (offset_type *) (index->constant_pool
3315                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3316           return true;
3317         }
3318
3319       slot = (slot + step) & (index->symbol_table_slots - 1);
3320     }
3321 }
3322
3323 /* A helper function that reads the .gdb_index from SECTION and fills
3324    in MAP.  FILENAME is the name of the file containing the section;
3325    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3326    ok to use deprecated sections.
3327
3328    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3329    out parameters that are filled in with information about the CU and
3330    TU lists in the section.
3331
3332    Returns 1 if all went well, 0 otherwise.  */
3333
3334 static int
3335 read_index_from_section (struct objfile *objfile,
3336                          const char *filename,
3337                          int deprecated_ok,
3338                          struct dwarf2_section_info *section,
3339                          struct mapped_index *map,
3340                          const gdb_byte **cu_list,
3341                          offset_type *cu_list_elements,
3342                          const gdb_byte **types_list,
3343                          offset_type *types_list_elements)
3344 {
3345   const gdb_byte *addr;
3346   offset_type version;
3347   offset_type *metadata;
3348   int i;
3349
3350   if (dwarf2_section_empty_p (section))
3351     return 0;
3352
3353   /* Older elfutils strip versions could keep the section in the main
3354      executable while splitting it for the separate debug info file.  */
3355   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3356     return 0;
3357
3358   dwarf2_read_section (objfile, section);
3359
3360   addr = section->buffer;
3361   /* Version check.  */
3362   version = MAYBE_SWAP (*(offset_type *) addr);
3363   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3364      causes the index to behave very poorly for certain requests.  Version 3
3365      contained incomplete addrmap.  So, it seems better to just ignore such
3366      indices.  */
3367   if (version < 4)
3368     {
3369       static int warning_printed = 0;
3370       if (!warning_printed)
3371         {
3372           warning (_("Skipping obsolete .gdb_index section in %s."),
3373                    filename);
3374           warning_printed = 1;
3375         }
3376       return 0;
3377     }
3378   /* Index version 4 uses a different hash function than index version
3379      5 and later.
3380
3381      Versions earlier than 6 did not emit psymbols for inlined
3382      functions.  Using these files will cause GDB not to be able to
3383      set breakpoints on inlined functions by name, so we ignore these
3384      indices unless the user has done
3385      "set use-deprecated-index-sections on".  */
3386   if (version < 6 && !deprecated_ok)
3387     {
3388       static int warning_printed = 0;
3389       if (!warning_printed)
3390         {
3391           warning (_("\
3392 Skipping deprecated .gdb_index section in %s.\n\
3393 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3394 to use the section anyway."),
3395                    filename);
3396           warning_printed = 1;
3397         }
3398       return 0;
3399     }
3400   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3401      of the TU (for symbols coming from TUs),
3402      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3403      Plus gold-generated indices can have duplicate entries for global symbols,
3404      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3405      These are just performance bugs, and we can't distinguish gdb-generated
3406      indices from gold-generated ones, so issue no warning here.  */
3407
3408   /* Indexes with higher version than the one supported by GDB may be no
3409      longer backward compatible.  */
3410   if (version > 8)
3411     return 0;
3412
3413   map->version = version;
3414   map->total_size = section->size;
3415
3416   metadata = (offset_type *) (addr + sizeof (offset_type));
3417
3418   i = 0;
3419   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3420   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3421                        / 8);
3422   ++i;
3423
3424   *types_list = addr + MAYBE_SWAP (metadata[i]);
3425   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3426                            - MAYBE_SWAP (metadata[i]))
3427                           / 8);
3428   ++i;
3429
3430   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3431   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3432                              - MAYBE_SWAP (metadata[i]));
3433   ++i;
3434
3435   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3436   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3437                               - MAYBE_SWAP (metadata[i]))
3438                              / (2 * sizeof (offset_type)));
3439   ++i;
3440
3441   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3442
3443   return 1;
3444 }
3445
3446
3447 /* Read the index file.  If everything went ok, initialize the "quick"
3448    elements of all the CUs and return 1.  Otherwise, return 0.  */
3449
3450 static int
3451 dwarf2_read_index (struct objfile *objfile)
3452 {
3453   struct mapped_index local_map, *map;
3454   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3455   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3456   struct dwz_file *dwz;
3457
3458   if (!read_index_from_section (objfile, objfile_name (objfile),
3459                                 use_deprecated_index_sections,
3460                                 &dwarf2_per_objfile->gdb_index, &local_map,
3461                                 &cu_list, &cu_list_elements,
3462                                 &types_list, &types_list_elements))
3463     return 0;
3464
3465   /* Don't use the index if it's empty.  */
3466   if (local_map.symbol_table_slots == 0)
3467     return 0;
3468
3469   /* If there is a .dwz file, read it so we can get its CU list as
3470      well.  */
3471   dwz = dwarf2_get_dwz_file ();
3472   if (dwz != NULL)
3473     {
3474       struct mapped_index dwz_map;
3475       const gdb_byte *dwz_types_ignore;
3476       offset_type dwz_types_elements_ignore;
3477
3478       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3479                                     1,
3480                                     &dwz->gdb_index, &dwz_map,
3481                                     &dwz_list, &dwz_list_elements,
3482                                     &dwz_types_ignore,
3483                                     &dwz_types_elements_ignore))
3484         {
3485           warning (_("could not read '.gdb_index' section from %s; skipping"),
3486                    bfd_get_filename (dwz->dwz_bfd));
3487           return 0;
3488         }
3489     }
3490
3491   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3492                          dwz_list_elements);
3493
3494   if (types_list_elements)
3495     {
3496       struct dwarf2_section_info *section;
3497
3498       /* We can only handle a single .debug_types when we have an
3499          index.  */
3500       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3501         return 0;
3502
3503       section = VEC_index (dwarf2_section_info_def,
3504                            dwarf2_per_objfile->types, 0);
3505
3506       create_signatured_type_table_from_index (objfile, section, types_list,
3507                                                types_list_elements);
3508     }
3509
3510   create_addrmap_from_index (objfile, &local_map);
3511
3512   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3513   map = new (map) mapped_index ();
3514   *map = local_map;
3515
3516   dwarf2_per_objfile->index_table = map;
3517   dwarf2_per_objfile->using_index = 1;
3518   dwarf2_per_objfile->quick_file_names_table =
3519     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3520
3521   return 1;
3522 }
3523
3524 /* A helper for the "quick" functions which sets the global
3525    dwarf2_per_objfile according to OBJFILE.  */
3526
3527 static void
3528 dw2_setup (struct objfile *objfile)
3529 {
3530   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3531                         objfile_data (objfile, dwarf2_objfile_data_key));
3532   gdb_assert (dwarf2_per_objfile);
3533 }
3534
3535 /* die_reader_func for dw2_get_file_names.  */
3536
3537 static void
3538 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3539                            const gdb_byte *info_ptr,
3540                            struct die_info *comp_unit_die,
3541                            int has_children,
3542                            void *data)
3543 {
3544   struct dwarf2_cu *cu = reader->cu;
3545   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3546   struct objfile *objfile = dwarf2_per_objfile->objfile;
3547   struct dwarf2_per_cu_data *lh_cu;
3548   struct attribute *attr;
3549   int i;
3550   void **slot;
3551   struct quick_file_names *qfn;
3552
3553   gdb_assert (! this_cu->is_debug_types);
3554
3555   /* Our callers never want to match partial units -- instead they
3556      will match the enclosing full CU.  */
3557   if (comp_unit_die->tag == DW_TAG_partial_unit)
3558     {
3559       this_cu->v.quick->no_file_data = 1;
3560       return;
3561     }
3562
3563   lh_cu = this_cu;
3564   slot = NULL;
3565
3566   line_header_up lh;
3567   sect_offset line_offset {};
3568
3569   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3570   if (attr)
3571     {
3572       struct quick_file_names find_entry;
3573
3574       line_offset = (sect_offset) DW_UNSND (attr);
3575
3576       /* We may have already read in this line header (TU line header sharing).
3577          If we have we're done.  */
3578       find_entry.hash.dwo_unit = cu->dwo_unit;
3579       find_entry.hash.line_sect_off = line_offset;
3580       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3581                              &find_entry, INSERT);
3582       if (*slot != NULL)
3583         {
3584           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3585           return;
3586         }
3587
3588       lh = dwarf_decode_line_header (line_offset, cu);
3589     }
3590   if (lh == NULL)
3591     {
3592       lh_cu->v.quick->no_file_data = 1;
3593       return;
3594     }
3595
3596   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3597   qfn->hash.dwo_unit = cu->dwo_unit;
3598   qfn->hash.line_sect_off = line_offset;
3599   gdb_assert (slot != NULL);
3600   *slot = qfn;
3601
3602   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3603
3604   qfn->num_file_names = lh->file_names.size ();
3605   qfn->file_names =
3606     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3607   for (i = 0; i < lh->file_names.size (); ++i)
3608     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3609   qfn->real_names = NULL;
3610
3611   lh_cu->v.quick->file_names = qfn;
3612 }
3613
3614 /* A helper for the "quick" functions which attempts to read the line
3615    table for THIS_CU.  */
3616
3617 static struct quick_file_names *
3618 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3619 {
3620   /* This should never be called for TUs.  */
3621   gdb_assert (! this_cu->is_debug_types);
3622   /* Nor type unit groups.  */
3623   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3624
3625   if (this_cu->v.quick->file_names != NULL)
3626     return this_cu->v.quick->file_names;
3627   /* If we know there is no line data, no point in looking again.  */
3628   if (this_cu->v.quick->no_file_data)
3629     return NULL;
3630
3631   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3632
3633   if (this_cu->v.quick->no_file_data)
3634     return NULL;
3635   return this_cu->v.quick->file_names;
3636 }
3637
3638 /* A helper for the "quick" functions which computes and caches the
3639    real path for a given file name from the line table.  */
3640
3641 static const char *
3642 dw2_get_real_path (struct objfile *objfile,
3643                    struct quick_file_names *qfn, int index)
3644 {
3645   if (qfn->real_names == NULL)
3646     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3647                                       qfn->num_file_names, const char *);
3648
3649   if (qfn->real_names[index] == NULL)
3650     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3651
3652   return qfn->real_names[index];
3653 }
3654
3655 static struct symtab *
3656 dw2_find_last_source_symtab (struct objfile *objfile)
3657 {
3658   struct compunit_symtab *cust;
3659   int index;
3660
3661   dw2_setup (objfile);
3662   index = dwarf2_per_objfile->n_comp_units - 1;
3663   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3664   if (cust == NULL)
3665     return NULL;
3666   return compunit_primary_filetab (cust);
3667 }
3668
3669 /* Traversal function for dw2_forget_cached_source_info.  */
3670
3671 static int
3672 dw2_free_cached_file_names (void **slot, void *info)
3673 {
3674   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3675
3676   if (file_data->real_names)
3677     {
3678       int i;
3679
3680       for (i = 0; i < file_data->num_file_names; ++i)
3681         {
3682           xfree ((void*) file_data->real_names[i]);
3683           file_data->real_names[i] = NULL;
3684         }
3685     }
3686
3687   return 1;
3688 }
3689
3690 static void
3691 dw2_forget_cached_source_info (struct objfile *objfile)
3692 {
3693   dw2_setup (objfile);
3694
3695   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3696                           dw2_free_cached_file_names, NULL);
3697 }
3698
3699 /* Helper function for dw2_map_symtabs_matching_filename that expands
3700    the symtabs and calls the iterator.  */
3701
3702 static int
3703 dw2_map_expand_apply (struct objfile *objfile,
3704                       struct dwarf2_per_cu_data *per_cu,
3705                       const char *name, const char *real_path,
3706                       gdb::function_view<bool (symtab *)> callback)
3707 {
3708   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3709
3710   /* Don't visit already-expanded CUs.  */
3711   if (per_cu->v.quick->compunit_symtab)
3712     return 0;
3713
3714   /* This may expand more than one symtab, and we want to iterate over
3715      all of them.  */
3716   dw2_instantiate_symtab (per_cu);
3717
3718   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3719                                     last_made, callback);
3720 }
3721
3722 /* Implementation of the map_symtabs_matching_filename method.  */
3723
3724 static bool
3725 dw2_map_symtabs_matching_filename
3726   (struct objfile *objfile, const char *name, const char *real_path,
3727    gdb::function_view<bool (symtab *)> callback)
3728 {
3729   int i;
3730   const char *name_basename = lbasename (name);
3731
3732   dw2_setup (objfile);
3733
3734   /* The rule is CUs specify all the files, including those used by
3735      any TU, so there's no need to scan TUs here.  */
3736
3737   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3738     {
3739       int j;
3740       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3741       struct quick_file_names *file_data;
3742
3743       /* We only need to look at symtabs not already expanded.  */
3744       if (per_cu->v.quick->compunit_symtab)
3745         continue;
3746
3747       file_data = dw2_get_file_names (per_cu);
3748       if (file_data == NULL)
3749         continue;
3750
3751       for (j = 0; j < file_data->num_file_names; ++j)
3752         {
3753           const char *this_name = file_data->file_names[j];
3754           const char *this_real_name;
3755
3756           if (compare_filenames_for_search (this_name, name))
3757             {
3758               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3759                                         callback))
3760                 return true;
3761               continue;
3762             }
3763
3764           /* Before we invoke realpath, which can get expensive when many
3765              files are involved, do a quick comparison of the basenames.  */
3766           if (! basenames_may_differ
3767               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3768             continue;
3769
3770           this_real_name = dw2_get_real_path (objfile, file_data, j);
3771           if (compare_filenames_for_search (this_real_name, name))
3772             {
3773               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3774                                         callback))
3775                 return true;
3776               continue;
3777             }
3778
3779           if (real_path != NULL)
3780             {
3781               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3782               gdb_assert (IS_ABSOLUTE_PATH (name));
3783               if (this_real_name != NULL
3784                   && FILENAME_CMP (real_path, this_real_name) == 0)
3785                 {
3786                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3787                                             callback))
3788                     return true;
3789                   continue;
3790                 }
3791             }
3792         }
3793     }
3794
3795   return false;
3796 }
3797
3798 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3799
3800 struct dw2_symtab_iterator
3801 {
3802   /* The internalized form of .gdb_index.  */
3803   struct mapped_index *index;
3804   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3805   int want_specific_block;
3806   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3807      Unused if !WANT_SPECIFIC_BLOCK.  */
3808   int block_index;
3809   /* The kind of symbol we're looking for.  */
3810   domain_enum domain;
3811   /* The list of CUs from the index entry of the symbol,
3812      or NULL if not found.  */
3813   offset_type *vec;
3814   /* The next element in VEC to look at.  */
3815   int next;
3816   /* The number of elements in VEC, or zero if there is no match.  */
3817   int length;
3818   /* Have we seen a global version of the symbol?
3819      If so we can ignore all further global instances.
3820      This is to work around gold/15646, inefficient gold-generated
3821      indices.  */
3822   int global_seen;
3823 };
3824
3825 /* Initialize the index symtab iterator ITER.
3826    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3827    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3828
3829 static void
3830 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3831                       struct mapped_index *index,
3832                       int want_specific_block,
3833                       int block_index,
3834                       domain_enum domain,
3835                       const char *name)
3836 {
3837   iter->index = index;
3838   iter->want_specific_block = want_specific_block;
3839   iter->block_index = block_index;
3840   iter->domain = domain;
3841   iter->next = 0;
3842   iter->global_seen = 0;
3843
3844   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3845     iter->length = MAYBE_SWAP (*iter->vec);
3846   else
3847     {
3848       iter->vec = NULL;
3849       iter->length = 0;
3850     }
3851 }
3852
3853 /* Return the next matching CU or NULL if there are no more.  */
3854
3855 static struct dwarf2_per_cu_data *
3856 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3857 {
3858   for ( ; iter->next < iter->length; ++iter->next)
3859     {
3860       offset_type cu_index_and_attrs =
3861         MAYBE_SWAP (iter->vec[iter->next + 1]);
3862       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3863       struct dwarf2_per_cu_data *per_cu;
3864       int want_static = iter->block_index != GLOBAL_BLOCK;
3865       /* This value is only valid for index versions >= 7.  */
3866       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3867       gdb_index_symbol_kind symbol_kind =
3868         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3869       /* Only check the symbol attributes if they're present.
3870          Indices prior to version 7 don't record them,
3871          and indices >= 7 may elide them for certain symbols
3872          (gold does this).  */
3873       int attrs_valid =
3874         (iter->index->version >= 7
3875          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3876
3877       /* Don't crash on bad data.  */
3878       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3879                        + dwarf2_per_objfile->n_type_units))
3880         {
3881           complaint (&symfile_complaints,
3882                      _(".gdb_index entry has bad CU index"
3883                        " [in module %s]"),
3884                      objfile_name (dwarf2_per_objfile->objfile));
3885           continue;
3886         }
3887
3888       per_cu = dw2_get_cutu (cu_index);
3889
3890       /* Skip if already read in.  */
3891       if (per_cu->v.quick->compunit_symtab)
3892         continue;
3893
3894       /* Check static vs global.  */
3895       if (attrs_valid)
3896         {
3897           if (iter->want_specific_block
3898               && want_static != is_static)
3899             continue;
3900           /* Work around gold/15646.  */
3901           if (!is_static && iter->global_seen)
3902             continue;
3903           if (!is_static)
3904             iter->global_seen = 1;
3905         }
3906
3907       /* Only check the symbol's kind if it has one.  */
3908       if (attrs_valid)
3909         {
3910           switch (iter->domain)
3911             {
3912             case VAR_DOMAIN:
3913               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3914                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3915                   /* Some types are also in VAR_DOMAIN.  */
3916                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3917                 continue;
3918               break;
3919             case STRUCT_DOMAIN:
3920               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3921                 continue;
3922               break;
3923             case LABEL_DOMAIN:
3924               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3925                 continue;
3926               break;
3927             default:
3928               break;
3929             }
3930         }
3931
3932       ++iter->next;
3933       return per_cu;
3934     }
3935
3936   return NULL;
3937 }
3938
3939 static struct compunit_symtab *
3940 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3941                    const char *name, domain_enum domain)
3942 {
3943   struct compunit_symtab *stab_best = NULL;
3944   struct mapped_index *index;
3945
3946   dw2_setup (objfile);
3947
3948   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3949
3950   index = dwarf2_per_objfile->index_table;
3951
3952   /* index is NULL if OBJF_READNOW.  */
3953   if (index)
3954     {
3955       struct dw2_symtab_iterator iter;
3956       struct dwarf2_per_cu_data *per_cu;
3957
3958       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3959
3960       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3961         {
3962           struct symbol *sym, *with_opaque = NULL;
3963           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3964           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3965           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3966
3967           sym = block_find_symbol (block, name, domain,
3968                                    block_find_non_opaque_type_preferred,
3969                                    &with_opaque);
3970
3971           /* Some caution must be observed with overloaded functions
3972              and methods, since the index will not contain any overload
3973              information (but NAME might contain it).  */
3974
3975           if (sym != NULL
3976               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3977             return stab;
3978           if (with_opaque != NULL
3979               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3980             stab_best = stab;
3981
3982           /* Keep looking through other CUs.  */
3983         }
3984     }
3985
3986   return stab_best;
3987 }
3988
3989 static void
3990 dw2_print_stats (struct objfile *objfile)
3991 {
3992   int i, total, count;
3993
3994   dw2_setup (objfile);
3995   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3996   count = 0;
3997   for (i = 0; i < total; ++i)
3998     {
3999       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4000
4001       if (!per_cu->v.quick->compunit_symtab)
4002         ++count;
4003     }
4004   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4005   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4006 }
4007
4008 /* This dumps minimal information about the index.
4009    It is called via "mt print objfiles".
4010    One use is to verify .gdb_index has been loaded by the
4011    gdb.dwarf2/gdb-index.exp testcase.  */
4012
4013 static void
4014 dw2_dump (struct objfile *objfile)
4015 {
4016   dw2_setup (objfile);
4017   gdb_assert (dwarf2_per_objfile->using_index);
4018   printf_filtered (".gdb_index:");
4019   if (dwarf2_per_objfile->index_table != NULL)
4020     {
4021       printf_filtered (" version %d\n",
4022                        dwarf2_per_objfile->index_table->version);
4023     }
4024   else
4025     printf_filtered (" faked for \"readnow\"\n");
4026   printf_filtered ("\n");
4027 }
4028
4029 static void
4030 dw2_relocate (struct objfile *objfile,
4031               const struct section_offsets *new_offsets,
4032               const struct section_offsets *delta)
4033 {
4034   /* There's nothing to relocate here.  */
4035 }
4036
4037 static void
4038 dw2_expand_symtabs_for_function (struct objfile *objfile,
4039                                  const char *func_name)
4040 {
4041   struct mapped_index *index;
4042
4043   dw2_setup (objfile);
4044
4045   index = dwarf2_per_objfile->index_table;
4046
4047   /* index is NULL if OBJF_READNOW.  */
4048   if (index)
4049     {
4050       struct dw2_symtab_iterator iter;
4051       struct dwarf2_per_cu_data *per_cu;
4052
4053       /* Note: It doesn't matter what we pass for block_index here.  */
4054       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4055                             func_name);
4056
4057       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4058         dw2_instantiate_symtab (per_cu);
4059     }
4060 }
4061
4062 static void
4063 dw2_expand_all_symtabs (struct objfile *objfile)
4064 {
4065   int i;
4066
4067   dw2_setup (objfile);
4068
4069   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4070                    + dwarf2_per_objfile->n_type_units); ++i)
4071     {
4072       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4073
4074       dw2_instantiate_symtab (per_cu);
4075     }
4076 }
4077
4078 static void
4079 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4080                                   const char *fullname)
4081 {
4082   int i;
4083
4084   dw2_setup (objfile);
4085
4086   /* We don't need to consider type units here.
4087      This is only called for examining code, e.g. expand_line_sal.
4088      There can be an order of magnitude (or more) more type units
4089      than comp units, and we avoid them if we can.  */
4090
4091   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4092     {
4093       int j;
4094       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4095       struct quick_file_names *file_data;
4096
4097       /* We only need to look at symtabs not already expanded.  */
4098       if (per_cu->v.quick->compunit_symtab)
4099         continue;
4100
4101       file_data = dw2_get_file_names (per_cu);
4102       if (file_data == NULL)
4103         continue;
4104
4105       for (j = 0; j < file_data->num_file_names; ++j)
4106         {
4107           const char *this_fullname = file_data->file_names[j];
4108
4109           if (filename_cmp (this_fullname, fullname) == 0)
4110             {
4111               dw2_instantiate_symtab (per_cu);
4112               break;
4113             }
4114         }
4115     }
4116 }
4117
4118 static void
4119 dw2_map_matching_symbols (struct objfile *objfile,
4120                           const char * name, domain_enum domain,
4121                           int global,
4122                           int (*callback) (struct block *,
4123                                            struct symbol *, void *),
4124                           void *data, symbol_name_match_type match,
4125                           symbol_compare_ftype *ordered_compare)
4126 {
4127   /* Currently unimplemented; used for Ada.  The function can be called if the
4128      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4129      does not look for non-Ada symbols this function should just return.  */
4130 }
4131
4132 /* Symbol name matcher for .gdb_index names.
4133
4134    Symbol names in .gdb_index have a few particularities:
4135
4136    - There's no indication of which is the language of each symbol.
4137
4138      Since each language has its own symbol name matching algorithm,
4139      and we don't know which language is the right one, we must match
4140      each symbol against all languages.  This would be a potential
4141      performance problem if it were not mitigated by the
4142      mapped_index::name_components lookup table, which significantly
4143      reduces the number of times we need to call into this matcher,
4144      making it a non-issue.
4145
4146    - Symbol names in the index have no overload (parameter)
4147      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4148      appear as "foo" in the index, for example.
4149
4150      This means that the lookup names passed to the symbol name
4151      matcher functions must have no parameter information either
4152      because (e.g.) symbol search name "foo" does not match
4153      lookup-name "foo(int)" [while swapping search name for lookup
4154      name would match].
4155 */
4156 class gdb_index_symbol_name_matcher
4157 {
4158 public:
4159   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4160   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4161
4162   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4163      Returns true if any matcher matches.  */
4164   bool matches (const char *symbol_name);
4165
4166 private:
4167   /* A reference to the lookup name we're matching against.  */
4168   const lookup_name_info &m_lookup_name;
4169
4170   /* A vector holding all the different symbol name matchers, for all
4171      languages.  */
4172   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4173 };
4174
4175 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4176   (const lookup_name_info &lookup_name)
4177     : m_lookup_name (lookup_name)
4178 {
4179   /* Prepare the vector of comparison functions upfront, to avoid
4180      doing the same work for each symbol.  Care is taken to avoid
4181      matching with the same matcher more than once if/when multiple
4182      languages use the same matcher function.  */
4183   auto &matchers = m_symbol_name_matcher_funcs;
4184   matchers.reserve (nr_languages);
4185
4186   matchers.push_back (default_symbol_name_matcher);
4187
4188   for (int i = 0; i < nr_languages; i++)
4189     {
4190       const language_defn *lang = language_def ((enum language) i);
4191       if (lang->la_get_symbol_name_matcher != NULL)
4192         {
4193           symbol_name_matcher_ftype *name_matcher
4194             = lang->la_get_symbol_name_matcher (m_lookup_name);
4195
4196           /* Don't insert the same comparison routine more than once.
4197              Note that we do this linear walk instead of a cheaper
4198              sorted insert, or use a std::set or something like that,
4199              because relative order of function addresses is not
4200              stable.  This is not a problem in practice because the
4201              number of supported languages is low, and the cost here
4202              is tiny compared to the number of searches we'll do
4203              afterwards using this object.  */
4204           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4205               == matchers.end ())
4206             matchers.push_back (name_matcher);
4207         }
4208     }
4209 }
4210
4211 bool
4212 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4213 {
4214   for (auto matches_name : m_symbol_name_matcher_funcs)
4215     if (matches_name (symbol_name, m_lookup_name, NULL))
4216       return true;
4217
4218   return false;
4219 }
4220
4221 /* Starting from a search name, return the string that finds the upper
4222    bound of all strings that start with SEARCH_NAME in a sorted name
4223    list.  Returns the empty string to indicate that the upper bound is
4224    the end of the list.  */
4225
4226 static std::string
4227 make_sort_after_prefix_name (const char *search_name)
4228 {
4229   /* When looking to complete "func", we find the upper bound of all
4230      symbols that start with "func" by looking for where we'd insert
4231      the closest string that would follow "func" in lexicographical
4232      order.  Usually, that's "func"-with-last-character-incremented,
4233      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4234      will be UTF-8 multi-byte sequences, but we can't be certain.
4235      Especially mind the 0xff character, which is a valid character in
4236      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4237      rule out compilers allowing it in identifiers.  Note that
4238      conveniently, strcmp/strcasecmp are specified to compare
4239      characters interpreted as unsigned char.  So what we do is treat
4240      the whole string as a base 256 number composed of a sequence of
4241      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4242      to 0, and carries 1 to the following more-significant position.
4243      If the very first character in SEARCH_NAME ends up incremented
4244      and carries/overflows, then the upper bound is the end of the
4245      list.  The string after the empty string is also the empty
4246      string.
4247
4248      Some examples of this operation:
4249
4250        SEARCH_NAME  => "+1" RESULT
4251
4252        "abc"              => "abd"
4253        "ab\xff"           => "ac"
4254        "\xff" "a" "\xff"  => "\xff" "b"
4255        "\xff"             => ""
4256        "\xff\xff"         => ""
4257        ""                 => ""
4258
4259      Then, with these symbols for example:
4260
4261       func
4262       func1
4263       fund
4264
4265      completing "func" looks for symbols between "func" and
4266      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4267      which finds "func" and "func1", but not "fund".
4268
4269      And with:
4270
4271       funcÿ     (Latin1 'ÿ' [0xff])
4272       funcÿ1
4273       fund
4274
4275      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4276      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4277
4278      And with:
4279
4280       ÿÿ        (Latin1 'ÿ' [0xff])
4281       ÿÿ1
4282
4283      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4284      the end of the list.
4285   */
4286   std::string after = search_name;
4287   while (!after.empty () && (unsigned char) after.back () == 0xff)
4288     after.pop_back ();
4289   if (!after.empty ())
4290     after.back () = (unsigned char) after.back () + 1;
4291   return after;
4292 }
4293
4294 /* See declaration.  */
4295
4296 std::pair<std::vector<name_component>::const_iterator,
4297           std::vector<name_component>::const_iterator>
4298 mapped_index::find_name_components_bounds
4299   (const lookup_name_info &lookup_name_without_params) const
4300 {
4301   auto *name_cmp
4302     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4303
4304   const char *cplus
4305     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4306
4307   /* Comparison function object for lower_bound that matches against a
4308      given symbol name.  */
4309   auto lookup_compare_lower = [&] (const name_component &elem,
4310                                    const char *name)
4311     {
4312       const char *elem_qualified = this->symbol_name_at (elem.idx);
4313       const char *elem_name = elem_qualified + elem.name_offset;
4314       return name_cmp (elem_name, name) < 0;
4315     };
4316
4317   /* Comparison function object for upper_bound that matches against a
4318      given symbol name.  */
4319   auto lookup_compare_upper = [&] (const char *name,
4320                                    const name_component &elem)
4321     {
4322       const char *elem_qualified = this->symbol_name_at (elem.idx);
4323       const char *elem_name = elem_qualified + elem.name_offset;
4324       return name_cmp (name, elem_name) < 0;
4325     };
4326
4327   auto begin = this->name_components.begin ();
4328   auto end = this->name_components.end ();
4329
4330   /* Find the lower bound.  */
4331   auto lower = [&] ()
4332     {
4333       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4334         return begin;
4335       else
4336         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4337     } ();
4338
4339   /* Find the upper bound.  */
4340   auto upper = [&] ()
4341     {
4342       if (lookup_name_without_params.completion_mode ())
4343         {
4344           /* In completion mode, we want UPPER to point past all
4345              symbols names that have the same prefix.  I.e., with
4346              these symbols, and completing "func":
4347
4348               function        << lower bound
4349               function1
4350               other_function  << upper bound
4351
4352              We find the upper bound by looking for the insertion
4353              point of "func"-with-last-character-incremented,
4354              i.e. "fund".  */
4355           std::string after = make_sort_after_prefix_name (cplus);
4356           if (after.empty ())
4357             return end;
4358           return std::lower_bound (lower, end, after.c_str (),
4359                                    lookup_compare_lower);
4360         }
4361       else
4362         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4363     } ();
4364
4365   return {lower, upper};
4366 }
4367
4368 /* See declaration.  */
4369
4370 void
4371 mapped_index::build_name_components ()
4372 {
4373   if (!this->name_components.empty ())
4374     return;
4375
4376   this->name_components_casing = case_sensitivity;
4377   auto *name_cmp
4378     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4379
4380   /* The code below only knows how to break apart components of C++
4381      symbol names (and other languages that use '::' as
4382      namespace/module separator).  If we add support for wild matching
4383      to some language that uses some other operator (E.g., Ada, Go and
4384      D use '.'), then we'll need to try splitting the symbol name
4385      according to that language too.  Note that Ada does support wild
4386      matching, but doesn't currently support .gdb_index.  */
4387   for (size_t iter = 0; iter < this->symbol_table_slots; ++iter)
4388     {
4389       offset_type idx = 2 * iter;
4390
4391       if (this->symbol_table[idx] == 0
4392           && this->symbol_table[idx + 1] == 0)
4393         continue;
4394
4395       const char *name = this->symbol_name_at (idx);
4396
4397       /* Add each name component to the name component table.  */
4398       unsigned int previous_len = 0;
4399       for (unsigned int current_len = cp_find_first_component (name);
4400            name[current_len] != '\0';
4401            current_len += cp_find_first_component (name + current_len))
4402         {
4403           gdb_assert (name[current_len] == ':');
4404           this->name_components.push_back ({previous_len, idx});
4405           /* Skip the '::'.  */
4406           current_len += 2;
4407           previous_len = current_len;
4408         }
4409       this->name_components.push_back ({previous_len, idx});
4410     }
4411
4412   /* Sort name_components elements by name.  */
4413   auto name_comp_compare = [&] (const name_component &left,
4414                                 const name_component &right)
4415     {
4416       const char *left_qualified = this->symbol_name_at (left.idx);
4417       const char *right_qualified = this->symbol_name_at (right.idx);
4418
4419       const char *left_name = left_qualified + left.name_offset;
4420       const char *right_name = right_qualified + right.name_offset;
4421
4422       return name_cmp (left_name, right_name) < 0;
4423     };
4424
4425   std::sort (this->name_components.begin (),
4426              this->name_components.end (),
4427              name_comp_compare);
4428 }
4429
4430 /* Helper for dw2_expand_symtabs_matching that works with a
4431    mapped_index instead of the containing objfile.  This is split to a
4432    separate function in order to be able to unit test the
4433    name_components matching using a mock mapped_index.  For each
4434    symbol name that matches, calls MATCH_CALLBACK, passing it the
4435    symbol's index in the mapped_index symbol table.  */
4436
4437 static void
4438 dw2_expand_symtabs_matching_symbol
4439   (mapped_index &index,
4440    const lookup_name_info &lookup_name_in,
4441    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4442    enum search_domain kind,
4443    gdb::function_view<void (offset_type)> match_callback)
4444 {
4445   lookup_name_info lookup_name_without_params
4446     = lookup_name_in.make_ignore_params ();
4447   gdb_index_symbol_name_matcher lookup_name_matcher
4448     (lookup_name_without_params);
4449
4450   /* Build the symbol name component sorted vector, if we haven't
4451      yet.  */
4452   index.build_name_components ();
4453
4454   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4455
4456   /* Now for each symbol name in range, check to see if we have a name
4457      match, and if so, call the MATCH_CALLBACK callback.  */
4458
4459   /* The same symbol may appear more than once in the range though.
4460      E.g., if we're looking for symbols that complete "w", and we have
4461      a symbol named "w1::w2", we'll find the two name components for
4462      that same symbol in the range.  To be sure we only call the
4463      callback once per symbol, we first collect the symbol name
4464      indexes that matched in a temporary vector and ignore
4465      duplicates.  */
4466   std::vector<offset_type> matches;
4467   matches.reserve (std::distance (bounds.first, bounds.second));
4468
4469   for (; bounds.first != bounds.second; ++bounds.first)
4470     {
4471       const char *qualified = index.symbol_name_at (bounds.first->idx);
4472
4473       if (!lookup_name_matcher.matches (qualified)
4474           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4475         continue;
4476
4477       matches.push_back (bounds.first->idx);
4478     }
4479
4480   std::sort (matches.begin (), matches.end ());
4481
4482   /* Finally call the callback, once per match.  */
4483   ULONGEST prev = -1;
4484   for (offset_type idx : matches)
4485     {
4486       if (prev != idx)
4487         {
4488           match_callback (idx);
4489           prev = idx;
4490         }
4491     }
4492
4493   /* Above we use a type wider than idx's for 'prev', since 0 and
4494      (offset_type)-1 are both possible values.  */
4495   static_assert (sizeof (prev) > sizeof (offset_type), "");
4496 }
4497
4498 #if GDB_SELF_TEST
4499
4500 namespace selftests { namespace dw2_expand_symtabs_matching {
4501
4502 /* A wrapper around mapped_index that builds a mock mapped_index, from
4503    the symbol list passed as parameter to the constructor.  */
4504 class mock_mapped_index
4505 {
4506 public:
4507   template<size_t N>
4508   mock_mapped_index (const char *(&symbols)[N])
4509     : mock_mapped_index (symbols, N)
4510   {}
4511
4512   /* Access the built index.  */
4513   mapped_index &index ()
4514   { return m_index; }
4515
4516   /* Disable copy.  */
4517   mock_mapped_index(const mock_mapped_index &) = delete;
4518   void operator= (const mock_mapped_index &) = delete;
4519
4520 private:
4521   mock_mapped_index (const char **symbols, size_t symbols_size)
4522   {
4523     /* No string can live at offset zero.  Add a dummy entry.  */
4524     obstack_grow_str0 (&m_constant_pool, "");
4525
4526     for (size_t i = 0; i < symbols_size; i++)
4527       {
4528         const char *sym = symbols[i];
4529         size_t offset = obstack_object_size (&m_constant_pool);
4530         obstack_grow_str0 (&m_constant_pool, sym);
4531         m_symbol_table.push_back (offset);
4532         m_symbol_table.push_back (0);
4533       };
4534
4535     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4536     m_index.symbol_table = m_symbol_table.data ();
4537     m_index.symbol_table_slots = m_symbol_table.size () / 2;
4538   }
4539
4540 public:
4541   /* The built mapped_index.  */
4542   mapped_index m_index{};
4543
4544   /* The storage that the built mapped_index uses for symbol and
4545      constant pool tables.  */
4546   std::vector<offset_type> m_symbol_table;
4547   auto_obstack m_constant_pool;
4548 };
4549
4550 /* Convenience function that converts a NULL pointer to a "<null>"
4551    string, to pass to print routines.  */
4552
4553 static const char *
4554 string_or_null (const char *str)
4555 {
4556   return str != NULL ? str : "<null>";
4557 }
4558
4559 /* Check if a lookup_name_info built from
4560    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4561    index.  EXPECTED_LIST is the list of expected matches, in expected
4562    matching order.  If no match expected, then an empty list is
4563    specified.  Returns true on success.  On failure prints a warning
4564    indicating the file:line that failed, and returns false.  */
4565
4566 static bool
4567 check_match (const char *file, int line,
4568              mock_mapped_index &mock_index,
4569              const char *name, symbol_name_match_type match_type,
4570              bool completion_mode,
4571              std::initializer_list<const char *> expected_list)
4572 {
4573   lookup_name_info lookup_name (name, match_type, completion_mode);
4574
4575   bool matched = true;
4576
4577   auto mismatch = [&] (const char *expected_str,
4578                        const char *got)
4579   {
4580     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4581                "expected=\"%s\", got=\"%s\"\n"),
4582              file, line,
4583              (match_type == symbol_name_match_type::FULL
4584               ? "FULL" : "WILD"),
4585              name, string_or_null (expected_str), string_or_null (got));
4586     matched = false;
4587   };
4588
4589   auto expected_it = expected_list.begin ();
4590   auto expected_end = expected_list.end ();
4591
4592   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4593                                       NULL, ALL_DOMAIN,
4594                                       [&] (offset_type idx)
4595   {
4596     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4597     const char *expected_str
4598       = expected_it == expected_end ? NULL : *expected_it++;
4599
4600     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4601       mismatch (expected_str, matched_name);
4602   });
4603
4604   const char *expected_str
4605   = expected_it == expected_end ? NULL : *expected_it++;
4606   if (expected_str != NULL)
4607     mismatch (expected_str, NULL);
4608
4609   return matched;
4610 }
4611
4612 /* The symbols added to the mock mapped_index for testing (in
4613    canonical form).  */
4614 static const char *test_symbols[] = {
4615   "function",
4616   "std::bar",
4617   "std::zfunction",
4618   "std::zfunction2",
4619   "w1::w2",
4620   "ns::foo<char*>",
4621   "ns::foo<int>",
4622   "ns::foo<long>",
4623   "ns2::tmpl<int>::foo2",
4624   "(anonymous namespace)::A::B::C",
4625
4626   /* These are used to check that the increment-last-char in the
4627      matching algorithm for completion doesn't match "t1_fund" when
4628      completing "t1_func".  */
4629   "t1_func",
4630   "t1_func1",
4631   "t1_fund",
4632   "t1_fund1",
4633
4634   /* A UTF-8 name with multi-byte sequences to make sure that
4635      cp-name-parser understands this as a single identifier ("função"
4636      is "function" in PT).  */
4637   u8"u8função",
4638
4639   /* \377 (0xff) is Latin1 'ÿ'.  */
4640   "yfunc\377",
4641
4642   /* \377 (0xff) is Latin1 'ÿ'.  */
4643   "\377",
4644   "\377\377123",
4645
4646   /* A name with all sorts of complications.  Starts with "z" to make
4647      it easier for the completion tests below.  */
4648 #define Z_SYM_NAME \
4649   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4650     "::tuple<(anonymous namespace)::ui*, " \
4651     "std::default_delete<(anonymous namespace)::ui>, void>"
4652
4653   Z_SYM_NAME
4654 };
4655
4656 /* Returns true if the mapped_index::find_name_component_bounds method
4657    finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME, in
4658    completion mode.  */
4659
4660 static bool
4661 check_find_bounds_finds (mapped_index &index,
4662                          const char *search_name,
4663                          gdb::array_view<const char *> expected_syms)
4664 {
4665   lookup_name_info lookup_name (search_name,
4666                                 symbol_name_match_type::FULL, true);
4667
4668   auto bounds = index.find_name_components_bounds (lookup_name);
4669
4670   size_t distance = std::distance (bounds.first, bounds.second);
4671   if (distance != expected_syms.size ())
4672     return false;
4673
4674   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4675     {
4676       auto nc_elem = bounds.first + exp_elem;
4677       const char *qualified = index.symbol_name_at (nc_elem->idx);
4678       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4679         return false;
4680     }
4681
4682   return true;
4683 }
4684
4685 /* Test the lower-level mapped_index::find_name_component_bounds
4686    method.  */
4687
4688 static void
4689 test_mapped_index_find_name_component_bounds ()
4690 {
4691   mock_mapped_index mock_index (test_symbols);
4692
4693   mock_index.index ().build_name_components ();
4694
4695   /* Test the lower-level mapped_index::find_name_component_bounds
4696      method in completion mode.  */
4697   {
4698     static const char *expected_syms[] = {
4699       "t1_func",
4700       "t1_func1",
4701     };
4702
4703     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4704                                          "t1_func", expected_syms));
4705   }
4706
4707   /* Check that the increment-last-char in the name matching algorithm
4708      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4709   {
4710     static const char *expected_syms1[] = {
4711       "\377",
4712       "\377\377123",
4713     };
4714     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4715                                          "\377", expected_syms1));
4716
4717     static const char *expected_syms2[] = {
4718       "\377\377123",
4719     };
4720     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4721                                          "\377\377", expected_syms2));
4722   }
4723 }
4724
4725 /* Test dw2_expand_symtabs_matching_symbol.  */
4726
4727 static void
4728 test_dw2_expand_symtabs_matching_symbol ()
4729 {
4730   mock_mapped_index mock_index (test_symbols);
4731
4732   /* We let all tests run until the end even if some fails, for debug
4733      convenience.  */
4734   bool any_mismatch = false;
4735
4736   /* Create the expected symbols list (an initializer_list).  Needed
4737      because lists have commas, and we need to pass them to CHECK,
4738      which is a macro.  */
4739 #define EXPECT(...) { __VA_ARGS__ }
4740
4741   /* Wrapper for check_match that passes down the current
4742      __FILE__/__LINE__.  */
4743 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4744   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4745                                 mock_index,                             \
4746                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4747                                 EXPECTED_LIST)
4748
4749   /* Identity checks.  */
4750   for (const char *sym : test_symbols)
4751     {
4752       /* Should be able to match all existing symbols.  */
4753       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4754                    EXPECT (sym));
4755
4756       /* Should be able to match all existing symbols with
4757          parameters.  */
4758       std::string with_params = std::string (sym) + "(int)";
4759       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4760                    EXPECT (sym));
4761
4762       /* Should be able to match all existing symbols with
4763          parameters and qualifiers.  */
4764       with_params = std::string (sym) + " ( int ) const";
4765       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4766                    EXPECT (sym));
4767
4768       /* This should really find sym, but cp-name-parser.y doesn't
4769          know about lvalue/rvalue qualifiers yet.  */
4770       with_params = std::string (sym) + " ( int ) &&";
4771       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4772                    {});
4773     }
4774
4775   /* Check that the name matching algorithm for completion doesn't get
4776      confused with Latin1 'ÿ' / 0xff.  */
4777   {
4778     static const char str[] = "\377";
4779     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4780                  EXPECT ("\377", "\377\377123"));
4781   }
4782
4783   /* Check that the increment-last-char in the matching algorithm for
4784      completion doesn't match "t1_fund" when completing "t1_func".  */
4785   {
4786     static const char str[] = "t1_func";
4787     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4788                  EXPECT ("t1_func", "t1_func1"));
4789   }
4790
4791   /* Check that completion mode works at each prefix of the expected
4792      symbol name.  */
4793   {
4794     static const char str[] = "function(int)";
4795     size_t len = strlen (str);
4796     std::string lookup;
4797
4798     for (size_t i = 1; i < len; i++)
4799       {
4800         lookup.assign (str, i);
4801         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4802                      EXPECT ("function"));
4803       }
4804   }
4805
4806   /* While "w" is a prefix of both components, the match function
4807      should still only be called once.  */
4808   {
4809     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4810                  EXPECT ("w1::w2"));
4811     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4812                  EXPECT ("w1::w2"));
4813   }
4814
4815   /* Same, with a "complicated" symbol.  */
4816   {
4817     static const char str[] = Z_SYM_NAME;
4818     size_t len = strlen (str);
4819     std::string lookup;
4820
4821     for (size_t i = 1; i < len; i++)
4822       {
4823         lookup.assign (str, i);
4824         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4825                      EXPECT (Z_SYM_NAME));
4826       }
4827   }
4828
4829   /* In FULL mode, an incomplete symbol doesn't match.  */
4830   {
4831     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4832                  {});
4833   }
4834
4835   /* A complete symbol with parameters matches any overload, since the
4836      index has no overload info.  */
4837   {
4838     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4839                  EXPECT ("std::zfunction", "std::zfunction2"));
4840     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4841                  EXPECT ("std::zfunction", "std::zfunction2"));
4842     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4843                  EXPECT ("std::zfunction", "std::zfunction2"));
4844   }
4845
4846   /* Check that whitespace is ignored appropriately.  A symbol with a
4847      template argument list. */
4848   {
4849     static const char expected[] = "ns::foo<int>";
4850     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4851                  EXPECT (expected));
4852     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4853                  EXPECT (expected));
4854   }
4855
4856   /* Check that whitespace is ignored appropriately.  A symbol with a
4857      template argument list that includes a pointer.  */
4858   {
4859     static const char expected[] = "ns::foo<char*>";
4860     /* Try both completion and non-completion modes.  */
4861     static const bool completion_mode[2] = {false, true};
4862     for (size_t i = 0; i < 2; i++)
4863       {
4864         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4865                      completion_mode[i], EXPECT (expected));
4866         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4867                      completion_mode[i], EXPECT (expected));
4868
4869         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4870                      completion_mode[i], EXPECT (expected));
4871         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4872                      completion_mode[i], EXPECT (expected));
4873       }
4874   }
4875
4876   {
4877     /* Check method qualifiers are ignored.  */
4878     static const char expected[] = "ns::foo<char*>";
4879     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4880                  symbol_name_match_type::FULL, true, EXPECT (expected));
4881     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4882                  symbol_name_match_type::FULL, true, EXPECT (expected));
4883     CHECK_MATCH ("foo < char * >  ( int ) const",
4884                  symbol_name_match_type::WILD, true, EXPECT (expected));
4885     CHECK_MATCH ("foo < char * >  ( int ) &&",
4886                  symbol_name_match_type::WILD, true, EXPECT (expected));
4887   }
4888
4889   /* Test lookup names that don't match anything.  */
4890   {
4891     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4892                  {});
4893
4894     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4895                  {});
4896   }
4897
4898   /* Some wild matching tests, exercising "(anonymous namespace)",
4899      which should not be confused with a parameter list.  */
4900   {
4901     static const char *syms[] = {
4902       "A::B::C",
4903       "B::C",
4904       "C",
4905       "A :: B :: C ( int )",
4906       "B :: C ( int )",
4907       "C ( int )",
4908     };
4909
4910     for (const char *s : syms)
4911       {
4912         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4913                      EXPECT ("(anonymous namespace)::A::B::C"));
4914       }
4915   }
4916
4917   {
4918     static const char expected[] = "ns2::tmpl<int>::foo2";
4919     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4920                  EXPECT (expected));
4921     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4922                  EXPECT (expected));
4923   }
4924
4925   SELF_CHECK (!any_mismatch);
4926
4927 #undef EXPECT
4928 #undef CHECK_MATCH
4929 }
4930
4931 static void
4932 run_test ()
4933 {
4934   test_mapped_index_find_name_component_bounds ();
4935   test_dw2_expand_symtabs_matching_symbol ();
4936 }
4937
4938 }} // namespace selftests::dw2_expand_symtabs_matching
4939
4940 #endif /* GDB_SELF_TEST */
4941
4942 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4943    matched, to expand corresponding CUs that were marked.  IDX is the
4944    index of the symbol name that matched.  */
4945
4946 static void
4947 dw2_expand_marked_cus
4948   (mapped_index &index, offset_type idx,
4949    struct objfile *objfile,
4950    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4951    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4952    search_domain kind)
4953 {
4954   offset_type *vec, vec_len, vec_idx;
4955   bool global_seen = false;
4956
4957   vec = (offset_type *) (index.constant_pool
4958                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
4959   vec_len = MAYBE_SWAP (vec[0]);
4960   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4961     {
4962       struct dwarf2_per_cu_data *per_cu;
4963       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4964       /* This value is only valid for index versions >= 7.  */
4965       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4966       gdb_index_symbol_kind symbol_kind =
4967         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4968       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4969       /* Only check the symbol attributes if they're present.
4970          Indices prior to version 7 don't record them,
4971          and indices >= 7 may elide them for certain symbols
4972          (gold does this).  */
4973       int attrs_valid =
4974         (index.version >= 7
4975          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4976
4977       /* Work around gold/15646.  */
4978       if (attrs_valid)
4979         {
4980           if (!is_static && global_seen)
4981             continue;
4982           if (!is_static)
4983             global_seen = true;
4984         }
4985
4986       /* Only check the symbol's kind if it has one.  */
4987       if (attrs_valid)
4988         {
4989           switch (kind)
4990             {
4991             case VARIABLES_DOMAIN:
4992               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4993                 continue;
4994               break;
4995             case FUNCTIONS_DOMAIN:
4996               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4997                 continue;
4998               break;
4999             case TYPES_DOMAIN:
5000               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5001                 continue;
5002               break;
5003             default:
5004               break;
5005             }
5006         }
5007
5008       /* Don't crash on bad data.  */
5009       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5010                        + dwarf2_per_objfile->n_type_units))
5011         {
5012           complaint (&symfile_complaints,
5013                      _(".gdb_index entry has bad CU index"
5014                        " [in module %s]"), objfile_name (objfile));
5015           continue;
5016         }
5017
5018       per_cu = dw2_get_cutu (cu_index);
5019       if (file_matcher == NULL || per_cu->v.quick->mark)
5020         {
5021           int symtab_was_null =
5022             (per_cu->v.quick->compunit_symtab == NULL);
5023
5024           dw2_instantiate_symtab (per_cu);
5025
5026           if (expansion_notify != NULL
5027               && symtab_was_null
5028               && per_cu->v.quick->compunit_symtab != NULL)
5029             expansion_notify (per_cu->v.quick->compunit_symtab);
5030         }
5031     }
5032 }
5033
5034 static void
5035 dw2_expand_symtabs_matching
5036   (struct objfile *objfile,
5037    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5038    const lookup_name_info &lookup_name,
5039    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5040    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5041    enum search_domain kind)
5042 {
5043   int i;
5044
5045   dw2_setup (objfile);
5046
5047   /* index_table is NULL if OBJF_READNOW.  */
5048   if (!dwarf2_per_objfile->index_table)
5049     return;
5050
5051   if (file_matcher != NULL)
5052     {
5053       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5054                                                 htab_eq_pointer,
5055                                                 NULL, xcalloc, xfree));
5056       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5057                                                     htab_eq_pointer,
5058                                                     NULL, xcalloc, xfree));
5059
5060       /* The rule is CUs specify all the files, including those used by
5061          any TU, so there's no need to scan TUs here.  */
5062
5063       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5064         {
5065           int j;
5066           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5067           struct quick_file_names *file_data;
5068           void **slot;
5069
5070           QUIT;
5071
5072           per_cu->v.quick->mark = 0;
5073
5074           /* We only need to look at symtabs not already expanded.  */
5075           if (per_cu->v.quick->compunit_symtab)
5076             continue;
5077
5078           file_data = dw2_get_file_names (per_cu);
5079           if (file_data == NULL)
5080             continue;
5081
5082           if (htab_find (visited_not_found.get (), file_data) != NULL)
5083             continue;
5084           else if (htab_find (visited_found.get (), file_data) != NULL)
5085             {
5086               per_cu->v.quick->mark = 1;
5087               continue;
5088             }
5089
5090           for (j = 0; j < file_data->num_file_names; ++j)
5091             {
5092               const char *this_real_name;
5093
5094               if (file_matcher (file_data->file_names[j], false))
5095                 {
5096                   per_cu->v.quick->mark = 1;
5097                   break;
5098                 }
5099
5100               /* Before we invoke realpath, which can get expensive when many
5101                  files are involved, do a quick comparison of the basenames.  */
5102               if (!basenames_may_differ
5103                   && !file_matcher (lbasename (file_data->file_names[j]),
5104                                     true))
5105                 continue;
5106
5107               this_real_name = dw2_get_real_path (objfile, file_data, j);
5108               if (file_matcher (this_real_name, false))
5109                 {
5110                   per_cu->v.quick->mark = 1;
5111                   break;
5112                 }
5113             }
5114
5115           slot = htab_find_slot (per_cu->v.quick->mark
5116                                  ? visited_found.get ()
5117                                  : visited_not_found.get (),
5118                                  file_data, INSERT);
5119           *slot = file_data;
5120         }
5121     }
5122
5123   mapped_index &index = *dwarf2_per_objfile->index_table;
5124
5125   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5126                                       symbol_matcher,
5127                                       kind, [&] (offset_type idx)
5128     {
5129       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5130                              expansion_notify, kind);
5131     });
5132 }
5133
5134 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5135    symtab.  */
5136
5137 static struct compunit_symtab *
5138 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5139                                           CORE_ADDR pc)
5140 {
5141   int i;
5142
5143   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5144       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5145     return cust;
5146
5147   if (cust->includes == NULL)
5148     return NULL;
5149
5150   for (i = 0; cust->includes[i]; ++i)
5151     {
5152       struct compunit_symtab *s = cust->includes[i];
5153
5154       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5155       if (s != NULL)
5156         return s;
5157     }
5158
5159   return NULL;
5160 }
5161
5162 static struct compunit_symtab *
5163 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5164                                   struct bound_minimal_symbol msymbol,
5165                                   CORE_ADDR pc,
5166                                   struct obj_section *section,
5167                                   int warn_if_readin)
5168 {
5169   struct dwarf2_per_cu_data *data;
5170   struct compunit_symtab *result;
5171
5172   dw2_setup (objfile);
5173
5174   if (!objfile->psymtabs_addrmap)
5175     return NULL;
5176
5177   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5178                                                      pc);
5179   if (!data)
5180     return NULL;
5181
5182   if (warn_if_readin && data->v.quick->compunit_symtab)
5183     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5184              paddress (get_objfile_arch (objfile), pc));
5185
5186   result
5187     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5188                                                 pc);
5189   gdb_assert (result != NULL);
5190   return result;
5191 }
5192
5193 static void
5194 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5195                           void *data, int need_fullname)
5196 {
5197   dw2_setup (objfile);
5198
5199   if (!dwarf2_per_objfile->filenames_cache)
5200     {
5201       dwarf2_per_objfile->filenames_cache.emplace ();
5202
5203       htab_up visited (htab_create_alloc (10,
5204                                           htab_hash_pointer, htab_eq_pointer,
5205                                           NULL, xcalloc, xfree));
5206
5207       /* The rule is CUs specify all the files, including those used
5208          by any TU, so there's no need to scan TUs here.  We can
5209          ignore file names coming from already-expanded CUs.  */
5210
5211       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5212         {
5213           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5214
5215           if (per_cu->v.quick->compunit_symtab)
5216             {
5217               void **slot = htab_find_slot (visited.get (),
5218                                             per_cu->v.quick->file_names,
5219                                             INSERT);
5220
5221               *slot = per_cu->v.quick->file_names;
5222             }
5223         }
5224
5225       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5226         {
5227           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5228           struct quick_file_names *file_data;
5229           void **slot;
5230
5231           /* We only need to look at symtabs not already expanded.  */
5232           if (per_cu->v.quick->compunit_symtab)
5233             continue;
5234
5235           file_data = dw2_get_file_names (per_cu);
5236           if (file_data == NULL)
5237             continue;
5238
5239           slot = htab_find_slot (visited.get (), file_data, INSERT);
5240           if (*slot)
5241             {
5242               /* Already visited.  */
5243               continue;
5244             }
5245           *slot = file_data;
5246
5247           for (int j = 0; j < file_data->num_file_names; ++j)
5248             {
5249               const char *filename = file_data->file_names[j];
5250               dwarf2_per_objfile->filenames_cache->seen (filename);
5251             }
5252         }
5253     }
5254
5255   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5256     {
5257       gdb::unique_xmalloc_ptr<char> this_real_name;
5258
5259       if (need_fullname)
5260         this_real_name = gdb_realpath (filename);
5261       (*fun) (filename, this_real_name.get (), data);
5262     });
5263 }
5264
5265 static int
5266 dw2_has_symbols (struct objfile *objfile)
5267 {
5268   return 1;
5269 }
5270
5271 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5272 {
5273   dw2_has_symbols,
5274   dw2_find_last_source_symtab,
5275   dw2_forget_cached_source_info,
5276   dw2_map_symtabs_matching_filename,
5277   dw2_lookup_symbol,
5278   dw2_print_stats,
5279   dw2_dump,
5280   dw2_relocate,
5281   dw2_expand_symtabs_for_function,
5282   dw2_expand_all_symtabs,
5283   dw2_expand_symtabs_with_fullname,
5284   dw2_map_matching_symbols,
5285   dw2_expand_symtabs_matching,
5286   dw2_find_pc_sect_compunit_symtab,
5287   NULL,
5288   dw2_map_symbol_filenames
5289 };
5290
5291 /* Initialize for reading DWARF for this objfile.  Return 0 if this
5292    file will use psymtabs, or 1 if using the GNU index.  */
5293
5294 int
5295 dwarf2_initialize_objfile (struct objfile *objfile)
5296 {
5297   /* If we're about to read full symbols, don't bother with the
5298      indices.  In this case we also don't care if some other debug
5299      format is making psymtabs, because they are all about to be
5300      expanded anyway.  */
5301   if ((objfile->flags & OBJF_READNOW))
5302     {
5303       int i;
5304
5305       dwarf2_per_objfile->using_index = 1;
5306       create_all_comp_units (objfile);
5307       create_all_type_units (objfile);
5308       dwarf2_per_objfile->quick_file_names_table =
5309         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5310
5311       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
5312                        + dwarf2_per_objfile->n_type_units); ++i)
5313         {
5314           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5315
5316           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5317                                             struct dwarf2_per_cu_quick_data);
5318         }
5319
5320       /* Return 1 so that gdb sees the "quick" functions.  However,
5321          these functions will be no-ops because we will have expanded
5322          all symtabs.  */
5323       return 1;
5324     }
5325
5326   if (dwarf2_read_index (objfile))
5327     return 1;
5328
5329   return 0;
5330 }
5331
5332 \f
5333
5334 /* Build a partial symbol table.  */
5335
5336 void
5337 dwarf2_build_psymtabs (struct objfile *objfile)
5338 {
5339
5340   if (objfile->global_psymbols.capacity () == 0
5341       && objfile->static_psymbols.capacity () == 0)
5342     init_psymbol_list (objfile, 1024);
5343
5344   TRY
5345     {
5346       /* This isn't really ideal: all the data we allocate on the
5347          objfile's obstack is still uselessly kept around.  However,
5348          freeing it seems unsafe.  */
5349       psymtab_discarder psymtabs (objfile);
5350       dwarf2_build_psymtabs_hard (objfile);
5351       psymtabs.keep ();
5352     }
5353   CATCH (except, RETURN_MASK_ERROR)
5354     {
5355       exception_print (gdb_stderr, except);
5356     }
5357   END_CATCH
5358 }
5359
5360 /* Return the total length of the CU described by HEADER.  */
5361
5362 static unsigned int
5363 get_cu_length (const struct comp_unit_head *header)
5364 {
5365   return header->initial_length_size + header->length;
5366 }
5367
5368 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
5369
5370 static inline bool
5371 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
5372 {
5373   sect_offset bottom = cu_header->sect_off;
5374   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
5375
5376   return sect_off >= bottom && sect_off < top;
5377 }
5378
5379 /* Find the base address of the compilation unit for range lists and
5380    location lists.  It will normally be specified by DW_AT_low_pc.
5381    In DWARF-3 draft 4, the base address could be overridden by
5382    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5383    compilation units with discontinuous ranges.  */
5384
5385 static void
5386 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5387 {
5388   struct attribute *attr;
5389
5390   cu->base_known = 0;
5391   cu->base_address = 0;
5392
5393   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5394   if (attr)
5395     {
5396       cu->base_address = attr_value_as_address (attr);
5397       cu->base_known = 1;
5398     }
5399   else
5400     {
5401       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5402       if (attr)
5403         {
5404           cu->base_address = attr_value_as_address (attr);
5405           cu->base_known = 1;
5406         }
5407     }
5408 }
5409
5410 /* Read in the comp unit header information from the debug_info at info_ptr.
5411    Use rcuh_kind::COMPILE as the default type if not known by the caller.
5412    NOTE: This leaves members offset, first_die_offset to be filled in
5413    by the caller.  */
5414
5415 static const gdb_byte *
5416 read_comp_unit_head (struct comp_unit_head *cu_header,
5417                      const gdb_byte *info_ptr,
5418                      struct dwarf2_section_info *section,
5419                      rcuh_kind section_kind)
5420 {
5421   int signed_addr;
5422   unsigned int bytes_read;
5423   const char *filename = get_section_file_name (section);
5424   bfd *abfd = get_section_bfd_owner (section);
5425
5426   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
5427   cu_header->initial_length_size = bytes_read;
5428   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
5429   info_ptr += bytes_read;
5430   cu_header->version = read_2_bytes (abfd, info_ptr);
5431   info_ptr += 2;
5432   if (cu_header->version < 5)
5433     switch (section_kind)
5434       {
5435       case rcuh_kind::COMPILE:
5436         cu_header->unit_type = DW_UT_compile;
5437         break;
5438       case rcuh_kind::TYPE:
5439         cu_header->unit_type = DW_UT_type;
5440         break;
5441       default:
5442         internal_error (__FILE__, __LINE__,
5443                         _("read_comp_unit_head: invalid section_kind"));
5444       }
5445   else
5446     {
5447       cu_header->unit_type = static_cast<enum dwarf_unit_type>
5448                                                  (read_1_byte (abfd, info_ptr));
5449       info_ptr += 1;
5450       switch (cu_header->unit_type)
5451         {
5452         case DW_UT_compile:
5453           if (section_kind != rcuh_kind::COMPILE)
5454             error (_("Dwarf Error: wrong unit_type in compilation unit header "
5455                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
5456                    filename);
5457           break;
5458         case DW_UT_type:
5459           section_kind = rcuh_kind::TYPE;
5460           break;
5461         default:
5462           error (_("Dwarf Error: wrong unit_type in compilation unit header "
5463                  "(is %d, should be %d or %d) [in module %s]"),
5464                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
5465         }
5466
5467       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5468       info_ptr += 1;
5469     }
5470   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
5471                                                           cu_header,
5472                                                           &bytes_read);
5473   info_ptr += bytes_read;
5474   if (cu_header->version < 5)
5475     {
5476       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5477       info_ptr += 1;
5478     }
5479   signed_addr = bfd_get_sign_extend_vma (abfd);
5480   if (signed_addr < 0)
5481     internal_error (__FILE__, __LINE__,
5482                     _("read_comp_unit_head: dwarf from non elf file"));
5483   cu_header->signed_addr_p = signed_addr;
5484
5485   if (section_kind == rcuh_kind::TYPE)
5486     {
5487       LONGEST type_offset;
5488
5489       cu_header->signature = read_8_bytes (abfd, info_ptr);
5490       info_ptr += 8;
5491
5492       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
5493       info_ptr += bytes_read;
5494       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
5495       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
5496         error (_("Dwarf Error: Too big type_offset in compilation unit "
5497                "header (is %s) [in module %s]"), plongest (type_offset),
5498                filename);
5499     }
5500
5501   return info_ptr;
5502 }
5503
5504 /* Helper function that returns the proper abbrev section for
5505    THIS_CU.  */
5506
5507 static struct dwarf2_section_info *
5508 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5509 {
5510   struct dwarf2_section_info *abbrev;
5511
5512   if (this_cu->is_dwz)
5513     abbrev = &dwarf2_get_dwz_file ()->abbrev;
5514   else
5515     abbrev = &dwarf2_per_objfile->abbrev;
5516
5517   return abbrev;
5518 }
5519
5520 /* Subroutine of read_and_check_comp_unit_head and
5521    read_and_check_type_unit_head to simplify them.
5522    Perform various error checking on the header.  */
5523
5524 static void
5525 error_check_comp_unit_head (struct comp_unit_head *header,
5526                             struct dwarf2_section_info *section,
5527                             struct dwarf2_section_info *abbrev_section)
5528 {
5529   const char *filename = get_section_file_name (section);
5530
5531   if (header->version < 2 || header->version > 5)
5532     error (_("Dwarf Error: wrong version in compilation unit header "
5533            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
5534            filename);
5535
5536   if (to_underlying (header->abbrev_sect_off)
5537       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
5538     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
5539            "(offset 0x%x + 6) [in module %s]"),
5540            to_underlying (header->abbrev_sect_off),
5541            to_underlying (header->sect_off),
5542            filename);
5543
5544   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
5545      avoid potential 32-bit overflow.  */
5546   if (((ULONGEST) header->sect_off + get_cu_length (header))
5547       > section->size)
5548     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
5549            "(offset 0x%x + 0) [in module %s]"),
5550            header->length, to_underlying (header->sect_off),
5551            filename);
5552 }
5553
5554 /* Read in a CU/TU header and perform some basic error checking.
5555    The contents of the header are stored in HEADER.
5556    The result is a pointer to the start of the first DIE.  */
5557
5558 static const gdb_byte *
5559 read_and_check_comp_unit_head (struct comp_unit_head *header,
5560                                struct dwarf2_section_info *section,
5561                                struct dwarf2_section_info *abbrev_section,
5562                                const gdb_byte *info_ptr,
5563                                rcuh_kind section_kind)
5564 {
5565   const gdb_byte *beg_of_comp_unit = info_ptr;
5566
5567   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
5568
5569   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
5570
5571   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5572
5573   error_check_comp_unit_head (header, section, abbrev_section);
5574
5575   return info_ptr;
5576 }
5577
5578 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5579
5580 static sect_offset
5581 read_abbrev_offset (struct dwarf2_section_info *section,
5582                     sect_offset sect_off)
5583 {
5584   bfd *abfd = get_section_bfd_owner (section);
5585   const gdb_byte *info_ptr;
5586   unsigned int initial_length_size, offset_size;
5587   uint16_t version;
5588
5589   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5590   info_ptr = section->buffer + to_underlying (sect_off);
5591   read_initial_length (abfd, info_ptr, &initial_length_size);
5592   offset_size = initial_length_size == 4 ? 4 : 8;
5593   info_ptr += initial_length_size;
5594
5595   version = read_2_bytes (abfd, info_ptr);
5596   info_ptr += 2;
5597   if (version >= 5)
5598     {
5599       /* Skip unit type and address size.  */
5600       info_ptr += 2;
5601     }
5602
5603   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5604 }
5605
5606 /* Allocate a new partial symtab for file named NAME and mark this new
5607    partial symtab as being an include of PST.  */
5608
5609 static void
5610 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5611                                struct objfile *objfile)
5612 {
5613   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5614
5615   if (!IS_ABSOLUTE_PATH (subpst->filename))
5616     {
5617       /* It shares objfile->objfile_obstack.  */
5618       subpst->dirname = pst->dirname;
5619     }
5620
5621   subpst->textlow = 0;
5622   subpst->texthigh = 0;
5623
5624   subpst->dependencies
5625     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5626   subpst->dependencies[0] = pst;
5627   subpst->number_of_dependencies = 1;
5628
5629   subpst->globals_offset = 0;
5630   subpst->n_global_syms = 0;
5631   subpst->statics_offset = 0;
5632   subpst->n_static_syms = 0;
5633   subpst->compunit_symtab = NULL;
5634   subpst->read_symtab = pst->read_symtab;
5635   subpst->readin = 0;
5636
5637   /* No private part is necessary for include psymtabs.  This property
5638      can be used to differentiate between such include psymtabs and
5639      the regular ones.  */
5640   subpst->read_symtab_private = NULL;
5641 }
5642
5643 /* Read the Line Number Program data and extract the list of files
5644    included by the source file represented by PST.  Build an include
5645    partial symtab for each of these included files.  */
5646
5647 static void
5648 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5649                                struct die_info *die,
5650                                struct partial_symtab *pst)
5651 {
5652   line_header_up lh;
5653   struct attribute *attr;
5654
5655   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5656   if (attr)
5657     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5658   if (lh == NULL)
5659     return;  /* No linetable, so no includes.  */
5660
5661   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5662   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5663 }
5664
5665 static hashval_t
5666 hash_signatured_type (const void *item)
5667 {
5668   const struct signatured_type *sig_type
5669     = (const struct signatured_type *) item;
5670
5671   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5672   return sig_type->signature;
5673 }
5674
5675 static int
5676 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5677 {
5678   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5679   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5680
5681   return lhs->signature == rhs->signature;
5682 }
5683
5684 /* Allocate a hash table for signatured types.  */
5685
5686 static htab_t
5687 allocate_signatured_type_table (struct objfile *objfile)
5688 {
5689   return htab_create_alloc_ex (41,
5690                                hash_signatured_type,
5691                                eq_signatured_type,
5692                                NULL,
5693                                &objfile->objfile_obstack,
5694                                hashtab_obstack_allocate,
5695                                dummy_obstack_deallocate);
5696 }
5697
5698 /* A helper function to add a signatured type CU to a table.  */
5699
5700 static int
5701 add_signatured_type_cu_to_table (void **slot, void *datum)
5702 {
5703   struct signatured_type *sigt = (struct signatured_type *) *slot;
5704   struct signatured_type ***datap = (struct signatured_type ***) datum;
5705
5706   **datap = sigt;
5707   ++*datap;
5708
5709   return 1;
5710 }
5711
5712 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5713    and fill them into TYPES_HTAB.  It will process only type units,
5714    therefore DW_UT_type.  */
5715
5716 static void
5717 create_debug_type_hash_table (struct dwo_file *dwo_file,
5718                               dwarf2_section_info *section, htab_t &types_htab,
5719                               rcuh_kind section_kind)
5720 {
5721   struct objfile *objfile = dwarf2_per_objfile->objfile;
5722   struct dwarf2_section_info *abbrev_section;
5723   bfd *abfd;
5724   const gdb_byte *info_ptr, *end_ptr;
5725
5726   abbrev_section = (dwo_file != NULL
5727                     ? &dwo_file->sections.abbrev
5728                     : &dwarf2_per_objfile->abbrev);
5729
5730   if (dwarf_read_debug)
5731     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5732                         get_section_name (section),
5733                         get_section_file_name (abbrev_section));
5734
5735   dwarf2_read_section (objfile, section);
5736   info_ptr = section->buffer;
5737
5738   if (info_ptr == NULL)
5739     return;
5740
5741   /* We can't set abfd until now because the section may be empty or
5742      not present, in which case the bfd is unknown.  */
5743   abfd = get_section_bfd_owner (section);
5744
5745   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5746      because we don't need to read any dies: the signature is in the
5747      header.  */
5748
5749   end_ptr = info_ptr + section->size;
5750   while (info_ptr < end_ptr)
5751     {
5752       struct signatured_type *sig_type;
5753       struct dwo_unit *dwo_tu;
5754       void **slot;
5755       const gdb_byte *ptr = info_ptr;
5756       struct comp_unit_head header;
5757       unsigned int length;
5758
5759       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5760
5761       /* Initialize it due to a false compiler warning.  */
5762       header.signature = -1;
5763       header.type_cu_offset_in_tu = (cu_offset) -1;
5764
5765       /* We need to read the type's signature in order to build the hash
5766          table, but we don't need anything else just yet.  */
5767
5768       ptr = read_and_check_comp_unit_head (&header, section,
5769                                            abbrev_section, ptr, section_kind);
5770
5771       length = get_cu_length (&header);
5772
5773       /* Skip dummy type units.  */
5774       if (ptr >= info_ptr + length
5775           || peek_abbrev_code (abfd, ptr) == 0
5776           || header.unit_type != DW_UT_type)
5777         {
5778           info_ptr += length;
5779           continue;
5780         }
5781
5782       if (types_htab == NULL)
5783         {
5784           if (dwo_file)
5785             types_htab = allocate_dwo_unit_table (objfile);
5786           else
5787             types_htab = allocate_signatured_type_table (objfile);
5788         }
5789
5790       if (dwo_file)
5791         {
5792           sig_type = NULL;
5793           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5794                                    struct dwo_unit);
5795           dwo_tu->dwo_file = dwo_file;
5796           dwo_tu->signature = header.signature;
5797           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5798           dwo_tu->section = section;
5799           dwo_tu->sect_off = sect_off;
5800           dwo_tu->length = length;
5801         }
5802       else
5803         {
5804           /* N.B.: type_offset is not usable if this type uses a DWO file.
5805              The real type_offset is in the DWO file.  */
5806           dwo_tu = NULL;
5807           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5808                                      struct signatured_type);
5809           sig_type->signature = header.signature;
5810           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5811           sig_type->per_cu.objfile = objfile;
5812           sig_type->per_cu.is_debug_types = 1;
5813           sig_type->per_cu.section = section;
5814           sig_type->per_cu.sect_off = sect_off;
5815           sig_type->per_cu.length = length;
5816         }
5817
5818       slot = htab_find_slot (types_htab,
5819                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5820                              INSERT);
5821       gdb_assert (slot != NULL);
5822       if (*slot != NULL)
5823         {
5824           sect_offset dup_sect_off;
5825
5826           if (dwo_file)
5827             {
5828               const struct dwo_unit *dup_tu
5829                 = (const struct dwo_unit *) *slot;
5830
5831               dup_sect_off = dup_tu->sect_off;
5832             }
5833           else
5834             {
5835               const struct signatured_type *dup_tu
5836                 = (const struct signatured_type *) *slot;
5837
5838               dup_sect_off = dup_tu->per_cu.sect_off;
5839             }
5840
5841           complaint (&symfile_complaints,
5842                      _("debug type entry at offset 0x%x is duplicate to"
5843                        " the entry at offset 0x%x, signature %s"),
5844                      to_underlying (sect_off), to_underlying (dup_sect_off),
5845                      hex_string (header.signature));
5846         }
5847       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5848
5849       if (dwarf_read_debug > 1)
5850         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5851                             to_underlying (sect_off),
5852                             hex_string (header.signature));
5853
5854       info_ptr += length;
5855     }
5856 }
5857
5858 /* Create the hash table of all entries in the .debug_types
5859    (or .debug_types.dwo) section(s).
5860    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5861    otherwise it is NULL.
5862
5863    The result is a pointer to the hash table or NULL if there are no types.
5864
5865    Note: This function processes DWO files only, not DWP files.  */
5866
5867 static void
5868 create_debug_types_hash_table (struct dwo_file *dwo_file,
5869                                VEC (dwarf2_section_info_def) *types,
5870                                htab_t &types_htab)
5871 {
5872   int ix;
5873   struct dwarf2_section_info *section;
5874
5875   if (VEC_empty (dwarf2_section_info_def, types))
5876     return;
5877
5878   for (ix = 0;
5879        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5880        ++ix)
5881     create_debug_type_hash_table (dwo_file, section, types_htab,
5882                                   rcuh_kind::TYPE);
5883 }
5884
5885 /* Create the hash table of all entries in the .debug_types section,
5886    and initialize all_type_units.
5887    The result is zero if there is an error (e.g. missing .debug_types section),
5888    otherwise non-zero.  */
5889
5890 static int
5891 create_all_type_units (struct objfile *objfile)
5892 {
5893   htab_t types_htab = NULL;
5894   struct signatured_type **iter;
5895
5896   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5897                                 rcuh_kind::COMPILE);
5898   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5899   if (types_htab == NULL)
5900     {
5901       dwarf2_per_objfile->signatured_types = NULL;
5902       return 0;
5903     }
5904
5905   dwarf2_per_objfile->signatured_types = types_htab;
5906
5907   dwarf2_per_objfile->n_type_units
5908     = dwarf2_per_objfile->n_allocated_type_units
5909     = htab_elements (types_htab);
5910   dwarf2_per_objfile->all_type_units =
5911     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5912   iter = &dwarf2_per_objfile->all_type_units[0];
5913   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5914   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5915               == dwarf2_per_objfile->n_type_units);
5916
5917   return 1;
5918 }
5919
5920 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5921    If SLOT is non-NULL, it is the entry to use in the hash table.
5922    Otherwise we find one.  */
5923
5924 static struct signatured_type *
5925 add_type_unit (ULONGEST sig, void **slot)
5926 {
5927   struct objfile *objfile = dwarf2_per_objfile->objfile;
5928   int n_type_units = dwarf2_per_objfile->n_type_units;
5929   struct signatured_type *sig_type;
5930
5931   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5932   ++n_type_units;
5933   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5934     {
5935       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5936         dwarf2_per_objfile->n_allocated_type_units = 1;
5937       dwarf2_per_objfile->n_allocated_type_units *= 2;
5938       dwarf2_per_objfile->all_type_units
5939         = XRESIZEVEC (struct signatured_type *,
5940                       dwarf2_per_objfile->all_type_units,
5941                       dwarf2_per_objfile->n_allocated_type_units);
5942       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5943     }
5944   dwarf2_per_objfile->n_type_units = n_type_units;
5945
5946   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5947                              struct signatured_type);
5948   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5949   sig_type->signature = sig;
5950   sig_type->per_cu.is_debug_types = 1;
5951   if (dwarf2_per_objfile->using_index)
5952     {
5953       sig_type->per_cu.v.quick =
5954         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5955                         struct dwarf2_per_cu_quick_data);
5956     }
5957
5958   if (slot == NULL)
5959     {
5960       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5961                              sig_type, INSERT);
5962     }
5963   gdb_assert (*slot == NULL);
5964   *slot = sig_type;
5965   /* The rest of sig_type must be filled in by the caller.  */
5966   return sig_type;
5967 }
5968
5969 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5970    Fill in SIG_ENTRY with DWO_ENTRY.  */
5971
5972 static void
5973 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5974                                   struct signatured_type *sig_entry,
5975                                   struct dwo_unit *dwo_entry)
5976 {
5977   /* Make sure we're not clobbering something we don't expect to.  */
5978   gdb_assert (! sig_entry->per_cu.queued);
5979   gdb_assert (sig_entry->per_cu.cu == NULL);
5980   if (dwarf2_per_objfile->using_index)
5981     {
5982       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5983       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5984     }
5985   else
5986       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5987   gdb_assert (sig_entry->signature == dwo_entry->signature);
5988   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5989   gdb_assert (sig_entry->type_unit_group == NULL);
5990   gdb_assert (sig_entry->dwo_unit == NULL);
5991
5992   sig_entry->per_cu.section = dwo_entry->section;
5993   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5994   sig_entry->per_cu.length = dwo_entry->length;
5995   sig_entry->per_cu.reading_dwo_directly = 1;
5996   sig_entry->per_cu.objfile = objfile;
5997   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5998   sig_entry->dwo_unit = dwo_entry;
5999 }
6000
6001 /* Subroutine of lookup_signatured_type.
6002    If we haven't read the TU yet, create the signatured_type data structure
6003    for a TU to be read in directly from a DWO file, bypassing the stub.
6004    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6005    using .gdb_index, then when reading a CU we want to stay in the DWO file
6006    containing that CU.  Otherwise we could end up reading several other DWO
6007    files (due to comdat folding) to process the transitive closure of all the
6008    mentioned TUs, and that can be slow.  The current DWO file will have every
6009    type signature that it needs.
6010    We only do this for .gdb_index because in the psymtab case we already have
6011    to read all the DWOs to build the type unit groups.  */
6012
6013 static struct signatured_type *
6014 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6015 {
6016   struct objfile *objfile = dwarf2_per_objfile->objfile;
6017   struct dwo_file *dwo_file;
6018   struct dwo_unit find_dwo_entry, *dwo_entry;
6019   struct signatured_type find_sig_entry, *sig_entry;
6020   void **slot;
6021
6022   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6023
6024   /* If TU skeletons have been removed then we may not have read in any
6025      TUs yet.  */
6026   if (dwarf2_per_objfile->signatured_types == NULL)
6027     {
6028       dwarf2_per_objfile->signatured_types
6029         = allocate_signatured_type_table (objfile);
6030     }
6031
6032   /* We only ever need to read in one copy of a signatured type.
6033      Use the global signatured_types array to do our own comdat-folding
6034      of types.  If this is the first time we're reading this TU, and
6035      the TU has an entry in .gdb_index, replace the recorded data from
6036      .gdb_index with this TU.  */
6037
6038   find_sig_entry.signature = sig;
6039   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6040                          &find_sig_entry, INSERT);
6041   sig_entry = (struct signatured_type *) *slot;
6042
6043   /* We can get here with the TU already read, *or* in the process of being
6044      read.  Don't reassign the global entry to point to this DWO if that's
6045      the case.  Also note that if the TU is already being read, it may not
6046      have come from a DWO, the program may be a mix of Fission-compiled
6047      code and non-Fission-compiled code.  */
6048
6049   /* Have we already tried to read this TU?
6050      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6051      needn't exist in the global table yet).  */
6052   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6053     return sig_entry;
6054
6055   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6056      dwo_unit of the TU itself.  */
6057   dwo_file = cu->dwo_unit->dwo_file;
6058
6059   /* Ok, this is the first time we're reading this TU.  */
6060   if (dwo_file->tus == NULL)
6061     return NULL;
6062   find_dwo_entry.signature = sig;
6063   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6064   if (dwo_entry == NULL)
6065     return NULL;
6066
6067   /* If the global table doesn't have an entry for this TU, add one.  */
6068   if (sig_entry == NULL)
6069     sig_entry = add_type_unit (sig, slot);
6070
6071   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6072   sig_entry->per_cu.tu_read = 1;
6073   return sig_entry;
6074 }
6075
6076 /* Subroutine of lookup_signatured_type.
6077    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6078    then try the DWP file.  If the TU stub (skeleton) has been removed then
6079    it won't be in .gdb_index.  */
6080
6081 static struct signatured_type *
6082 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6083 {
6084   struct objfile *objfile = dwarf2_per_objfile->objfile;
6085   struct dwp_file *dwp_file = get_dwp_file ();
6086   struct dwo_unit *dwo_entry;
6087   struct signatured_type find_sig_entry, *sig_entry;
6088   void **slot;
6089
6090   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6091   gdb_assert (dwp_file != NULL);
6092
6093   /* If TU skeletons have been removed then we may not have read in any
6094      TUs yet.  */
6095   if (dwarf2_per_objfile->signatured_types == NULL)
6096     {
6097       dwarf2_per_objfile->signatured_types
6098         = allocate_signatured_type_table (objfile);
6099     }
6100
6101   find_sig_entry.signature = sig;
6102   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6103                          &find_sig_entry, INSERT);
6104   sig_entry = (struct signatured_type *) *slot;
6105
6106   /* Have we already tried to read this TU?
6107      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6108      needn't exist in the global table yet).  */
6109   if (sig_entry != NULL)
6110     return sig_entry;
6111
6112   if (dwp_file->tus == NULL)
6113     return NULL;
6114   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
6115                                       sig, 1 /* is_debug_types */);
6116   if (dwo_entry == NULL)
6117     return NULL;
6118
6119   sig_entry = add_type_unit (sig, slot);
6120   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6121
6122   return sig_entry;
6123 }
6124
6125 /* Lookup a signature based type for DW_FORM_ref_sig8.
6126    Returns NULL if signature SIG is not present in the table.
6127    It is up to the caller to complain about this.  */
6128
6129 static struct signatured_type *
6130 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6131 {
6132   if (cu->dwo_unit
6133       && dwarf2_per_objfile->using_index)
6134     {
6135       /* We're in a DWO/DWP file, and we're using .gdb_index.
6136          These cases require special processing.  */
6137       if (get_dwp_file () == NULL)
6138         return lookup_dwo_signatured_type (cu, sig);
6139       else
6140         return lookup_dwp_signatured_type (cu, sig);
6141     }
6142   else
6143     {
6144       struct signatured_type find_entry, *entry;
6145
6146       if (dwarf2_per_objfile->signatured_types == NULL)
6147         return NULL;
6148       find_entry.signature = sig;
6149       entry = ((struct signatured_type *)
6150                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
6151       return entry;
6152     }
6153 }
6154 \f
6155 /* Low level DIE reading support.  */
6156
6157 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6158
6159 static void
6160 init_cu_die_reader (struct die_reader_specs *reader,
6161                     struct dwarf2_cu *cu,
6162                     struct dwarf2_section_info *section,
6163                     struct dwo_file *dwo_file)
6164 {
6165   gdb_assert (section->readin && section->buffer != NULL);
6166   reader->abfd = get_section_bfd_owner (section);
6167   reader->cu = cu;
6168   reader->dwo_file = dwo_file;
6169   reader->die_section = section;
6170   reader->buffer = section->buffer;
6171   reader->buffer_end = section->buffer + section->size;
6172   reader->comp_dir = NULL;
6173 }
6174
6175 /* Subroutine of init_cutu_and_read_dies to simplify it.
6176    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6177    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
6178    already.
6179
6180    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6181    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6182    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6183    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6184    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6185    STUB_COMP_DIR may be non-NULL.
6186    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
6187    are filled in with the info of the DIE from the DWO file.
6188    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
6189    provided an abbrev table to use.
6190    The result is non-zero if a valid (non-dummy) DIE was found.  */
6191
6192 static int
6193 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6194                         struct dwo_unit *dwo_unit,
6195                         int abbrev_table_provided,
6196                         struct die_info *stub_comp_unit_die,
6197                         const char *stub_comp_dir,
6198                         struct die_reader_specs *result_reader,
6199                         const gdb_byte **result_info_ptr,
6200                         struct die_info **result_comp_unit_die,
6201                         int *result_has_children)
6202 {
6203   struct objfile *objfile = dwarf2_per_objfile->objfile;
6204   struct dwarf2_cu *cu = this_cu->cu;
6205   struct dwarf2_section_info *section;
6206   bfd *abfd;
6207   const gdb_byte *begin_info_ptr, *info_ptr;
6208   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6209   int i,num_extra_attrs;
6210   struct dwarf2_section_info *dwo_abbrev_section;
6211   struct attribute *attr;
6212   struct die_info *comp_unit_die;
6213
6214   /* At most one of these may be provided.  */
6215   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6216
6217   /* These attributes aren't processed until later:
6218      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6219      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6220      referenced later.  However, these attributes are found in the stub
6221      which we won't have later.  In order to not impose this complication
6222      on the rest of the code, we read them here and copy them to the
6223      DWO CU/TU die.  */
6224
6225   stmt_list = NULL;
6226   low_pc = NULL;
6227   high_pc = NULL;
6228   ranges = NULL;
6229   comp_dir = NULL;
6230
6231   if (stub_comp_unit_die != NULL)
6232     {
6233       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6234          DWO file.  */
6235       if (! this_cu->is_debug_types)
6236         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6237       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6238       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6239       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6240       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6241
6242       /* There should be a DW_AT_addr_base attribute here (if needed).
6243          We need the value before we can process DW_FORM_GNU_addr_index.  */
6244       cu->addr_base = 0;
6245       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
6246       if (attr)
6247         cu->addr_base = DW_UNSND (attr);
6248
6249       /* There should be a DW_AT_ranges_base attribute here (if needed).
6250          We need the value before we can process DW_AT_ranges.  */
6251       cu->ranges_base = 0;
6252       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
6253       if (attr)
6254         cu->ranges_base = DW_UNSND (attr);
6255     }
6256   else if (stub_comp_dir != NULL)
6257     {
6258       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6259       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6260       comp_dir->name = DW_AT_comp_dir;
6261       comp_dir->form = DW_FORM_string;
6262       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6263       DW_STRING (comp_dir) = stub_comp_dir;
6264     }
6265
6266   /* Set up for reading the DWO CU/TU.  */
6267   cu->dwo_unit = dwo_unit;
6268   section = dwo_unit->section;
6269   dwarf2_read_section (objfile, section);
6270   abfd = get_section_bfd_owner (section);
6271   begin_info_ptr = info_ptr = (section->buffer
6272                                + to_underlying (dwo_unit->sect_off));
6273   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6274   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
6275
6276   if (this_cu->is_debug_types)
6277     {
6278       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
6279
6280       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6281                                                 dwo_abbrev_section,
6282                                                 info_ptr, rcuh_kind::TYPE);
6283       /* This is not an assert because it can be caused by bad debug info.  */
6284       if (sig_type->signature != cu->header.signature)
6285         {
6286           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6287                    " TU at offset 0x%x [in module %s]"),
6288                  hex_string (sig_type->signature),
6289                  hex_string (cu->header.signature),
6290                  to_underlying (dwo_unit->sect_off),
6291                  bfd_get_filename (abfd));
6292         }
6293       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6294       /* For DWOs coming from DWP files, we don't know the CU length
6295          nor the type's offset in the TU until now.  */
6296       dwo_unit->length = get_cu_length (&cu->header);
6297       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6298
6299       /* Establish the type offset that can be used to lookup the type.
6300          For DWO files, we don't know it until now.  */
6301       sig_type->type_offset_in_section
6302         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6303     }
6304   else
6305     {
6306       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6307                                                 dwo_abbrev_section,
6308                                                 info_ptr, rcuh_kind::COMPILE);
6309       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6310       /* For DWOs coming from DWP files, we don't know the CU length
6311          until now.  */
6312       dwo_unit->length = get_cu_length (&cu->header);
6313     }
6314
6315   /* Replace the CU's original abbrev table with the DWO's.
6316      Reminder: We can't read the abbrev table until we've read the header.  */
6317   if (abbrev_table_provided)
6318     {
6319       /* Don't free the provided abbrev table, the caller of
6320          init_cutu_and_read_dies owns it.  */
6321       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6322       /* Ensure the DWO abbrev table gets freed.  */
6323       make_cleanup (dwarf2_free_abbrev_table, cu);
6324     }
6325   else
6326     {
6327       dwarf2_free_abbrev_table (cu);
6328       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6329       /* Leave any existing abbrev table cleanup as is.  */
6330     }
6331
6332   /* Read in the die, but leave space to copy over the attributes
6333      from the stub.  This has the benefit of simplifying the rest of
6334      the code - all the work to maintain the illusion of a single
6335      DW_TAG_{compile,type}_unit DIE is done here.  */
6336   num_extra_attrs = ((stmt_list != NULL)
6337                      + (low_pc != NULL)
6338                      + (high_pc != NULL)
6339                      + (ranges != NULL)
6340                      + (comp_dir != NULL));
6341   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6342                               result_has_children, num_extra_attrs);
6343
6344   /* Copy over the attributes from the stub to the DIE we just read in.  */
6345   comp_unit_die = *result_comp_unit_die;
6346   i = comp_unit_die->num_attrs;
6347   if (stmt_list != NULL)
6348     comp_unit_die->attrs[i++] = *stmt_list;
6349   if (low_pc != NULL)
6350     comp_unit_die->attrs[i++] = *low_pc;
6351   if (high_pc != NULL)
6352     comp_unit_die->attrs[i++] = *high_pc;
6353   if (ranges != NULL)
6354     comp_unit_die->attrs[i++] = *ranges;
6355   if (comp_dir != NULL)
6356     comp_unit_die->attrs[i++] = *comp_dir;
6357   comp_unit_die->num_attrs += num_extra_attrs;
6358
6359   if (dwarf_die_debug)
6360     {
6361       fprintf_unfiltered (gdb_stdlog,
6362                           "Read die from %s@0x%x of %s:\n",
6363                           get_section_name (section),
6364                           (unsigned) (begin_info_ptr - section->buffer),
6365                           bfd_get_filename (abfd));
6366       dump_die (comp_unit_die, dwarf_die_debug);
6367     }
6368
6369   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
6370      TUs by skipping the stub and going directly to the entry in the DWO file.
6371      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
6372      to get it via circuitous means.  Blech.  */
6373   if (comp_dir != NULL)
6374     result_reader->comp_dir = DW_STRING (comp_dir);
6375
6376   /* Skip dummy compilation units.  */
6377   if (info_ptr >= begin_info_ptr + dwo_unit->length
6378       || peek_abbrev_code (abfd, info_ptr) == 0)
6379     return 0;
6380
6381   *result_info_ptr = info_ptr;
6382   return 1;
6383 }
6384
6385 /* Subroutine of init_cutu_and_read_dies to simplify it.
6386    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6387    Returns NULL if the specified DWO unit cannot be found.  */
6388
6389 static struct dwo_unit *
6390 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
6391                  struct die_info *comp_unit_die)
6392 {
6393   struct dwarf2_cu *cu = this_cu->cu;
6394   ULONGEST signature;
6395   struct dwo_unit *dwo_unit;
6396   const char *comp_dir, *dwo_name;
6397
6398   gdb_assert (cu != NULL);
6399
6400   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6401   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6402   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6403
6404   if (this_cu->is_debug_types)
6405     {
6406       struct signatured_type *sig_type;
6407
6408       /* Since this_cu is the first member of struct signatured_type,
6409          we can go from a pointer to one to a pointer to the other.  */
6410       sig_type = (struct signatured_type *) this_cu;
6411       signature = sig_type->signature;
6412       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
6413     }
6414   else
6415     {
6416       struct attribute *attr;
6417
6418       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6419       if (! attr)
6420         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6421                  " [in module %s]"),
6422                dwo_name, objfile_name (this_cu->objfile));
6423       signature = DW_UNSND (attr);
6424       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
6425                                        signature);
6426     }
6427
6428   return dwo_unit;
6429 }
6430
6431 /* Subroutine of init_cutu_and_read_dies to simplify it.
6432    See it for a description of the parameters.
6433    Read a TU directly from a DWO file, bypassing the stub.
6434
6435    Note: This function could be a little bit simpler if we shared cleanups
6436    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
6437    to do, so we keep this function self-contained.  Or we could move this
6438    into our caller, but it's complex enough already.  */
6439
6440 static void
6441 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
6442                            int use_existing_cu, int keep,
6443                            die_reader_func_ftype *die_reader_func,
6444                            void *data)
6445 {
6446   struct dwarf2_cu *cu;
6447   struct signatured_type *sig_type;
6448   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6449   struct die_reader_specs reader;
6450   const gdb_byte *info_ptr;
6451   struct die_info *comp_unit_die;
6452   int has_children;
6453
6454   /* Verify we can do the following downcast, and that we have the
6455      data we need.  */
6456   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6457   sig_type = (struct signatured_type *) this_cu;
6458   gdb_assert (sig_type->dwo_unit != NULL);
6459
6460   cleanups = make_cleanup (null_cleanup, NULL);
6461
6462   if (use_existing_cu && this_cu->cu != NULL)
6463     {
6464       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
6465       cu = this_cu->cu;
6466       /* There's no need to do the rereading_dwo_cu handling that
6467          init_cutu_and_read_dies does since we don't read the stub.  */
6468     }
6469   else
6470     {
6471       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6472       gdb_assert (this_cu->cu == NULL);
6473       cu = XNEW (struct dwarf2_cu);
6474       init_one_comp_unit (cu, this_cu);
6475       /* If an error occurs while loading, release our storage.  */
6476       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6477     }
6478
6479   /* A future optimization, if needed, would be to use an existing
6480      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6481      could share abbrev tables.  */
6482
6483   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
6484                               0 /* abbrev_table_provided */,
6485                               NULL /* stub_comp_unit_die */,
6486                               sig_type->dwo_unit->dwo_file->comp_dir,
6487                               &reader, &info_ptr,
6488                               &comp_unit_die, &has_children) == 0)
6489     {
6490       /* Dummy die.  */
6491       do_cleanups (cleanups);
6492       return;
6493     }
6494
6495   /* All the "real" work is done here.  */
6496   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6497
6498   /* This duplicates the code in init_cutu_and_read_dies,
6499      but the alternative is making the latter more complex.
6500      This function is only for the special case of using DWO files directly:
6501      no point in overly complicating the general case just to handle this.  */
6502   if (free_cu_cleanup != NULL)
6503     {
6504       if (keep)
6505         {
6506           /* We've successfully allocated this compilation unit.  Let our
6507              caller clean it up when finished with it.  */
6508           discard_cleanups (free_cu_cleanup);
6509
6510           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6511              So we have to manually free the abbrev table.  */
6512           dwarf2_free_abbrev_table (cu);
6513
6514           /* Link this CU into read_in_chain.  */
6515           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6516           dwarf2_per_objfile->read_in_chain = this_cu;
6517         }
6518       else
6519         do_cleanups (free_cu_cleanup);
6520     }
6521
6522   do_cleanups (cleanups);
6523 }
6524
6525 /* Initialize a CU (or TU) and read its DIEs.
6526    If the CU defers to a DWO file, read the DWO file as well.
6527
6528    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6529    Otherwise the table specified in the comp unit header is read in and used.
6530    This is an optimization for when we already have the abbrev table.
6531
6532    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
6533    Otherwise, a new CU is allocated with xmalloc.
6534
6535    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
6536    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
6537
6538    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6539    linker) then DIE_READER_FUNC will not get called.  */
6540
6541 static void
6542 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
6543                          struct abbrev_table *abbrev_table,
6544                          int use_existing_cu, int keep,
6545                          die_reader_func_ftype *die_reader_func,
6546                          void *data)
6547 {
6548   struct objfile *objfile = dwarf2_per_objfile->objfile;
6549   struct dwarf2_section_info *section = this_cu->section;
6550   bfd *abfd = get_section_bfd_owner (section);
6551   struct dwarf2_cu *cu;
6552   const gdb_byte *begin_info_ptr, *info_ptr;
6553   struct die_reader_specs reader;
6554   struct die_info *comp_unit_die;
6555   int has_children;
6556   struct attribute *attr;
6557   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6558   struct signatured_type *sig_type = NULL;
6559   struct dwarf2_section_info *abbrev_section;
6560   /* Non-zero if CU currently points to a DWO file and we need to
6561      reread it.  When this happens we need to reread the skeleton die
6562      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6563   int rereading_dwo_cu = 0;
6564
6565   if (dwarf_die_debug)
6566     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6567                         this_cu->is_debug_types ? "type" : "comp",
6568                         to_underlying (this_cu->sect_off));
6569
6570   if (use_existing_cu)
6571     gdb_assert (keep);
6572
6573   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6574      file (instead of going through the stub), short-circuit all of this.  */
6575   if (this_cu->reading_dwo_directly)
6576     {
6577       /* Narrow down the scope of possibilities to have to understand.  */
6578       gdb_assert (this_cu->is_debug_types);
6579       gdb_assert (abbrev_table == NULL);
6580       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6581                                  die_reader_func, data);
6582       return;
6583     }
6584
6585   cleanups = make_cleanup (null_cleanup, NULL);
6586
6587   /* This is cheap if the section is already read in.  */
6588   dwarf2_read_section (objfile, section);
6589
6590   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6591
6592   abbrev_section = get_abbrev_section_for_cu (this_cu);
6593
6594   if (use_existing_cu && this_cu->cu != NULL)
6595     {
6596       cu = this_cu->cu;
6597       /* If this CU is from a DWO file we need to start over, we need to
6598          refetch the attributes from the skeleton CU.
6599          This could be optimized by retrieving those attributes from when we
6600          were here the first time: the previous comp_unit_die was stored in
6601          comp_unit_obstack.  But there's no data yet that we need this
6602          optimization.  */
6603       if (cu->dwo_unit != NULL)
6604         rereading_dwo_cu = 1;
6605     }
6606   else
6607     {
6608       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6609       gdb_assert (this_cu->cu == NULL);
6610       cu = XNEW (struct dwarf2_cu);
6611       init_one_comp_unit (cu, this_cu);
6612       /* If an error occurs while loading, release our storage.  */
6613       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6614     }
6615
6616   /* Get the header.  */
6617   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6618     {
6619       /* We already have the header, there's no need to read it in again.  */
6620       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6621     }
6622   else
6623     {
6624       if (this_cu->is_debug_types)
6625         {
6626           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6627                                                     abbrev_section, info_ptr,
6628                                                     rcuh_kind::TYPE);
6629
6630           /* Since per_cu is the first member of struct signatured_type,
6631              we can go from a pointer to one to a pointer to the other.  */
6632           sig_type = (struct signatured_type *) this_cu;
6633           gdb_assert (sig_type->signature == cu->header.signature);
6634           gdb_assert (sig_type->type_offset_in_tu
6635                       == cu->header.type_cu_offset_in_tu);
6636           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6637
6638           /* LENGTH has not been set yet for type units if we're
6639              using .gdb_index.  */
6640           this_cu->length = get_cu_length (&cu->header);
6641
6642           /* Establish the type offset that can be used to lookup the type.  */
6643           sig_type->type_offset_in_section =
6644             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6645
6646           this_cu->dwarf_version = cu->header.version;
6647         }
6648       else
6649         {
6650           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6651                                                     abbrev_section,
6652                                                     info_ptr,
6653                                                     rcuh_kind::COMPILE);
6654
6655           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6656           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6657           this_cu->dwarf_version = cu->header.version;
6658         }
6659     }
6660
6661   /* Skip dummy compilation units.  */
6662   if (info_ptr >= begin_info_ptr + this_cu->length
6663       || peek_abbrev_code (abfd, info_ptr) == 0)
6664     {
6665       do_cleanups (cleanups);
6666       return;
6667     }
6668
6669   /* If we don't have them yet, read the abbrevs for this compilation unit.
6670      And if we need to read them now, make sure they're freed when we're
6671      done.  Note that it's important that if the CU had an abbrev table
6672      on entry we don't free it when we're done: Somewhere up the call stack
6673      it may be in use.  */
6674   if (abbrev_table != NULL)
6675     {
6676       gdb_assert (cu->abbrev_table == NULL);
6677       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6678       cu->abbrev_table = abbrev_table;
6679     }
6680   else if (cu->abbrev_table == NULL)
6681     {
6682       dwarf2_read_abbrevs (cu, abbrev_section);
6683       make_cleanup (dwarf2_free_abbrev_table, cu);
6684     }
6685   else if (rereading_dwo_cu)
6686     {
6687       dwarf2_free_abbrev_table (cu);
6688       dwarf2_read_abbrevs (cu, abbrev_section);
6689     }
6690
6691   /* Read the top level CU/TU die.  */
6692   init_cu_die_reader (&reader, cu, section, NULL);
6693   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6694
6695   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6696      from the DWO file.
6697      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6698      DWO CU, that this test will fail (the attribute will not be present).  */
6699   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6700   if (attr)
6701     {
6702       struct dwo_unit *dwo_unit;
6703       struct die_info *dwo_comp_unit_die;
6704
6705       if (has_children)
6706         {
6707           complaint (&symfile_complaints,
6708                      _("compilation unit with DW_AT_GNU_dwo_name"
6709                        " has children (offset 0x%x) [in module %s]"),
6710                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6711         }
6712       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6713       if (dwo_unit != NULL)
6714         {
6715           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6716                                       abbrev_table != NULL,
6717                                       comp_unit_die, NULL,
6718                                       &reader, &info_ptr,
6719                                       &dwo_comp_unit_die, &has_children) == 0)
6720             {
6721               /* Dummy die.  */
6722               do_cleanups (cleanups);
6723               return;
6724             }
6725           comp_unit_die = dwo_comp_unit_die;
6726         }
6727       else
6728         {
6729           /* Yikes, we couldn't find the rest of the DIE, we only have
6730              the stub.  A complaint has already been logged.  There's
6731              not much more we can do except pass on the stub DIE to
6732              die_reader_func.  We don't want to throw an error on bad
6733              debug info.  */
6734         }
6735     }
6736
6737   /* All of the above is setup for this call.  Yikes.  */
6738   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6739
6740   /* Done, clean up.  */
6741   if (free_cu_cleanup != NULL)
6742     {
6743       if (keep)
6744         {
6745           /* We've successfully allocated this compilation unit.  Let our
6746              caller clean it up when finished with it.  */
6747           discard_cleanups (free_cu_cleanup);
6748
6749           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6750              So we have to manually free the abbrev table.  */
6751           dwarf2_free_abbrev_table (cu);
6752
6753           /* Link this CU into read_in_chain.  */
6754           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6755           dwarf2_per_objfile->read_in_chain = this_cu;
6756         }
6757       else
6758         do_cleanups (free_cu_cleanup);
6759     }
6760
6761   do_cleanups (cleanups);
6762 }
6763
6764 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6765    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6766    to have already done the lookup to find the DWO file).
6767
6768    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6769    THIS_CU->is_debug_types, but nothing else.
6770
6771    We fill in THIS_CU->length.
6772
6773    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6774    linker) then DIE_READER_FUNC will not get called.
6775
6776    THIS_CU->cu is always freed when done.
6777    This is done in order to not leave THIS_CU->cu in a state where we have
6778    to care whether it refers to the "main" CU or the DWO CU.  */
6779
6780 static void
6781 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6782                                    struct dwo_file *dwo_file,
6783                                    die_reader_func_ftype *die_reader_func,
6784                                    void *data)
6785 {
6786   struct objfile *objfile = dwarf2_per_objfile->objfile;
6787   struct dwarf2_section_info *section = this_cu->section;
6788   bfd *abfd = get_section_bfd_owner (section);
6789   struct dwarf2_section_info *abbrev_section;
6790   struct dwarf2_cu cu;
6791   const gdb_byte *begin_info_ptr, *info_ptr;
6792   struct die_reader_specs reader;
6793   struct cleanup *cleanups;
6794   struct die_info *comp_unit_die;
6795   int has_children;
6796
6797   if (dwarf_die_debug)
6798     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6799                         this_cu->is_debug_types ? "type" : "comp",
6800                         to_underlying (this_cu->sect_off));
6801
6802   gdb_assert (this_cu->cu == NULL);
6803
6804   abbrev_section = (dwo_file != NULL
6805                     ? &dwo_file->sections.abbrev
6806                     : get_abbrev_section_for_cu (this_cu));
6807
6808   /* This is cheap if the section is already read in.  */
6809   dwarf2_read_section (objfile, section);
6810
6811   init_one_comp_unit (&cu, this_cu);
6812
6813   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6814
6815   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6816   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6817                                             abbrev_section, info_ptr,
6818                                             (this_cu->is_debug_types
6819                                              ? rcuh_kind::TYPE
6820                                              : rcuh_kind::COMPILE));
6821
6822   this_cu->length = get_cu_length (&cu.header);
6823
6824   /* Skip dummy compilation units.  */
6825   if (info_ptr >= begin_info_ptr + this_cu->length
6826       || peek_abbrev_code (abfd, info_ptr) == 0)
6827     {
6828       do_cleanups (cleanups);
6829       return;
6830     }
6831
6832   dwarf2_read_abbrevs (&cu, abbrev_section);
6833   make_cleanup (dwarf2_free_abbrev_table, &cu);
6834
6835   init_cu_die_reader (&reader, &cu, section, dwo_file);
6836   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6837
6838   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6839
6840   do_cleanups (cleanups);
6841 }
6842
6843 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6844    does not lookup the specified DWO file.
6845    This cannot be used to read DWO files.
6846
6847    THIS_CU->cu is always freed when done.
6848    This is done in order to not leave THIS_CU->cu in a state where we have
6849    to care whether it refers to the "main" CU or the DWO CU.
6850    We can revisit this if the data shows there's a performance issue.  */
6851
6852 static void
6853 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6854                                 die_reader_func_ftype *die_reader_func,
6855                                 void *data)
6856 {
6857   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6858 }
6859 \f
6860 /* Type Unit Groups.
6861
6862    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6863    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6864    so that all types coming from the same compilation (.o file) are grouped
6865    together.  A future step could be to put the types in the same symtab as
6866    the CU the types ultimately came from.  */
6867
6868 static hashval_t
6869 hash_type_unit_group (const void *item)
6870 {
6871   const struct type_unit_group *tu_group
6872     = (const struct type_unit_group *) item;
6873
6874   return hash_stmt_list_entry (&tu_group->hash);
6875 }
6876
6877 static int
6878 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6879 {
6880   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6881   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6882
6883   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6884 }
6885
6886 /* Allocate a hash table for type unit groups.  */
6887
6888 static htab_t
6889 allocate_type_unit_groups_table (void)
6890 {
6891   return htab_create_alloc_ex (3,
6892                                hash_type_unit_group,
6893                                eq_type_unit_group,
6894                                NULL,
6895                                &dwarf2_per_objfile->objfile->objfile_obstack,
6896                                hashtab_obstack_allocate,
6897                                dummy_obstack_deallocate);
6898 }
6899
6900 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6901    partial symtabs.  We combine several TUs per psymtab to not let the size
6902    of any one psymtab grow too big.  */
6903 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6904 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6905
6906 /* Helper routine for get_type_unit_group.
6907    Create the type_unit_group object used to hold one or more TUs.  */
6908
6909 static struct type_unit_group *
6910 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6911 {
6912   struct objfile *objfile = dwarf2_per_objfile->objfile;
6913   struct dwarf2_per_cu_data *per_cu;
6914   struct type_unit_group *tu_group;
6915
6916   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6917                              struct type_unit_group);
6918   per_cu = &tu_group->per_cu;
6919   per_cu->objfile = objfile;
6920
6921   if (dwarf2_per_objfile->using_index)
6922     {
6923       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6924                                         struct dwarf2_per_cu_quick_data);
6925     }
6926   else
6927     {
6928       unsigned int line_offset = to_underlying (line_offset_struct);
6929       struct partial_symtab *pst;
6930       char *name;
6931
6932       /* Give the symtab a useful name for debug purposes.  */
6933       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6934         name = xstrprintf ("<type_units_%d>",
6935                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6936       else
6937         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6938
6939       pst = create_partial_symtab (per_cu, name);
6940       pst->anonymous = 1;
6941
6942       xfree (name);
6943     }
6944
6945   tu_group->hash.dwo_unit = cu->dwo_unit;
6946   tu_group->hash.line_sect_off = line_offset_struct;
6947
6948   return tu_group;
6949 }
6950
6951 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6952    STMT_LIST is a DW_AT_stmt_list attribute.  */
6953
6954 static struct type_unit_group *
6955 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6956 {
6957   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6958   struct type_unit_group *tu_group;
6959   void **slot;
6960   unsigned int line_offset;
6961   struct type_unit_group type_unit_group_for_lookup;
6962
6963   if (dwarf2_per_objfile->type_unit_groups == NULL)
6964     {
6965       dwarf2_per_objfile->type_unit_groups =
6966         allocate_type_unit_groups_table ();
6967     }
6968
6969   /* Do we need to create a new group, or can we use an existing one?  */
6970
6971   if (stmt_list)
6972     {
6973       line_offset = DW_UNSND (stmt_list);
6974       ++tu_stats->nr_symtab_sharers;
6975     }
6976   else
6977     {
6978       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6979          We can do various things here like create one group per TU or
6980          spread them over multiple groups to split up the expansion work.
6981          To avoid worst case scenarios (too many groups or too large groups)
6982          we, umm, group them in bunches.  */
6983       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6984                      | (tu_stats->nr_stmt_less_type_units
6985                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6986       ++tu_stats->nr_stmt_less_type_units;
6987     }
6988
6989   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6990   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6991   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6992                          &type_unit_group_for_lookup, INSERT);
6993   if (*slot != NULL)
6994     {
6995       tu_group = (struct type_unit_group *) *slot;
6996       gdb_assert (tu_group != NULL);
6997     }
6998   else
6999     {
7000       sect_offset line_offset_struct = (sect_offset) line_offset;
7001       tu_group = create_type_unit_group (cu, line_offset_struct);
7002       *slot = tu_group;
7003       ++tu_stats->nr_symtabs;
7004     }
7005
7006   return tu_group;
7007 }
7008 \f
7009 /* Partial symbol tables.  */
7010
7011 /* Create a psymtab named NAME and assign it to PER_CU.
7012
7013    The caller must fill in the following details:
7014    dirname, textlow, texthigh.  */
7015
7016 static struct partial_symtab *
7017 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7018 {
7019   struct objfile *objfile = per_cu->objfile;
7020   struct partial_symtab *pst;
7021
7022   pst = start_psymtab_common (objfile, name, 0,
7023                               objfile->global_psymbols,
7024                               objfile->static_psymbols);
7025
7026   pst->psymtabs_addrmap_supported = 1;
7027
7028   /* This is the glue that links PST into GDB's symbol API.  */
7029   pst->read_symtab_private = per_cu;
7030   pst->read_symtab = dwarf2_read_symtab;
7031   per_cu->v.psymtab = pst;
7032
7033   return pst;
7034 }
7035
7036 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7037    type.  */
7038
7039 struct process_psymtab_comp_unit_data
7040 {
7041   /* True if we are reading a DW_TAG_partial_unit.  */
7042
7043   int want_partial_unit;
7044
7045   /* The "pretend" language that is used if the CU doesn't declare a
7046      language.  */
7047
7048   enum language pretend_language;
7049 };
7050
7051 /* die_reader_func for process_psymtab_comp_unit.  */
7052
7053 static void
7054 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7055                                   const gdb_byte *info_ptr,
7056                                   struct die_info *comp_unit_die,
7057                                   int has_children,
7058                                   void *data)
7059 {
7060   struct dwarf2_cu *cu = reader->cu;
7061   struct objfile *objfile = cu->objfile;
7062   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7063   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7064   CORE_ADDR baseaddr;
7065   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7066   struct partial_symtab *pst;
7067   enum pc_bounds_kind cu_bounds_kind;
7068   const char *filename;
7069   struct process_psymtab_comp_unit_data *info
7070     = (struct process_psymtab_comp_unit_data *) data;
7071
7072   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7073     return;
7074
7075   gdb_assert (! per_cu->is_debug_types);
7076
7077   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7078
7079   cu->list_in_scope = &file_symbols;
7080
7081   /* Allocate a new partial symbol table structure.  */
7082   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7083   if (filename == NULL)
7084     filename = "";
7085
7086   pst = create_partial_symtab (per_cu, filename);
7087
7088   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7089   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7090
7091   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7092
7093   dwarf2_find_base_address (comp_unit_die, cu);
7094
7095   /* Possibly set the default values of LOWPC and HIGHPC from
7096      `DW_AT_ranges'.  */
7097   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7098                                          &best_highpc, cu, pst);
7099   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7100     /* Store the contiguous range if it is not empty; it can be empty for
7101        CUs with no code.  */
7102     addrmap_set_empty (objfile->psymtabs_addrmap,
7103                        gdbarch_adjust_dwarf2_addr (gdbarch,
7104                                                    best_lowpc + baseaddr),
7105                        gdbarch_adjust_dwarf2_addr (gdbarch,
7106                                                    best_highpc + baseaddr) - 1,
7107                        pst);
7108
7109   /* Check if comp unit has_children.
7110      If so, read the rest of the partial symbols from this comp unit.
7111      If not, there's no more debug_info for this comp unit.  */
7112   if (has_children)
7113     {
7114       struct partial_die_info *first_die;
7115       CORE_ADDR lowpc, highpc;
7116
7117       lowpc = ((CORE_ADDR) -1);
7118       highpc = ((CORE_ADDR) 0);
7119
7120       first_die = load_partial_dies (reader, info_ptr, 1);
7121
7122       scan_partial_symbols (first_die, &lowpc, &highpc,
7123                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7124
7125       /* If we didn't find a lowpc, set it to highpc to avoid
7126          complaints from `maint check'.  */
7127       if (lowpc == ((CORE_ADDR) -1))
7128         lowpc = highpc;
7129
7130       /* If the compilation unit didn't have an explicit address range,
7131          then use the information extracted from its child dies.  */
7132       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7133         {
7134           best_lowpc = lowpc;
7135           best_highpc = highpc;
7136         }
7137     }
7138   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7139   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7140
7141   end_psymtab_common (objfile, pst);
7142
7143   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7144     {
7145       int i;
7146       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7147       struct dwarf2_per_cu_data *iter;
7148
7149       /* Fill in 'dependencies' here; we fill in 'users' in a
7150          post-pass.  */
7151       pst->number_of_dependencies = len;
7152       pst->dependencies =
7153         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7154       for (i = 0;
7155            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7156                         i, iter);
7157            ++i)
7158         pst->dependencies[i] = iter->v.psymtab;
7159
7160       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7161     }
7162
7163   /* Get the list of files included in the current compilation unit,
7164      and build a psymtab for each of them.  */
7165   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7166
7167   if (dwarf_read_debug)
7168     {
7169       struct gdbarch *gdbarch = get_objfile_arch (objfile);
7170
7171       fprintf_unfiltered (gdb_stdlog,
7172                           "Psymtab for %s unit @0x%x: %s - %s"
7173                           ", %d global, %d static syms\n",
7174                           per_cu->is_debug_types ? "type" : "comp",
7175                           to_underlying (per_cu->sect_off),
7176                           paddress (gdbarch, pst->textlow),
7177                           paddress (gdbarch, pst->texthigh),
7178                           pst->n_global_syms, pst->n_static_syms);
7179     }
7180 }
7181
7182 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7183    Process compilation unit THIS_CU for a psymtab.  */
7184
7185 static void
7186 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7187                            int want_partial_unit,
7188                            enum language pretend_language)
7189 {
7190   /* If this compilation unit was already read in, free the
7191      cached copy in order to read it in again.  This is
7192      necessary because we skipped some symbols when we first
7193      read in the compilation unit (see load_partial_dies).
7194      This problem could be avoided, but the benefit is unclear.  */
7195   if (this_cu->cu != NULL)
7196     free_one_cached_comp_unit (this_cu);
7197
7198   if (this_cu->is_debug_types)
7199     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
7200                              NULL);
7201   else
7202     {
7203       process_psymtab_comp_unit_data info;
7204       info.want_partial_unit = want_partial_unit;
7205       info.pretend_language = pretend_language;
7206       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
7207                                process_psymtab_comp_unit_reader, &info);
7208     }
7209
7210   /* Age out any secondary CUs.  */
7211   age_cached_comp_units ();
7212 }
7213
7214 /* Reader function for build_type_psymtabs.  */
7215
7216 static void
7217 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7218                             const gdb_byte *info_ptr,
7219                             struct die_info *type_unit_die,
7220                             int has_children,
7221                             void *data)
7222 {
7223   struct objfile *objfile = dwarf2_per_objfile->objfile;
7224   struct dwarf2_cu *cu = reader->cu;
7225   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7226   struct signatured_type *sig_type;
7227   struct type_unit_group *tu_group;
7228   struct attribute *attr;
7229   struct partial_die_info *first_die;
7230   CORE_ADDR lowpc, highpc;
7231   struct partial_symtab *pst;
7232
7233   gdb_assert (data == NULL);
7234   gdb_assert (per_cu->is_debug_types);
7235   sig_type = (struct signatured_type *) per_cu;
7236
7237   if (! has_children)
7238     return;
7239
7240   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7241   tu_group = get_type_unit_group (cu, attr);
7242
7243   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
7244
7245   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7246   cu->list_in_scope = &file_symbols;
7247   pst = create_partial_symtab (per_cu, "");
7248   pst->anonymous = 1;
7249
7250   first_die = load_partial_dies (reader, info_ptr, 1);
7251
7252   lowpc = (CORE_ADDR) -1;
7253   highpc = (CORE_ADDR) 0;
7254   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7255
7256   end_psymtab_common (objfile, pst);
7257 }
7258
7259 /* Struct used to sort TUs by their abbreviation table offset.  */
7260
7261 struct tu_abbrev_offset
7262 {
7263   struct signatured_type *sig_type;
7264   sect_offset abbrev_offset;
7265 };
7266
7267 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
7268
7269 static int
7270 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
7271 {
7272   const struct tu_abbrev_offset * const *a
7273     = (const struct tu_abbrev_offset * const*) ap;
7274   const struct tu_abbrev_offset * const *b
7275     = (const struct tu_abbrev_offset * const*) bp;
7276   sect_offset aoff = (*a)->abbrev_offset;
7277   sect_offset boff = (*b)->abbrev_offset;
7278
7279   return (aoff > boff) - (aoff < boff);
7280 }
7281
7282 /* Efficiently read all the type units.
7283    This does the bulk of the work for build_type_psymtabs.
7284
7285    The efficiency is because we sort TUs by the abbrev table they use and
7286    only read each abbrev table once.  In one program there are 200K TUs
7287    sharing 8K abbrev tables.
7288
7289    The main purpose of this function is to support building the
7290    dwarf2_per_objfile->type_unit_groups table.
7291    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7292    can collapse the search space by grouping them by stmt_list.
7293    The savings can be significant, in the same program from above the 200K TUs
7294    share 8K stmt_list tables.
7295
7296    FUNC is expected to call get_type_unit_group, which will create the
7297    struct type_unit_group if necessary and add it to
7298    dwarf2_per_objfile->type_unit_groups.  */
7299
7300 static void
7301 build_type_psymtabs_1 (void)
7302 {
7303   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7304   struct cleanup *cleanups;
7305   struct abbrev_table *abbrev_table;
7306   sect_offset abbrev_offset;
7307   struct tu_abbrev_offset *sorted_by_abbrev;
7308   int i;
7309
7310   /* It's up to the caller to not call us multiple times.  */
7311   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7312
7313   if (dwarf2_per_objfile->n_type_units == 0)
7314     return;
7315
7316   /* TUs typically share abbrev tables, and there can be way more TUs than
7317      abbrev tables.  Sort by abbrev table to reduce the number of times we
7318      read each abbrev table in.
7319      Alternatives are to punt or to maintain a cache of abbrev tables.
7320      This is simpler and efficient enough for now.
7321
7322      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7323      symtab to use).  Typically TUs with the same abbrev offset have the same
7324      stmt_list value too so in practice this should work well.
7325
7326      The basic algorithm here is:
7327
7328       sort TUs by abbrev table
7329       for each TU with same abbrev table:
7330         read abbrev table if first user
7331         read TU top level DIE
7332           [IWBN if DWO skeletons had DW_AT_stmt_list]
7333         call FUNC  */
7334
7335   if (dwarf_read_debug)
7336     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7337
7338   /* Sort in a separate table to maintain the order of all_type_units
7339      for .gdb_index: TU indices directly index all_type_units.  */
7340   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
7341                               dwarf2_per_objfile->n_type_units);
7342   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7343     {
7344       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
7345
7346       sorted_by_abbrev[i].sig_type = sig_type;
7347       sorted_by_abbrev[i].abbrev_offset =
7348         read_abbrev_offset (sig_type->per_cu.section,
7349                             sig_type->per_cu.sect_off);
7350     }
7351   cleanups = make_cleanup (xfree, sorted_by_abbrev);
7352   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
7353          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
7354
7355   abbrev_offset = (sect_offset) ~(unsigned) 0;
7356   abbrev_table = NULL;
7357   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
7358
7359   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7360     {
7361       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
7362
7363       /* Switch to the next abbrev table if necessary.  */
7364       if (abbrev_table == NULL
7365           || tu->abbrev_offset != abbrev_offset)
7366         {
7367           if (abbrev_table != NULL)
7368             {
7369               abbrev_table_free (abbrev_table);
7370               /* Reset to NULL in case abbrev_table_read_table throws
7371                  an error: abbrev_table_free_cleanup will get called.  */
7372               abbrev_table = NULL;
7373             }
7374           abbrev_offset = tu->abbrev_offset;
7375           abbrev_table =
7376             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
7377                                      abbrev_offset);
7378           ++tu_stats->nr_uniq_abbrev_tables;
7379         }
7380
7381       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
7382                                build_type_psymtabs_reader, NULL);
7383     }
7384
7385   do_cleanups (cleanups);
7386 }
7387
7388 /* Print collected type unit statistics.  */
7389
7390 static void
7391 print_tu_stats (void)
7392 {
7393   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7394
7395   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7396   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
7397                       dwarf2_per_objfile->n_type_units);
7398   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7399                       tu_stats->nr_uniq_abbrev_tables);
7400   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7401                       tu_stats->nr_symtabs);
7402   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7403                       tu_stats->nr_symtab_sharers);
7404   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
7405                       tu_stats->nr_stmt_less_type_units);
7406   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
7407                       tu_stats->nr_all_type_units_reallocs);
7408 }
7409
7410 /* Traversal function for build_type_psymtabs.  */
7411
7412 static int
7413 build_type_psymtab_dependencies (void **slot, void *info)
7414 {
7415   struct objfile *objfile = dwarf2_per_objfile->objfile;
7416   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7417   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7418   struct partial_symtab *pst = per_cu->v.psymtab;
7419   int len = VEC_length (sig_type_ptr, tu_group->tus);
7420   struct signatured_type *iter;
7421   int i;
7422
7423   gdb_assert (len > 0);
7424   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
7425
7426   pst->number_of_dependencies = len;
7427   pst->dependencies =
7428     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7429   for (i = 0;
7430        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
7431        ++i)
7432     {
7433       gdb_assert (iter->per_cu.is_debug_types);
7434       pst->dependencies[i] = iter->per_cu.v.psymtab;
7435       iter->type_unit_group = tu_group;
7436     }
7437
7438   VEC_free (sig_type_ptr, tu_group->tus);
7439
7440   return 1;
7441 }
7442
7443 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7444    Build partial symbol tables for the .debug_types comp-units.  */
7445
7446 static void
7447 build_type_psymtabs (struct objfile *objfile)
7448 {
7449   if (! create_all_type_units (objfile))
7450     return;
7451
7452   build_type_psymtabs_1 ();
7453 }
7454
7455 /* Traversal function for process_skeletonless_type_unit.
7456    Read a TU in a DWO file and build partial symbols for it.  */
7457
7458 static int
7459 process_skeletonless_type_unit (void **slot, void *info)
7460 {
7461   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7462   struct objfile *objfile = (struct objfile *) info;
7463   struct signatured_type find_entry, *entry;
7464
7465   /* If this TU doesn't exist in the global table, add it and read it in.  */
7466
7467   if (dwarf2_per_objfile->signatured_types == NULL)
7468     {
7469       dwarf2_per_objfile->signatured_types
7470         = allocate_signatured_type_table (objfile);
7471     }
7472
7473   find_entry.signature = dwo_unit->signature;
7474   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
7475                          INSERT);
7476   /* If we've already seen this type there's nothing to do.  What's happening
7477      is we're doing our own version of comdat-folding here.  */
7478   if (*slot != NULL)
7479     return 1;
7480
7481   /* This does the job that create_all_type_units would have done for
7482      this TU.  */
7483   entry = add_type_unit (dwo_unit->signature, slot);
7484   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
7485   *slot = entry;
7486
7487   /* This does the job that build_type_psymtabs_1 would have done.  */
7488   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
7489                            build_type_psymtabs_reader, NULL);
7490
7491   return 1;
7492 }
7493
7494 /* Traversal function for process_skeletonless_type_units.  */
7495
7496 static int
7497 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7498 {
7499   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7500
7501   if (dwo_file->tus != NULL)
7502     {
7503       htab_traverse_noresize (dwo_file->tus,
7504                               process_skeletonless_type_unit, info);
7505     }
7506
7507   return 1;
7508 }
7509
7510 /* Scan all TUs of DWO files, verifying we've processed them.
7511    This is needed in case a TU was emitted without its skeleton.
7512    Note: This can't be done until we know what all the DWO files are.  */
7513
7514 static void
7515 process_skeletonless_type_units (struct objfile *objfile)
7516 {
7517   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7518   if (get_dwp_file () == NULL
7519       && dwarf2_per_objfile->dwo_files != NULL)
7520     {
7521       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
7522                               process_dwo_file_for_skeletonless_type_units,
7523                               objfile);
7524     }
7525 }
7526
7527 /* Compute the 'user' field for each psymtab in OBJFILE.  */
7528
7529 static void
7530 set_partial_user (struct objfile *objfile)
7531 {
7532   int i;
7533
7534   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7535     {
7536       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7537       struct partial_symtab *pst = per_cu->v.psymtab;
7538       int j;
7539
7540       if (pst == NULL)
7541         continue;
7542
7543       for (j = 0; j < pst->number_of_dependencies; ++j)
7544         {
7545           /* Set the 'user' field only if it is not already set.  */
7546           if (pst->dependencies[j]->user == NULL)
7547             pst->dependencies[j]->user = pst;
7548         }
7549     }
7550 }
7551
7552 /* Build the partial symbol table by doing a quick pass through the
7553    .debug_info and .debug_abbrev sections.  */
7554
7555 static void
7556 dwarf2_build_psymtabs_hard (struct objfile *objfile)
7557 {
7558   struct cleanup *back_to;
7559   int i;
7560
7561   if (dwarf_read_debug)
7562     {
7563       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7564                           objfile_name (objfile));
7565     }
7566
7567   dwarf2_per_objfile->reading_partial_symbols = 1;
7568
7569   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7570
7571   /* Any cached compilation units will be linked by the per-objfile
7572      read_in_chain.  Make sure to free them when we're done.  */
7573   back_to = make_cleanup (free_cached_comp_units, NULL);
7574
7575   build_type_psymtabs (objfile);
7576
7577   create_all_comp_units (objfile);
7578
7579   /* Create a temporary address map on a temporary obstack.  We later
7580      copy this to the final obstack.  */
7581   auto_obstack temp_obstack;
7582
7583   scoped_restore save_psymtabs_addrmap
7584     = make_scoped_restore (&objfile->psymtabs_addrmap,
7585                            addrmap_create_mutable (&temp_obstack));
7586
7587   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7588     {
7589       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7590
7591       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7592     }
7593
7594   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7595   process_skeletonless_type_units (objfile);
7596
7597   /* Now that all TUs have been processed we can fill in the dependencies.  */
7598   if (dwarf2_per_objfile->type_unit_groups != NULL)
7599     {
7600       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7601                               build_type_psymtab_dependencies, NULL);
7602     }
7603
7604   if (dwarf_read_debug)
7605     print_tu_stats ();
7606
7607   set_partial_user (objfile);
7608
7609   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7610                                                     &objfile->objfile_obstack);
7611   /* At this point we want to keep the address map.  */
7612   save_psymtabs_addrmap.release ();
7613
7614   do_cleanups (back_to);
7615
7616   if (dwarf_read_debug)
7617     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7618                         objfile_name (objfile));
7619 }
7620
7621 /* die_reader_func for load_partial_comp_unit.  */
7622
7623 static void
7624 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7625                                const gdb_byte *info_ptr,
7626                                struct die_info *comp_unit_die,
7627                                int has_children,
7628                                void *data)
7629 {
7630   struct dwarf2_cu *cu = reader->cu;
7631
7632   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7633
7634   /* Check if comp unit has_children.
7635      If so, read the rest of the partial symbols from this comp unit.
7636      If not, there's no more debug_info for this comp unit.  */
7637   if (has_children)
7638     load_partial_dies (reader, info_ptr, 0);
7639 }
7640
7641 /* Load the partial DIEs for a secondary CU into memory.
7642    This is also used when rereading a primary CU with load_all_dies.  */
7643
7644 static void
7645 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7646 {
7647   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7648                            load_partial_comp_unit_reader, NULL);
7649 }
7650
7651 static void
7652 read_comp_units_from_section (struct objfile *objfile,
7653                               struct dwarf2_section_info *section,
7654                               struct dwarf2_section_info *abbrev_section,
7655                               unsigned int is_dwz,
7656                               int *n_allocated,
7657                               int *n_comp_units,
7658                               struct dwarf2_per_cu_data ***all_comp_units)
7659 {
7660   const gdb_byte *info_ptr;
7661
7662   if (dwarf_read_debug)
7663     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7664                         get_section_name (section),
7665                         get_section_file_name (section));
7666
7667   dwarf2_read_section (objfile, section);
7668
7669   info_ptr = section->buffer;
7670
7671   while (info_ptr < section->buffer + section->size)
7672     {
7673       struct dwarf2_per_cu_data *this_cu;
7674
7675       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7676
7677       comp_unit_head cu_header;
7678       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7679                                      info_ptr, rcuh_kind::COMPILE);
7680
7681       /* Save the compilation unit for later lookup.  */
7682       if (cu_header.unit_type != DW_UT_type)
7683         {
7684           this_cu = XOBNEW (&objfile->objfile_obstack,
7685                             struct dwarf2_per_cu_data);
7686           memset (this_cu, 0, sizeof (*this_cu));
7687         }
7688       else
7689         {
7690           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7691                                   struct signatured_type);
7692           memset (sig_type, 0, sizeof (*sig_type));
7693           sig_type->signature = cu_header.signature;
7694           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7695           this_cu = &sig_type->per_cu;
7696         }
7697       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7698       this_cu->sect_off = sect_off;
7699       this_cu->length = cu_header.length + cu_header.initial_length_size;
7700       this_cu->is_dwz = is_dwz;
7701       this_cu->objfile = objfile;
7702       this_cu->section = section;
7703
7704       if (*n_comp_units == *n_allocated)
7705         {
7706           *n_allocated *= 2;
7707           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7708                                         *all_comp_units, *n_allocated);
7709         }
7710       (*all_comp_units)[*n_comp_units] = this_cu;
7711       ++*n_comp_units;
7712
7713       info_ptr = info_ptr + this_cu->length;
7714     }
7715 }
7716
7717 /* Create a list of all compilation units in OBJFILE.
7718    This is only done for -readnow and building partial symtabs.  */
7719
7720 static void
7721 create_all_comp_units (struct objfile *objfile)
7722 {
7723   int n_allocated;
7724   int n_comp_units;
7725   struct dwarf2_per_cu_data **all_comp_units;
7726   struct dwz_file *dwz;
7727
7728   n_comp_units = 0;
7729   n_allocated = 10;
7730   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7731
7732   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7733                                 &dwarf2_per_objfile->abbrev, 0,
7734                                 &n_allocated, &n_comp_units, &all_comp_units);
7735
7736   dwz = dwarf2_get_dwz_file ();
7737   if (dwz != NULL)
7738     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7739                                   &n_allocated, &n_comp_units,
7740                                   &all_comp_units);
7741
7742   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7743                                                   struct dwarf2_per_cu_data *,
7744                                                   n_comp_units);
7745   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7746           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7747   xfree (all_comp_units);
7748   dwarf2_per_objfile->n_comp_units = n_comp_units;
7749 }
7750
7751 /* Process all loaded DIEs for compilation unit CU, starting at
7752    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7753    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7754    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7755    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7756
7757 static void
7758 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7759                       CORE_ADDR *highpc, int set_addrmap,
7760                       struct dwarf2_cu *cu)
7761 {
7762   struct partial_die_info *pdi;
7763
7764   /* Now, march along the PDI's, descending into ones which have
7765      interesting children but skipping the children of the other ones,
7766      until we reach the end of the compilation unit.  */
7767
7768   pdi = first_die;
7769
7770   while (pdi != NULL)
7771     {
7772       fixup_partial_die (pdi, cu);
7773
7774       /* Anonymous namespaces or modules have no name but have interesting
7775          children, so we need to look at them.  Ditto for anonymous
7776          enums.  */
7777
7778       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7779           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7780           || pdi->tag == DW_TAG_imported_unit)
7781         {
7782           switch (pdi->tag)
7783             {
7784             case DW_TAG_subprogram:
7785               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7786               break;
7787             case DW_TAG_constant:
7788             case DW_TAG_variable:
7789             case DW_TAG_typedef:
7790             case DW_TAG_union_type:
7791               if (!pdi->is_declaration)
7792                 {
7793                   add_partial_symbol (pdi, cu);
7794                 }
7795               break;
7796             case DW_TAG_class_type:
7797             case DW_TAG_interface_type:
7798             case DW_TAG_structure_type:
7799               if (!pdi->is_declaration)
7800                 {
7801                   add_partial_symbol (pdi, cu);
7802                 }
7803               if (cu->language == language_rust && pdi->has_children)
7804                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7805                                       set_addrmap, cu);
7806               break;
7807             case DW_TAG_enumeration_type:
7808               if (!pdi->is_declaration)
7809                 add_partial_enumeration (pdi, cu);
7810               break;
7811             case DW_TAG_base_type:
7812             case DW_TAG_subrange_type:
7813               /* File scope base type definitions are added to the partial
7814                  symbol table.  */
7815               add_partial_symbol (pdi, cu);
7816               break;
7817             case DW_TAG_namespace:
7818               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7819               break;
7820             case DW_TAG_module:
7821               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7822               break;
7823             case DW_TAG_imported_unit:
7824               {
7825                 struct dwarf2_per_cu_data *per_cu;
7826
7827                 /* For now we don't handle imported units in type units.  */
7828                 if (cu->per_cu->is_debug_types)
7829                   {
7830                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7831                              " supported in type units [in module %s]"),
7832                            objfile_name (cu->objfile));
7833                   }
7834
7835                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7836                                                            pdi->is_dwz,
7837                                                            cu->objfile);
7838
7839                 /* Go read the partial unit, if needed.  */
7840                 if (per_cu->v.psymtab == NULL)
7841                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7842
7843                 VEC_safe_push (dwarf2_per_cu_ptr,
7844                                cu->per_cu->imported_symtabs, per_cu);
7845               }
7846               break;
7847             case DW_TAG_imported_declaration:
7848               add_partial_symbol (pdi, cu);
7849               break;
7850             default:
7851               break;
7852             }
7853         }
7854
7855       /* If the die has a sibling, skip to the sibling.  */
7856
7857       pdi = pdi->die_sibling;
7858     }
7859 }
7860
7861 /* Functions used to compute the fully scoped name of a partial DIE.
7862
7863    Normally, this is simple.  For C++, the parent DIE's fully scoped
7864    name is concatenated with "::" and the partial DIE's name.
7865    Enumerators are an exception; they use the scope of their parent
7866    enumeration type, i.e. the name of the enumeration type is not
7867    prepended to the enumerator.
7868
7869    There are two complexities.  One is DW_AT_specification; in this
7870    case "parent" means the parent of the target of the specification,
7871    instead of the direct parent of the DIE.  The other is compilers
7872    which do not emit DW_TAG_namespace; in this case we try to guess
7873    the fully qualified name of structure types from their members'
7874    linkage names.  This must be done using the DIE's children rather
7875    than the children of any DW_AT_specification target.  We only need
7876    to do this for structures at the top level, i.e. if the target of
7877    any DW_AT_specification (if any; otherwise the DIE itself) does not
7878    have a parent.  */
7879
7880 /* Compute the scope prefix associated with PDI's parent, in
7881    compilation unit CU.  The result will be allocated on CU's
7882    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7883    field.  NULL is returned if no prefix is necessary.  */
7884 static const char *
7885 partial_die_parent_scope (struct partial_die_info *pdi,
7886                           struct dwarf2_cu *cu)
7887 {
7888   const char *grandparent_scope;
7889   struct partial_die_info *parent, *real_pdi;
7890
7891   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7892      then this means the parent of the specification DIE.  */
7893
7894   real_pdi = pdi;
7895   while (real_pdi->has_specification)
7896     real_pdi = find_partial_die (real_pdi->spec_offset,
7897                                  real_pdi->spec_is_dwz, cu);
7898
7899   parent = real_pdi->die_parent;
7900   if (parent == NULL)
7901     return NULL;
7902
7903   if (parent->scope_set)
7904     return parent->scope;
7905
7906   fixup_partial_die (parent, cu);
7907
7908   grandparent_scope = partial_die_parent_scope (parent, cu);
7909
7910   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7911      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7912      Work around this problem here.  */
7913   if (cu->language == language_cplus
7914       && parent->tag == DW_TAG_namespace
7915       && strcmp (parent->name, "::") == 0
7916       && grandparent_scope == NULL)
7917     {
7918       parent->scope = NULL;
7919       parent->scope_set = 1;
7920       return NULL;
7921     }
7922
7923   if (pdi->tag == DW_TAG_enumerator)
7924     /* Enumerators should not get the name of the enumeration as a prefix.  */
7925     parent->scope = grandparent_scope;
7926   else if (parent->tag == DW_TAG_namespace
7927       || parent->tag == DW_TAG_module
7928       || parent->tag == DW_TAG_structure_type
7929       || parent->tag == DW_TAG_class_type
7930       || parent->tag == DW_TAG_interface_type
7931       || parent->tag == DW_TAG_union_type
7932       || parent->tag == DW_TAG_enumeration_type)
7933     {
7934       if (grandparent_scope == NULL)
7935         parent->scope = parent->name;
7936       else
7937         parent->scope = typename_concat (&cu->comp_unit_obstack,
7938                                          grandparent_scope,
7939                                          parent->name, 0, cu);
7940     }
7941   else
7942     {
7943       /* FIXME drow/2004-04-01: What should we be doing with
7944          function-local names?  For partial symbols, we should probably be
7945          ignoring them.  */
7946       complaint (&symfile_complaints,
7947                  _("unhandled containing DIE tag %d for DIE at %d"),
7948                  parent->tag, to_underlying (pdi->sect_off));
7949       parent->scope = grandparent_scope;
7950     }
7951
7952   parent->scope_set = 1;
7953   return parent->scope;
7954 }
7955
7956 /* Return the fully scoped name associated with PDI, from compilation unit
7957    CU.  The result will be allocated with malloc.  */
7958
7959 static char *
7960 partial_die_full_name (struct partial_die_info *pdi,
7961                        struct dwarf2_cu *cu)
7962 {
7963   const char *parent_scope;
7964
7965   /* If this is a template instantiation, we can not work out the
7966      template arguments from partial DIEs.  So, unfortunately, we have
7967      to go through the full DIEs.  At least any work we do building
7968      types here will be reused if full symbols are loaded later.  */
7969   if (pdi->has_template_arguments)
7970     {
7971       fixup_partial_die (pdi, cu);
7972
7973       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7974         {
7975           struct die_info *die;
7976           struct attribute attr;
7977           struct dwarf2_cu *ref_cu = cu;
7978
7979           /* DW_FORM_ref_addr is using section offset.  */
7980           attr.name = (enum dwarf_attribute) 0;
7981           attr.form = DW_FORM_ref_addr;
7982           attr.u.unsnd = to_underlying (pdi->sect_off);
7983           die = follow_die_ref (NULL, &attr, &ref_cu);
7984
7985           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7986         }
7987     }
7988
7989   parent_scope = partial_die_parent_scope (pdi, cu);
7990   if (parent_scope == NULL)
7991     return NULL;
7992   else
7993     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7994 }
7995
7996 static void
7997 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7998 {
7999   struct objfile *objfile = cu->objfile;
8000   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8001   CORE_ADDR addr = 0;
8002   const char *actual_name = NULL;
8003   CORE_ADDR baseaddr;
8004   char *built_actual_name;
8005
8006   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8007
8008   built_actual_name = partial_die_full_name (pdi, cu);
8009   if (built_actual_name != NULL)
8010     actual_name = built_actual_name;
8011
8012   if (actual_name == NULL)
8013     actual_name = pdi->name;
8014
8015   switch (pdi->tag)
8016     {
8017     case DW_TAG_subprogram:
8018       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8019       if (pdi->is_external || cu->language == language_ada)
8020         {
8021           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8022              of the global scope.  But in Ada, we want to be able to access
8023              nested procedures globally.  So all Ada subprograms are stored
8024              in the global scope.  */
8025           add_psymbol_to_list (actual_name, strlen (actual_name),
8026                                built_actual_name != NULL,
8027                                VAR_DOMAIN, LOC_BLOCK,
8028                                &objfile->global_psymbols,
8029                                addr, cu->language, objfile);
8030         }
8031       else
8032         {
8033           add_psymbol_to_list (actual_name, strlen (actual_name),
8034                                built_actual_name != NULL,
8035                                VAR_DOMAIN, LOC_BLOCK,
8036                                &objfile->static_psymbols,
8037                                addr, cu->language, objfile);
8038         }
8039
8040       if (pdi->main_subprogram && actual_name != NULL)
8041         set_objfile_main_name (objfile, actual_name, cu->language);
8042       break;
8043     case DW_TAG_constant:
8044       {
8045         std::vector<partial_symbol *> *list;
8046
8047         if (pdi->is_external)
8048           list = &objfile->global_psymbols;
8049         else
8050           list = &objfile->static_psymbols;
8051         add_psymbol_to_list (actual_name, strlen (actual_name),
8052                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8053                              list, 0, cu->language, objfile);
8054       }
8055       break;
8056     case DW_TAG_variable:
8057       if (pdi->d.locdesc)
8058         addr = decode_locdesc (pdi->d.locdesc, cu);
8059
8060       if (pdi->d.locdesc
8061           && addr == 0
8062           && !dwarf2_per_objfile->has_section_at_zero)
8063         {
8064           /* A global or static variable may also have been stripped
8065              out by the linker if unused, in which case its address
8066              will be nullified; do not add such variables into partial
8067              symbol table then.  */
8068         }
8069       else if (pdi->is_external)
8070         {
8071           /* Global Variable.
8072              Don't enter into the minimal symbol tables as there is
8073              a minimal symbol table entry from the ELF symbols already.
8074              Enter into partial symbol table if it has a location
8075              descriptor or a type.
8076              If the location descriptor is missing, new_symbol will create
8077              a LOC_UNRESOLVED symbol, the address of the variable will then
8078              be determined from the minimal symbol table whenever the variable
8079              is referenced.
8080              The address for the partial symbol table entry is not
8081              used by GDB, but it comes in handy for debugging partial symbol
8082              table building.  */
8083
8084           if (pdi->d.locdesc || pdi->has_type)
8085             add_psymbol_to_list (actual_name, strlen (actual_name),
8086                                  built_actual_name != NULL,
8087                                  VAR_DOMAIN, LOC_STATIC,
8088                                  &objfile->global_psymbols,
8089                                  addr + baseaddr,
8090                                  cu->language, objfile);
8091         }
8092       else
8093         {
8094           int has_loc = pdi->d.locdesc != NULL;
8095
8096           /* Static Variable.  Skip symbols whose value we cannot know (those
8097              without location descriptors or constant values).  */
8098           if (!has_loc && !pdi->has_const_value)
8099             {
8100               xfree (built_actual_name);
8101               return;
8102             }
8103
8104           add_psymbol_to_list (actual_name, strlen (actual_name),
8105                                built_actual_name != NULL,
8106                                VAR_DOMAIN, LOC_STATIC,
8107                                &objfile->static_psymbols,
8108                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8109                                cu->language, objfile);
8110         }
8111       break;
8112     case DW_TAG_typedef:
8113     case DW_TAG_base_type:
8114     case DW_TAG_subrange_type:
8115       add_psymbol_to_list (actual_name, strlen (actual_name),
8116                            built_actual_name != NULL,
8117                            VAR_DOMAIN, LOC_TYPEDEF,
8118                            &objfile->static_psymbols,
8119                            0, cu->language, objfile);
8120       break;
8121     case DW_TAG_imported_declaration:
8122     case DW_TAG_namespace:
8123       add_psymbol_to_list (actual_name, strlen (actual_name),
8124                            built_actual_name != NULL,
8125                            VAR_DOMAIN, LOC_TYPEDEF,
8126                            &objfile->global_psymbols,
8127                            0, cu->language, objfile);
8128       break;
8129     case DW_TAG_module:
8130       add_psymbol_to_list (actual_name, strlen (actual_name),
8131                            built_actual_name != NULL,
8132                            MODULE_DOMAIN, LOC_TYPEDEF,
8133                            &objfile->global_psymbols,
8134                            0, cu->language, objfile);
8135       break;
8136     case DW_TAG_class_type:
8137     case DW_TAG_interface_type:
8138     case DW_TAG_structure_type:
8139     case DW_TAG_union_type:
8140     case DW_TAG_enumeration_type:
8141       /* Skip external references.  The DWARF standard says in the section
8142          about "Structure, Union, and Class Type Entries": "An incomplete
8143          structure, union or class type is represented by a structure,
8144          union or class entry that does not have a byte size attribute
8145          and that has a DW_AT_declaration attribute."  */
8146       if (!pdi->has_byte_size && pdi->is_declaration)
8147         {
8148           xfree (built_actual_name);
8149           return;
8150         }
8151
8152       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8153          static vs. global.  */
8154       add_psymbol_to_list (actual_name, strlen (actual_name),
8155                            built_actual_name != NULL,
8156                            STRUCT_DOMAIN, LOC_TYPEDEF,
8157                            cu->language == language_cplus
8158                            ? &objfile->global_psymbols
8159                            : &objfile->static_psymbols,
8160                            0, cu->language, objfile);
8161
8162       break;
8163     case DW_TAG_enumerator:
8164       add_psymbol_to_list (actual_name, strlen (actual_name),
8165                            built_actual_name != NULL,
8166                            VAR_DOMAIN, LOC_CONST,
8167                            cu->language == language_cplus
8168                            ? &objfile->global_psymbols
8169                            : &objfile->static_psymbols,
8170                            0, cu->language, objfile);
8171       break;
8172     default:
8173       break;
8174     }
8175
8176   xfree (built_actual_name);
8177 }
8178
8179 /* Read a partial die corresponding to a namespace; also, add a symbol
8180    corresponding to that namespace to the symbol table.  NAMESPACE is
8181    the name of the enclosing namespace.  */
8182
8183 static void
8184 add_partial_namespace (struct partial_die_info *pdi,
8185                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8186                        int set_addrmap, struct dwarf2_cu *cu)
8187 {
8188   /* Add a symbol for the namespace.  */
8189
8190   add_partial_symbol (pdi, cu);
8191
8192   /* Now scan partial symbols in that namespace.  */
8193
8194   if (pdi->has_children)
8195     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8196 }
8197
8198 /* Read a partial die corresponding to a Fortran module.  */
8199
8200 static void
8201 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8202                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8203 {
8204   /* Add a symbol for the namespace.  */
8205
8206   add_partial_symbol (pdi, cu);
8207
8208   /* Now scan partial symbols in that module.  */
8209
8210   if (pdi->has_children)
8211     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8212 }
8213
8214 /* Read a partial die corresponding to a subprogram and create a partial
8215    symbol for that subprogram.  When the CU language allows it, this
8216    routine also defines a partial symbol for each nested subprogram
8217    that this subprogram contains.  If SET_ADDRMAP is true, record the
8218    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
8219    and highest PC values found in PDI.
8220
8221    PDI may also be a lexical block, in which case we simply search
8222    recursively for subprograms defined inside that lexical block.
8223    Again, this is only performed when the CU language allows this
8224    type of definitions.  */
8225
8226 static void
8227 add_partial_subprogram (struct partial_die_info *pdi,
8228                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8229                         int set_addrmap, struct dwarf2_cu *cu)
8230 {
8231   if (pdi->tag == DW_TAG_subprogram)
8232     {
8233       if (pdi->has_pc_info)
8234         {
8235           if (pdi->lowpc < *lowpc)
8236             *lowpc = pdi->lowpc;
8237           if (pdi->highpc > *highpc)
8238             *highpc = pdi->highpc;
8239           if (set_addrmap)
8240             {
8241               struct objfile *objfile = cu->objfile;
8242               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8243               CORE_ADDR baseaddr;
8244               CORE_ADDR highpc;
8245               CORE_ADDR lowpc;
8246
8247               baseaddr = ANOFFSET (objfile->section_offsets,
8248                                    SECT_OFF_TEXT (objfile));
8249               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8250                                                   pdi->lowpc + baseaddr);
8251               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8252                                                    pdi->highpc + baseaddr);
8253               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
8254                                  cu->per_cu->v.psymtab);
8255             }
8256         }
8257
8258       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8259         {
8260           if (!pdi->is_declaration)
8261             /* Ignore subprogram DIEs that do not have a name, they are
8262                illegal.  Do not emit a complaint at this point, we will
8263                do so when we convert this psymtab into a symtab.  */
8264             if (pdi->name)
8265               add_partial_symbol (pdi, cu);
8266         }
8267     }
8268
8269   if (! pdi->has_children)
8270     return;
8271
8272   if (cu->language == language_ada)
8273     {
8274       pdi = pdi->die_child;
8275       while (pdi != NULL)
8276         {
8277           fixup_partial_die (pdi, cu);
8278           if (pdi->tag == DW_TAG_subprogram
8279               || pdi->tag == DW_TAG_lexical_block)
8280             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8281           pdi = pdi->die_sibling;
8282         }
8283     }
8284 }
8285
8286 /* Read a partial die corresponding to an enumeration type.  */
8287
8288 static void
8289 add_partial_enumeration (struct partial_die_info *enum_pdi,
8290                          struct dwarf2_cu *cu)
8291 {
8292   struct partial_die_info *pdi;
8293
8294   if (enum_pdi->name != NULL)
8295     add_partial_symbol (enum_pdi, cu);
8296
8297   pdi = enum_pdi->die_child;
8298   while (pdi)
8299     {
8300       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8301         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
8302       else
8303         add_partial_symbol (pdi, cu);
8304       pdi = pdi->die_sibling;
8305     }
8306 }
8307
8308 /* Return the initial uleb128 in the die at INFO_PTR.  */
8309
8310 static unsigned int
8311 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8312 {
8313   unsigned int bytes_read;
8314
8315   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8316 }
8317
8318 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
8319    Return the corresponding abbrev, or NULL if the number is zero (indicating
8320    an empty DIE).  In either case *BYTES_READ will be set to the length of
8321    the initial number.  */
8322
8323 static struct abbrev_info *
8324 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
8325                  struct dwarf2_cu *cu)
8326 {
8327   bfd *abfd = cu->objfile->obfd;
8328   unsigned int abbrev_number;
8329   struct abbrev_info *abbrev;
8330
8331   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8332
8333   if (abbrev_number == 0)
8334     return NULL;
8335
8336   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
8337   if (!abbrev)
8338     {
8339       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8340                " at offset 0x%x [in module %s]"),
8341              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8342              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
8343     }
8344
8345   return abbrev;
8346 }
8347
8348 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8349    Returns a pointer to the end of a series of DIEs, terminated by an empty
8350    DIE.  Any children of the skipped DIEs will also be skipped.  */
8351
8352 static const gdb_byte *
8353 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8354 {
8355   struct dwarf2_cu *cu = reader->cu;
8356   struct abbrev_info *abbrev;
8357   unsigned int bytes_read;
8358
8359   while (1)
8360     {
8361       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
8362       if (abbrev == NULL)
8363         return info_ptr + bytes_read;
8364       else
8365         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8366     }
8367 }
8368
8369 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8370    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8371    abbrev corresponding to that skipped uleb128 should be passed in
8372    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8373    children.  */
8374
8375 static const gdb_byte *
8376 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8377               struct abbrev_info *abbrev)
8378 {
8379   unsigned int bytes_read;
8380   struct attribute attr;
8381   bfd *abfd = reader->abfd;
8382   struct dwarf2_cu *cu = reader->cu;
8383   const gdb_byte *buffer = reader->buffer;
8384   const gdb_byte *buffer_end = reader->buffer_end;
8385   unsigned int form, i;
8386
8387   for (i = 0; i < abbrev->num_attrs; i++)
8388     {
8389       /* The only abbrev we care about is DW_AT_sibling.  */
8390       if (abbrev->attrs[i].name == DW_AT_sibling)
8391         {
8392           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8393           if (attr.form == DW_FORM_ref_addr)
8394             complaint (&symfile_complaints,
8395                        _("ignoring absolute DW_AT_sibling"));
8396           else
8397             {
8398               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8399               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8400
8401               if (sibling_ptr < info_ptr)
8402                 complaint (&symfile_complaints,
8403                            _("DW_AT_sibling points backwards"));
8404               else if (sibling_ptr > reader->buffer_end)
8405                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8406               else
8407                 return sibling_ptr;
8408             }
8409         }
8410
8411       /* If it isn't DW_AT_sibling, skip this attribute.  */
8412       form = abbrev->attrs[i].form;
8413     skip_attribute:
8414       switch (form)
8415         {
8416         case DW_FORM_ref_addr:
8417           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8418              and later it is offset sized.  */
8419           if (cu->header.version == 2)
8420             info_ptr += cu->header.addr_size;
8421           else
8422             info_ptr += cu->header.offset_size;
8423           break;
8424         case DW_FORM_GNU_ref_alt:
8425           info_ptr += cu->header.offset_size;
8426           break;
8427         case DW_FORM_addr:
8428           info_ptr += cu->header.addr_size;
8429           break;
8430         case DW_FORM_data1:
8431         case DW_FORM_ref1:
8432         case DW_FORM_flag:
8433           info_ptr += 1;
8434           break;
8435         case DW_FORM_flag_present:
8436         case DW_FORM_implicit_const:
8437           break;
8438         case DW_FORM_data2:
8439         case DW_FORM_ref2:
8440           info_ptr += 2;
8441           break;
8442         case DW_FORM_data4:
8443         case DW_FORM_ref4:
8444           info_ptr += 4;
8445           break;
8446         case DW_FORM_data8:
8447         case DW_FORM_ref8:
8448         case DW_FORM_ref_sig8:
8449           info_ptr += 8;
8450           break;
8451         case DW_FORM_data16:
8452           info_ptr += 16;
8453           break;
8454         case DW_FORM_string:
8455           read_direct_string (abfd, info_ptr, &bytes_read);
8456           info_ptr += bytes_read;
8457           break;
8458         case DW_FORM_sec_offset:
8459         case DW_FORM_strp:
8460         case DW_FORM_GNU_strp_alt:
8461           info_ptr += cu->header.offset_size;
8462           break;
8463         case DW_FORM_exprloc:
8464         case DW_FORM_block:
8465           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8466           info_ptr += bytes_read;
8467           break;
8468         case DW_FORM_block1:
8469           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8470           break;
8471         case DW_FORM_block2:
8472           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8473           break;
8474         case DW_FORM_block4:
8475           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8476           break;
8477         case DW_FORM_sdata:
8478         case DW_FORM_udata:
8479         case DW_FORM_ref_udata:
8480         case DW_FORM_GNU_addr_index:
8481         case DW_FORM_GNU_str_index:
8482           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8483           break;
8484         case DW_FORM_indirect:
8485           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8486           info_ptr += bytes_read;
8487           /* We need to continue parsing from here, so just go back to
8488              the top.  */
8489           goto skip_attribute;
8490
8491         default:
8492           error (_("Dwarf Error: Cannot handle %s "
8493                    "in DWARF reader [in module %s]"),
8494                  dwarf_form_name (form),
8495                  bfd_get_filename (abfd));
8496         }
8497     }
8498
8499   if (abbrev->has_children)
8500     return skip_children (reader, info_ptr);
8501   else
8502     return info_ptr;
8503 }
8504
8505 /* Locate ORIG_PDI's sibling.
8506    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8507
8508 static const gdb_byte *
8509 locate_pdi_sibling (const struct die_reader_specs *reader,
8510                     struct partial_die_info *orig_pdi,
8511                     const gdb_byte *info_ptr)
8512 {
8513   /* Do we know the sibling already?  */
8514
8515   if (orig_pdi->sibling)
8516     return orig_pdi->sibling;
8517
8518   /* Are there any children to deal with?  */
8519
8520   if (!orig_pdi->has_children)
8521     return info_ptr;
8522
8523   /* Skip the children the long way.  */
8524
8525   return skip_children (reader, info_ptr);
8526 }
8527
8528 /* Expand this partial symbol table into a full symbol table.  SELF is
8529    not NULL.  */
8530
8531 static void
8532 dwarf2_read_symtab (struct partial_symtab *self,
8533                     struct objfile *objfile)
8534 {
8535   if (self->readin)
8536     {
8537       warning (_("bug: psymtab for %s is already read in."),
8538                self->filename);
8539     }
8540   else
8541     {
8542       if (info_verbose)
8543         {
8544           printf_filtered (_("Reading in symbols for %s..."),
8545                            self->filename);
8546           gdb_flush (gdb_stdout);
8547         }
8548
8549       /* Restore our global data.  */
8550       dwarf2_per_objfile
8551         = (struct dwarf2_per_objfile *) objfile_data (objfile,
8552                                                       dwarf2_objfile_data_key);
8553
8554       /* If this psymtab is constructed from a debug-only objfile, the
8555          has_section_at_zero flag will not necessarily be correct.  We
8556          can get the correct value for this flag by looking at the data
8557          associated with the (presumably stripped) associated objfile.  */
8558       if (objfile->separate_debug_objfile_backlink)
8559         {
8560           struct dwarf2_per_objfile *dpo_backlink
8561             = ((struct dwarf2_per_objfile *)
8562                objfile_data (objfile->separate_debug_objfile_backlink,
8563                              dwarf2_objfile_data_key));
8564
8565           dwarf2_per_objfile->has_section_at_zero
8566             = dpo_backlink->has_section_at_zero;
8567         }
8568
8569       dwarf2_per_objfile->reading_partial_symbols = 0;
8570
8571       psymtab_to_symtab_1 (self);
8572
8573       /* Finish up the debug error message.  */
8574       if (info_verbose)
8575         printf_filtered (_("done.\n"));
8576     }
8577
8578   process_cu_includes ();
8579 }
8580 \f
8581 /* Reading in full CUs.  */
8582
8583 /* Add PER_CU to the queue.  */
8584
8585 static void
8586 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8587                  enum language pretend_language)
8588 {
8589   struct dwarf2_queue_item *item;
8590
8591   per_cu->queued = 1;
8592   item = XNEW (struct dwarf2_queue_item);
8593   item->per_cu = per_cu;
8594   item->pretend_language = pretend_language;
8595   item->next = NULL;
8596
8597   if (dwarf2_queue == NULL)
8598     dwarf2_queue = item;
8599   else
8600     dwarf2_queue_tail->next = item;
8601
8602   dwarf2_queue_tail = item;
8603 }
8604
8605 /* If PER_CU is not yet queued, add it to the queue.
8606    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8607    dependency.
8608    The result is non-zero if PER_CU was queued, otherwise the result is zero
8609    meaning either PER_CU is already queued or it is already loaded.
8610
8611    N.B. There is an invariant here that if a CU is queued then it is loaded.
8612    The caller is required to load PER_CU if we return non-zero.  */
8613
8614 static int
8615 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8616                        struct dwarf2_per_cu_data *per_cu,
8617                        enum language pretend_language)
8618 {
8619   /* We may arrive here during partial symbol reading, if we need full
8620      DIEs to process an unusual case (e.g. template arguments).  Do
8621      not queue PER_CU, just tell our caller to load its DIEs.  */
8622   if (dwarf2_per_objfile->reading_partial_symbols)
8623     {
8624       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8625         return 1;
8626       return 0;
8627     }
8628
8629   /* Mark the dependence relation so that we don't flush PER_CU
8630      too early.  */
8631   if (dependent_cu != NULL)
8632     dwarf2_add_dependence (dependent_cu, per_cu);
8633
8634   /* If it's already on the queue, we have nothing to do.  */
8635   if (per_cu->queued)
8636     return 0;
8637
8638   /* If the compilation unit is already loaded, just mark it as
8639      used.  */
8640   if (per_cu->cu != NULL)
8641     {
8642       per_cu->cu->last_used = 0;
8643       return 0;
8644     }
8645
8646   /* Add it to the queue.  */
8647   queue_comp_unit (per_cu, pretend_language);
8648
8649   return 1;
8650 }
8651
8652 /* Process the queue.  */
8653
8654 static void
8655 process_queue (void)
8656 {
8657   struct dwarf2_queue_item *item, *next_item;
8658
8659   if (dwarf_read_debug)
8660     {
8661       fprintf_unfiltered (gdb_stdlog,
8662                           "Expanding one or more symtabs of objfile %s ...\n",
8663                           objfile_name (dwarf2_per_objfile->objfile));
8664     }
8665
8666   /* The queue starts out with one item, but following a DIE reference
8667      may load a new CU, adding it to the end of the queue.  */
8668   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8669     {
8670       if ((dwarf2_per_objfile->using_index
8671            ? !item->per_cu->v.quick->compunit_symtab
8672            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8673           /* Skip dummy CUs.  */
8674           && item->per_cu->cu != NULL)
8675         {
8676           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8677           unsigned int debug_print_threshold;
8678           char buf[100];
8679
8680           if (per_cu->is_debug_types)
8681             {
8682               struct signatured_type *sig_type =
8683                 (struct signatured_type *) per_cu;
8684
8685               sprintf (buf, "TU %s at offset 0x%x",
8686                        hex_string (sig_type->signature),
8687                        to_underlying (per_cu->sect_off));
8688               /* There can be 100s of TUs.
8689                  Only print them in verbose mode.  */
8690               debug_print_threshold = 2;
8691             }
8692           else
8693             {
8694               sprintf (buf, "CU at offset 0x%x",
8695                        to_underlying (per_cu->sect_off));
8696               debug_print_threshold = 1;
8697             }
8698
8699           if (dwarf_read_debug >= debug_print_threshold)
8700             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8701
8702           if (per_cu->is_debug_types)
8703             process_full_type_unit (per_cu, item->pretend_language);
8704           else
8705             process_full_comp_unit (per_cu, item->pretend_language);
8706
8707           if (dwarf_read_debug >= debug_print_threshold)
8708             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8709         }
8710
8711       item->per_cu->queued = 0;
8712       next_item = item->next;
8713       xfree (item);
8714     }
8715
8716   dwarf2_queue_tail = NULL;
8717
8718   if (dwarf_read_debug)
8719     {
8720       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8721                           objfile_name (dwarf2_per_objfile->objfile));
8722     }
8723 }
8724
8725 /* Free all allocated queue entries.  This function only releases anything if
8726    an error was thrown; if the queue was processed then it would have been
8727    freed as we went along.  */
8728
8729 static void
8730 dwarf2_release_queue (void *dummy)
8731 {
8732   struct dwarf2_queue_item *item, *last;
8733
8734   item = dwarf2_queue;
8735   while (item)
8736     {
8737       /* Anything still marked queued is likely to be in an
8738          inconsistent state, so discard it.  */
8739       if (item->per_cu->queued)
8740         {
8741           if (item->per_cu->cu != NULL)
8742             free_one_cached_comp_unit (item->per_cu);
8743           item->per_cu->queued = 0;
8744         }
8745
8746       last = item;
8747       item = item->next;
8748       xfree (last);
8749     }
8750
8751   dwarf2_queue = dwarf2_queue_tail = NULL;
8752 }
8753
8754 /* Read in full symbols for PST, and anything it depends on.  */
8755
8756 static void
8757 psymtab_to_symtab_1 (struct partial_symtab *pst)
8758 {
8759   struct dwarf2_per_cu_data *per_cu;
8760   int i;
8761
8762   if (pst->readin)
8763     return;
8764
8765   for (i = 0; i < pst->number_of_dependencies; i++)
8766     if (!pst->dependencies[i]->readin
8767         && pst->dependencies[i]->user == NULL)
8768       {
8769         /* Inform about additional files that need to be read in.  */
8770         if (info_verbose)
8771           {
8772             /* FIXME: i18n: Need to make this a single string.  */
8773             fputs_filtered (" ", gdb_stdout);
8774             wrap_here ("");
8775             fputs_filtered ("and ", gdb_stdout);
8776             wrap_here ("");
8777             printf_filtered ("%s...", pst->dependencies[i]->filename);
8778             wrap_here ("");     /* Flush output.  */
8779             gdb_flush (gdb_stdout);
8780           }
8781         psymtab_to_symtab_1 (pst->dependencies[i]);
8782       }
8783
8784   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8785
8786   if (per_cu == NULL)
8787     {
8788       /* It's an include file, no symbols to read for it.
8789          Everything is in the parent symtab.  */
8790       pst->readin = 1;
8791       return;
8792     }
8793
8794   dw2_do_instantiate_symtab (per_cu);
8795 }
8796
8797 /* Trivial hash function for die_info: the hash value of a DIE
8798    is its offset in .debug_info for this objfile.  */
8799
8800 static hashval_t
8801 die_hash (const void *item)
8802 {
8803   const struct die_info *die = (const struct die_info *) item;
8804
8805   return to_underlying (die->sect_off);
8806 }
8807
8808 /* Trivial comparison function for die_info structures: two DIEs
8809    are equal if they have the same offset.  */
8810
8811 static int
8812 die_eq (const void *item_lhs, const void *item_rhs)
8813 {
8814   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8815   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8816
8817   return die_lhs->sect_off == die_rhs->sect_off;
8818 }
8819
8820 /* die_reader_func for load_full_comp_unit.
8821    This is identical to read_signatured_type_reader,
8822    but is kept separate for now.  */
8823
8824 static void
8825 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8826                             const gdb_byte *info_ptr,
8827                             struct die_info *comp_unit_die,
8828                             int has_children,
8829                             void *data)
8830 {
8831   struct dwarf2_cu *cu = reader->cu;
8832   enum language *language_ptr = (enum language *) data;
8833
8834   gdb_assert (cu->die_hash == NULL);
8835   cu->die_hash =
8836     htab_create_alloc_ex (cu->header.length / 12,
8837                           die_hash,
8838                           die_eq,
8839                           NULL,
8840                           &cu->comp_unit_obstack,
8841                           hashtab_obstack_allocate,
8842                           dummy_obstack_deallocate);
8843
8844   if (has_children)
8845     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8846                                                   &info_ptr, comp_unit_die);
8847   cu->dies = comp_unit_die;
8848   /* comp_unit_die is not stored in die_hash, no need.  */
8849
8850   /* We try not to read any attributes in this function, because not
8851      all CUs needed for references have been loaded yet, and symbol
8852      table processing isn't initialized.  But we have to set the CU language,
8853      or we won't be able to build types correctly.
8854      Similarly, if we do not read the producer, we can not apply
8855      producer-specific interpretation.  */
8856   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8857 }
8858
8859 /* Load the DIEs associated with PER_CU into memory.  */
8860
8861 static void
8862 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8863                      enum language pretend_language)
8864 {
8865   gdb_assert (! this_cu->is_debug_types);
8866
8867   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8868                            load_full_comp_unit_reader, &pretend_language);
8869 }
8870
8871 /* Add a DIE to the delayed physname list.  */
8872
8873 static void
8874 add_to_method_list (struct type *type, int fnfield_index, int index,
8875                     const char *name, struct die_info *die,
8876                     struct dwarf2_cu *cu)
8877 {
8878   struct delayed_method_info mi;
8879   mi.type = type;
8880   mi.fnfield_index = fnfield_index;
8881   mi.index = index;
8882   mi.name = name;
8883   mi.die = die;
8884   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8885 }
8886
8887 /* A cleanup for freeing the delayed method list.  */
8888
8889 static void
8890 free_delayed_list (void *ptr)
8891 {
8892   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8893   if (cu->method_list != NULL)
8894     {
8895       VEC_free (delayed_method_info, cu->method_list);
8896       cu->method_list = NULL;
8897     }
8898 }
8899
8900 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8901    "const" / "volatile".  If so, decrements LEN by the length of the
8902    modifier and return true.  Otherwise return false.  */
8903
8904 template<size_t N>
8905 static bool
8906 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8907 {
8908   size_t mod_len = sizeof (mod) - 1;
8909   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8910     {
8911       len -= mod_len;
8912       return true;
8913     }
8914   return false;
8915 }
8916
8917 /* Compute the physnames of any methods on the CU's method list.
8918
8919    The computation of method physnames is delayed in order to avoid the
8920    (bad) condition that one of the method's formal parameters is of an as yet
8921    incomplete type.  */
8922
8923 static void
8924 compute_delayed_physnames (struct dwarf2_cu *cu)
8925 {
8926   int i;
8927   struct delayed_method_info *mi;
8928
8929   /* Only C++ delays computing physnames.  */
8930   if (VEC_empty (delayed_method_info, cu->method_list))
8931     return;
8932   gdb_assert (cu->language == language_cplus);
8933
8934   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8935     {
8936       const char *physname;
8937       struct fn_fieldlist *fn_flp
8938         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8939       physname = dwarf2_physname (mi->name, mi->die, cu);
8940       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8941         = physname ? physname : "";
8942
8943       /* Since there's no tag to indicate whether a method is a
8944          const/volatile overload, extract that information out of the
8945          demangled name.  */
8946       if (physname != NULL)
8947         {
8948           size_t len = strlen (physname);
8949
8950           while (1)
8951             {
8952               if (physname[len] == ')') /* shortcut */
8953                 break;
8954               else if (check_modifier (physname, len, " const"))
8955                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8956               else if (check_modifier (physname, len, " volatile"))
8957                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8958               else
8959                 break;
8960             }
8961         }
8962     }
8963 }
8964
8965 /* Go objects should be embedded in a DW_TAG_module DIE,
8966    and it's not clear if/how imported objects will appear.
8967    To keep Go support simple until that's worked out,
8968    go back through what we've read and create something usable.
8969    We could do this while processing each DIE, and feels kinda cleaner,
8970    but that way is more invasive.
8971    This is to, for example, allow the user to type "p var" or "b main"
8972    without having to specify the package name, and allow lookups
8973    of module.object to work in contexts that use the expression
8974    parser.  */
8975
8976 static void
8977 fixup_go_packaging (struct dwarf2_cu *cu)
8978 {
8979   char *package_name = NULL;
8980   struct pending *list;
8981   int i;
8982
8983   for (list = global_symbols; list != NULL; list = list->next)
8984     {
8985       for (i = 0; i < list->nsyms; ++i)
8986         {
8987           struct symbol *sym = list->symbol[i];
8988
8989           if (SYMBOL_LANGUAGE (sym) == language_go
8990               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8991             {
8992               char *this_package_name = go_symbol_package_name (sym);
8993
8994               if (this_package_name == NULL)
8995                 continue;
8996               if (package_name == NULL)
8997                 package_name = this_package_name;
8998               else
8999                 {
9000                   if (strcmp (package_name, this_package_name) != 0)
9001                     complaint (&symfile_complaints,
9002                                _("Symtab %s has objects from two different Go packages: %s and %s"),
9003                                (symbol_symtab (sym) != NULL
9004                                 ? symtab_to_filename_for_display
9005                                     (symbol_symtab (sym))
9006                                 : objfile_name (cu->objfile)),
9007                                this_package_name, package_name);
9008                   xfree (this_package_name);
9009                 }
9010             }
9011         }
9012     }
9013
9014   if (package_name != NULL)
9015     {
9016       struct objfile *objfile = cu->objfile;
9017       const char *saved_package_name
9018         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9019                                         package_name,
9020                                         strlen (package_name));
9021       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9022                                      saved_package_name);
9023       struct symbol *sym;
9024
9025       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9026
9027       sym = allocate_symbol (objfile);
9028       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9029       SYMBOL_SET_NAMES (sym, saved_package_name,
9030                         strlen (saved_package_name), 0, objfile);
9031       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9032          e.g., "main" finds the "main" module and not C's main().  */
9033       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9034       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9035       SYMBOL_TYPE (sym) = type;
9036
9037       add_symbol_to_list (sym, &global_symbols);
9038
9039       xfree (package_name);
9040     }
9041 }
9042
9043 /* Return the symtab for PER_CU.  This works properly regardless of
9044    whether we're using the index or psymtabs.  */
9045
9046 static struct compunit_symtab *
9047 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9048 {
9049   return (dwarf2_per_objfile->using_index
9050           ? per_cu->v.quick->compunit_symtab
9051           : per_cu->v.psymtab->compunit_symtab);
9052 }
9053
9054 /* A helper function for computing the list of all symbol tables
9055    included by PER_CU.  */
9056
9057 static void
9058 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
9059                                 htab_t all_children, htab_t all_type_symtabs,
9060                                 struct dwarf2_per_cu_data *per_cu,
9061                                 struct compunit_symtab *immediate_parent)
9062 {
9063   void **slot;
9064   int ix;
9065   struct compunit_symtab *cust;
9066   struct dwarf2_per_cu_data *iter;
9067
9068   slot = htab_find_slot (all_children, per_cu, INSERT);
9069   if (*slot != NULL)
9070     {
9071       /* This inclusion and its children have been processed.  */
9072       return;
9073     }
9074
9075   *slot = per_cu;
9076   /* Only add a CU if it has a symbol table.  */
9077   cust = get_compunit_symtab (per_cu);
9078   if (cust != NULL)
9079     {
9080       /* If this is a type unit only add its symbol table if we haven't
9081          seen it yet (type unit per_cu's can share symtabs).  */
9082       if (per_cu->is_debug_types)
9083         {
9084           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9085           if (*slot == NULL)
9086             {
9087               *slot = cust;
9088               VEC_safe_push (compunit_symtab_ptr, *result, cust);
9089               if (cust->user == NULL)
9090                 cust->user = immediate_parent;
9091             }
9092         }
9093       else
9094         {
9095           VEC_safe_push (compunit_symtab_ptr, *result, cust);
9096           if (cust->user == NULL)
9097             cust->user = immediate_parent;
9098         }
9099     }
9100
9101   for (ix = 0;
9102        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
9103        ++ix)
9104     {
9105       recursively_compute_inclusions (result, all_children,
9106                                       all_type_symtabs, iter, cust);
9107     }
9108 }
9109
9110 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9111    PER_CU.  */
9112
9113 static void
9114 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9115 {
9116   gdb_assert (! per_cu->is_debug_types);
9117
9118   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
9119     {
9120       int ix, len;
9121       struct dwarf2_per_cu_data *per_cu_iter;
9122       struct compunit_symtab *compunit_symtab_iter;
9123       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
9124       htab_t all_children, all_type_symtabs;
9125       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9126
9127       /* If we don't have a symtab, we can just skip this case.  */
9128       if (cust == NULL)
9129         return;
9130
9131       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9132                                         NULL, xcalloc, xfree);
9133       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9134                                             NULL, xcalloc, xfree);
9135
9136       for (ix = 0;
9137            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
9138                         ix, per_cu_iter);
9139            ++ix)
9140         {
9141           recursively_compute_inclusions (&result_symtabs, all_children,
9142                                           all_type_symtabs, per_cu_iter,
9143                                           cust);
9144         }
9145
9146       /* Now we have a transitive closure of all the included symtabs.  */
9147       len = VEC_length (compunit_symtab_ptr, result_symtabs);
9148       cust->includes
9149         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
9150                      struct compunit_symtab *, len + 1);
9151       for (ix = 0;
9152            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
9153                         compunit_symtab_iter);
9154            ++ix)
9155         cust->includes[ix] = compunit_symtab_iter;
9156       cust->includes[len] = NULL;
9157
9158       VEC_free (compunit_symtab_ptr, result_symtabs);
9159       htab_delete (all_children);
9160       htab_delete (all_type_symtabs);
9161     }
9162 }
9163
9164 /* Compute the 'includes' field for the symtabs of all the CUs we just
9165    read.  */
9166
9167 static void
9168 process_cu_includes (void)
9169 {
9170   int ix;
9171   struct dwarf2_per_cu_data *iter;
9172
9173   for (ix = 0;
9174        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
9175                     ix, iter);
9176        ++ix)
9177     {
9178       if (! iter->is_debug_types)
9179         compute_compunit_symtab_includes (iter);
9180     }
9181
9182   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
9183 }
9184
9185 /* Generate full symbol information for PER_CU, whose DIEs have
9186    already been loaded into memory.  */
9187
9188 static void
9189 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9190                         enum language pretend_language)
9191 {
9192   struct dwarf2_cu *cu = per_cu->cu;
9193   struct objfile *objfile = per_cu->objfile;
9194   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9195   CORE_ADDR lowpc, highpc;
9196   struct compunit_symtab *cust;
9197   struct cleanup *delayed_list_cleanup;
9198   CORE_ADDR baseaddr;
9199   struct block *static_block;
9200   CORE_ADDR addr;
9201
9202   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9203
9204   buildsym_init ();
9205   scoped_free_pendings free_pending;
9206   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9207
9208   cu->list_in_scope = &file_symbols;
9209
9210   cu->language = pretend_language;
9211   cu->language_defn = language_def (cu->language);
9212
9213   /* Do line number decoding in read_file_scope () */
9214   process_die (cu->dies, cu);
9215
9216   /* For now fudge the Go package.  */
9217   if (cu->language == language_go)
9218     fixup_go_packaging (cu);
9219
9220   /* Now that we have processed all the DIEs in the CU, all the types 
9221      should be complete, and it should now be safe to compute all of the
9222      physnames.  */
9223   compute_delayed_physnames (cu);
9224   do_cleanups (delayed_list_cleanup);
9225
9226   /* Some compilers don't define a DW_AT_high_pc attribute for the
9227      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9228      it, by scanning the DIE's below the compilation unit.  */
9229   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9230
9231   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9232   static_block = end_symtab_get_static_block (addr, 0, 1);
9233
9234   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9235      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9236      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9237      addrmap to help ensure it has an accurate map of pc values belonging to
9238      this comp unit.  */
9239   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9240
9241   cust = end_symtab_from_static_block (static_block,
9242                                        SECT_OFF_TEXT (objfile), 0);
9243
9244   if (cust != NULL)
9245     {
9246       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9247
9248       /* Set symtab language to language from DW_AT_language.  If the
9249          compilation is from a C file generated by language preprocessors, do
9250          not set the language if it was already deduced by start_subfile.  */
9251       if (!(cu->language == language_c
9252             && COMPUNIT_FILETABS (cust)->language != language_unknown))
9253         COMPUNIT_FILETABS (cust)->language = cu->language;
9254
9255       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9256          produce DW_AT_location with location lists but it can be possibly
9257          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9258          there were bugs in prologue debug info, fixed later in GCC-4.5
9259          by "unwind info for epilogues" patch (which is not directly related).
9260
9261          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9262          needed, it would be wrong due to missing DW_AT_producer there.
9263
9264          Still one can confuse GDB by using non-standard GCC compilation
9265          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9266          */ 
9267       if (cu->has_loclist && gcc_4_minor >= 5)
9268         cust->locations_valid = 1;
9269
9270       if (gcc_4_minor >= 5)
9271         cust->epilogue_unwind_valid = 1;
9272
9273       cust->call_site_htab = cu->call_site_htab;
9274     }
9275
9276   if (dwarf2_per_objfile->using_index)
9277     per_cu->v.quick->compunit_symtab = cust;
9278   else
9279     {
9280       struct partial_symtab *pst = per_cu->v.psymtab;
9281       pst->compunit_symtab = cust;
9282       pst->readin = 1;
9283     }
9284
9285   /* Push it for inclusion processing later.  */
9286   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
9287 }
9288
9289 /* Generate full symbol information for type unit PER_CU, whose DIEs have
9290    already been loaded into memory.  */
9291
9292 static void
9293 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
9294                         enum language pretend_language)
9295 {
9296   struct dwarf2_cu *cu = per_cu->cu;
9297   struct objfile *objfile = per_cu->objfile;
9298   struct compunit_symtab *cust;
9299   struct cleanup *delayed_list_cleanup;
9300   struct signatured_type *sig_type;
9301
9302   gdb_assert (per_cu->is_debug_types);
9303   sig_type = (struct signatured_type *) per_cu;
9304
9305   buildsym_init ();
9306   scoped_free_pendings free_pending;
9307   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9308
9309   cu->list_in_scope = &file_symbols;
9310
9311   cu->language = pretend_language;
9312   cu->language_defn = language_def (cu->language);
9313
9314   /* The symbol tables are set up in read_type_unit_scope.  */
9315   process_die (cu->dies, cu);
9316
9317   /* For now fudge the Go package.  */
9318   if (cu->language == language_go)
9319     fixup_go_packaging (cu);
9320
9321   /* Now that we have processed all the DIEs in the CU, all the types 
9322      should be complete, and it should now be safe to compute all of the
9323      physnames.  */
9324   compute_delayed_physnames (cu);
9325   do_cleanups (delayed_list_cleanup);
9326
9327   /* TUs share symbol tables.
9328      If this is the first TU to use this symtab, complete the construction
9329      of it with end_expandable_symtab.  Otherwise, complete the addition of
9330      this TU's symbols to the existing symtab.  */
9331   if (sig_type->type_unit_group->compunit_symtab == NULL)
9332     {
9333       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9334       sig_type->type_unit_group->compunit_symtab = cust;
9335
9336       if (cust != NULL)
9337         {
9338           /* Set symtab language to language from DW_AT_language.  If the
9339              compilation is from a C file generated by language preprocessors,
9340              do not set the language if it was already deduced by
9341              start_subfile.  */
9342           if (!(cu->language == language_c
9343                 && COMPUNIT_FILETABS (cust)->language != language_c))
9344             COMPUNIT_FILETABS (cust)->language = cu->language;
9345         }
9346     }
9347   else
9348     {
9349       augment_type_symtab ();
9350       cust = sig_type->type_unit_group->compunit_symtab;
9351     }
9352
9353   if (dwarf2_per_objfile->using_index)
9354     per_cu->v.quick->compunit_symtab = cust;
9355   else
9356     {
9357       struct partial_symtab *pst = per_cu->v.psymtab;
9358       pst->compunit_symtab = cust;
9359       pst->readin = 1;
9360     }
9361 }
9362
9363 /* Process an imported unit DIE.  */
9364
9365 static void
9366 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9367 {
9368   struct attribute *attr;
9369
9370   /* For now we don't handle imported units in type units.  */
9371   if (cu->per_cu->is_debug_types)
9372     {
9373       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9374                " supported in type units [in module %s]"),
9375              objfile_name (cu->objfile));
9376     }
9377
9378   attr = dwarf2_attr (die, DW_AT_import, cu);
9379   if (attr != NULL)
9380     {
9381       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9382       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9383       dwarf2_per_cu_data *per_cu
9384         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
9385
9386       /* If necessary, add it to the queue and load its DIEs.  */
9387       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
9388         load_full_comp_unit (per_cu, cu->language);
9389
9390       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
9391                      per_cu);
9392     }
9393 }
9394
9395 /* RAII object that represents a process_die scope: i.e.,
9396    starts/finishes processing a DIE.  */
9397 class process_die_scope
9398 {
9399 public:
9400   process_die_scope (die_info *die, dwarf2_cu *cu)
9401     : m_die (die), m_cu (cu)
9402   {
9403     /* We should only be processing DIEs not already in process.  */
9404     gdb_assert (!m_die->in_process);
9405     m_die->in_process = true;
9406   }
9407
9408   ~process_die_scope ()
9409   {
9410     m_die->in_process = false;
9411
9412     /* If we're done processing the DIE for the CU that owns the line
9413        header, we don't need the line header anymore.  */
9414     if (m_cu->line_header_die_owner == m_die)
9415       {
9416         delete m_cu->line_header;
9417         m_cu->line_header = NULL;
9418         m_cu->line_header_die_owner = NULL;
9419       }
9420   }
9421
9422 private:
9423   die_info *m_die;
9424   dwarf2_cu *m_cu;
9425 };
9426
9427 /* Process a die and its children.  */
9428
9429 static void
9430 process_die (struct die_info *die, struct dwarf2_cu *cu)
9431 {
9432   process_die_scope scope (die, cu);
9433
9434   switch (die->tag)
9435     {
9436     case DW_TAG_padding:
9437       break;
9438     case DW_TAG_compile_unit:
9439     case DW_TAG_partial_unit:
9440       read_file_scope (die, cu);
9441       break;
9442     case DW_TAG_type_unit:
9443       read_type_unit_scope (die, cu);
9444       break;
9445     case DW_TAG_subprogram:
9446     case DW_TAG_inlined_subroutine:
9447       read_func_scope (die, cu);
9448       break;
9449     case DW_TAG_lexical_block:
9450     case DW_TAG_try_block:
9451     case DW_TAG_catch_block:
9452       read_lexical_block_scope (die, cu);
9453       break;
9454     case DW_TAG_call_site:
9455     case DW_TAG_GNU_call_site:
9456       read_call_site_scope (die, cu);
9457       break;
9458     case DW_TAG_class_type:
9459     case DW_TAG_interface_type:
9460     case DW_TAG_structure_type:
9461     case DW_TAG_union_type:
9462       process_structure_scope (die, cu);
9463       break;
9464     case DW_TAG_enumeration_type:
9465       process_enumeration_scope (die, cu);
9466       break;
9467
9468     /* These dies have a type, but processing them does not create
9469        a symbol or recurse to process the children.  Therefore we can
9470        read them on-demand through read_type_die.  */
9471     case DW_TAG_subroutine_type:
9472     case DW_TAG_set_type:
9473     case DW_TAG_array_type:
9474     case DW_TAG_pointer_type:
9475     case DW_TAG_ptr_to_member_type:
9476     case DW_TAG_reference_type:
9477     case DW_TAG_rvalue_reference_type:
9478     case DW_TAG_string_type:
9479       break;
9480
9481     case DW_TAG_base_type:
9482     case DW_TAG_subrange_type:
9483     case DW_TAG_typedef:
9484       /* Add a typedef symbol for the type definition, if it has a
9485          DW_AT_name.  */
9486       new_symbol (die, read_type_die (die, cu), cu);
9487       break;
9488     case DW_TAG_common_block:
9489       read_common_block (die, cu);
9490       break;
9491     case DW_TAG_common_inclusion:
9492       break;
9493     case DW_TAG_namespace:
9494       cu->processing_has_namespace_info = 1;
9495       read_namespace (die, cu);
9496       break;
9497     case DW_TAG_module:
9498       cu->processing_has_namespace_info = 1;
9499       read_module (die, cu);
9500       break;
9501     case DW_TAG_imported_declaration:
9502       cu->processing_has_namespace_info = 1;
9503       if (read_namespace_alias (die, cu))
9504         break;
9505       /* The declaration is not a global namespace alias: fall through.  */
9506     case DW_TAG_imported_module:
9507       cu->processing_has_namespace_info = 1;
9508       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9509                                  || cu->language != language_fortran))
9510         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
9511                    dwarf_tag_name (die->tag));
9512       read_import_statement (die, cu);
9513       break;
9514
9515     case DW_TAG_imported_unit:
9516       process_imported_unit_die (die, cu);
9517       break;
9518
9519     case DW_TAG_variable:
9520       read_variable (die, cu);
9521       break;
9522
9523     default:
9524       new_symbol (die, NULL, cu);
9525       break;
9526     }
9527 }
9528 \f
9529 /* DWARF name computation.  */
9530
9531 /* A helper function for dwarf2_compute_name which determines whether DIE
9532    needs to have the name of the scope prepended to the name listed in the
9533    die.  */
9534
9535 static int
9536 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9537 {
9538   struct attribute *attr;
9539
9540   switch (die->tag)
9541     {
9542     case DW_TAG_namespace:
9543     case DW_TAG_typedef:
9544     case DW_TAG_class_type:
9545     case DW_TAG_interface_type:
9546     case DW_TAG_structure_type:
9547     case DW_TAG_union_type:
9548     case DW_TAG_enumeration_type:
9549     case DW_TAG_enumerator:
9550     case DW_TAG_subprogram:
9551     case DW_TAG_inlined_subroutine:
9552     case DW_TAG_member:
9553     case DW_TAG_imported_declaration:
9554       return 1;
9555
9556     case DW_TAG_variable:
9557     case DW_TAG_constant:
9558       /* We only need to prefix "globally" visible variables.  These include
9559          any variable marked with DW_AT_external or any variable that
9560          lives in a namespace.  [Variables in anonymous namespaces
9561          require prefixing, but they are not DW_AT_external.]  */
9562
9563       if (dwarf2_attr (die, DW_AT_specification, cu))
9564         {
9565           struct dwarf2_cu *spec_cu = cu;
9566
9567           return die_needs_namespace (die_specification (die, &spec_cu),
9568                                       spec_cu);
9569         }
9570
9571       attr = dwarf2_attr (die, DW_AT_external, cu);
9572       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9573           && die->parent->tag != DW_TAG_module)
9574         return 0;
9575       /* A variable in a lexical block of some kind does not need a
9576          namespace, even though in C++ such variables may be external
9577          and have a mangled name.  */
9578       if (die->parent->tag ==  DW_TAG_lexical_block
9579           || die->parent->tag ==  DW_TAG_try_block
9580           || die->parent->tag ==  DW_TAG_catch_block
9581           || die->parent->tag == DW_TAG_subprogram)
9582         return 0;
9583       return 1;
9584
9585     default:
9586       return 0;
9587     }
9588 }
9589
9590 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9591    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9592    defined for the given DIE.  */
9593
9594 static struct attribute *
9595 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9596 {
9597   struct attribute *attr;
9598
9599   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9600   if (attr == NULL)
9601     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9602
9603   return attr;
9604 }
9605
9606 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9607    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9608    defined for the given DIE.  */
9609
9610 static const char *
9611 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9612 {
9613   const char *linkage_name;
9614
9615   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9616   if (linkage_name == NULL)
9617     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9618
9619   return linkage_name;
9620 }
9621
9622 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9623    compute the physname for the object, which include a method's:
9624    - formal parameters (C++),
9625    - receiver type (Go),
9626
9627    The term "physname" is a bit confusing.
9628    For C++, for example, it is the demangled name.
9629    For Go, for example, it's the mangled name.
9630
9631    For Ada, return the DIE's linkage name rather than the fully qualified
9632    name.  PHYSNAME is ignored..
9633
9634    The result is allocated on the objfile_obstack and canonicalized.  */
9635
9636 static const char *
9637 dwarf2_compute_name (const char *name,
9638                      struct die_info *die, struct dwarf2_cu *cu,
9639                      int physname)
9640 {
9641   struct objfile *objfile = cu->objfile;
9642
9643   if (name == NULL)
9644     name = dwarf2_name (die, cu);
9645
9646   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9647      but otherwise compute it by typename_concat inside GDB.
9648      FIXME: Actually this is not really true, or at least not always true.
9649      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9650      Fortran names because there is no mangling standard.  So new_symbol_full
9651      will set the demangled name to the result of dwarf2_full_name, and it is
9652      the demangled name that GDB uses if it exists.  */
9653   if (cu->language == language_ada
9654       || (cu->language == language_fortran && physname))
9655     {
9656       /* For Ada unit, we prefer the linkage name over the name, as
9657          the former contains the exported name, which the user expects
9658          to be able to reference.  Ideally, we want the user to be able
9659          to reference this entity using either natural or linkage name,
9660          but we haven't started looking at this enhancement yet.  */
9661       const char *linkage_name = dw2_linkage_name (die, cu);
9662
9663       if (linkage_name != NULL)
9664         return linkage_name;
9665     }
9666
9667   /* These are the only languages we know how to qualify names in.  */
9668   if (name != NULL
9669       && (cu->language == language_cplus
9670           || cu->language == language_fortran || cu->language == language_d
9671           || cu->language == language_rust))
9672     {
9673       if (die_needs_namespace (die, cu))
9674         {
9675           const char *prefix;
9676           const char *canonical_name = NULL;
9677
9678           string_file buf;
9679
9680           prefix = determine_prefix (die, cu);
9681           if (*prefix != '\0')
9682             {
9683               char *prefixed_name = typename_concat (NULL, prefix, name,
9684                                                      physname, cu);
9685
9686               buf.puts (prefixed_name);
9687               xfree (prefixed_name);
9688             }
9689           else
9690             buf.puts (name);
9691
9692           /* Template parameters may be specified in the DIE's DW_AT_name, or
9693              as children with DW_TAG_template_type_param or
9694              DW_TAG_value_type_param.  If the latter, add them to the name
9695              here.  If the name already has template parameters, then
9696              skip this step; some versions of GCC emit both, and
9697              it is more efficient to use the pre-computed name.
9698
9699              Something to keep in mind about this process: it is very
9700              unlikely, or in some cases downright impossible, to produce
9701              something that will match the mangled name of a function.
9702              If the definition of the function has the same debug info,
9703              we should be able to match up with it anyway.  But fallbacks
9704              using the minimal symbol, for instance to find a method
9705              implemented in a stripped copy of libstdc++, will not work.
9706              If we do not have debug info for the definition, we will have to
9707              match them up some other way.
9708
9709              When we do name matching there is a related problem with function
9710              templates; two instantiated function templates are allowed to
9711              differ only by their return types, which we do not add here.  */
9712
9713           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9714             {
9715               struct attribute *attr;
9716               struct die_info *child;
9717               int first = 1;
9718
9719               die->building_fullname = 1;
9720
9721               for (child = die->child; child != NULL; child = child->sibling)
9722                 {
9723                   struct type *type;
9724                   LONGEST value;
9725                   const gdb_byte *bytes;
9726                   struct dwarf2_locexpr_baton *baton;
9727                   struct value *v;
9728
9729                   if (child->tag != DW_TAG_template_type_param
9730                       && child->tag != DW_TAG_template_value_param)
9731                     continue;
9732
9733                   if (first)
9734                     {
9735                       buf.puts ("<");
9736                       first = 0;
9737                     }
9738                   else
9739                     buf.puts (", ");
9740
9741                   attr = dwarf2_attr (child, DW_AT_type, cu);
9742                   if (attr == NULL)
9743                     {
9744                       complaint (&symfile_complaints,
9745                                  _("template parameter missing DW_AT_type"));
9746                       buf.puts ("UNKNOWN_TYPE");
9747                       continue;
9748                     }
9749                   type = die_type (child, cu);
9750
9751                   if (child->tag == DW_TAG_template_type_param)
9752                     {
9753                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9754                       continue;
9755                     }
9756
9757                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9758                   if (attr == NULL)
9759                     {
9760                       complaint (&symfile_complaints,
9761                                  _("template parameter missing "
9762                                    "DW_AT_const_value"));
9763                       buf.puts ("UNKNOWN_VALUE");
9764                       continue;
9765                     }
9766
9767                   dwarf2_const_value_attr (attr, type, name,
9768                                            &cu->comp_unit_obstack, cu,
9769                                            &value, &bytes, &baton);
9770
9771                   if (TYPE_NOSIGN (type))
9772                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9773                        changed, this can use value_print instead.  */
9774                     c_printchar (value, type, &buf);
9775                   else
9776                     {
9777                       struct value_print_options opts;
9778
9779                       if (baton != NULL)
9780                         v = dwarf2_evaluate_loc_desc (type, NULL,
9781                                                       baton->data,
9782                                                       baton->size,
9783                                                       baton->per_cu);
9784                       else if (bytes != NULL)
9785                         {
9786                           v = allocate_value (type);
9787                           memcpy (value_contents_writeable (v), bytes,
9788                                   TYPE_LENGTH (type));
9789                         }
9790                       else
9791                         v = value_from_longest (type, value);
9792
9793                       /* Specify decimal so that we do not depend on
9794                          the radix.  */
9795                       get_formatted_print_options (&opts, 'd');
9796                       opts.raw = 1;
9797                       value_print (v, &buf, &opts);
9798                       release_value (v);
9799                       value_free (v);
9800                     }
9801                 }
9802
9803               die->building_fullname = 0;
9804
9805               if (!first)
9806                 {
9807                   /* Close the argument list, with a space if necessary
9808                      (nested templates).  */
9809                   if (!buf.empty () && buf.string ().back () == '>')
9810                     buf.puts (" >");
9811                   else
9812                     buf.puts (">");
9813                 }
9814             }
9815
9816           /* For C++ methods, append formal parameter type
9817              information, if PHYSNAME.  */
9818
9819           if (physname && die->tag == DW_TAG_subprogram
9820               && cu->language == language_cplus)
9821             {
9822               struct type *type = read_type_die (die, cu);
9823
9824               c_type_print_args (type, &buf, 1, cu->language,
9825                                  &type_print_raw_options);
9826
9827               if (cu->language == language_cplus)
9828                 {
9829                   /* Assume that an artificial first parameter is
9830                      "this", but do not crash if it is not.  RealView
9831                      marks unnamed (and thus unused) parameters as
9832                      artificial; there is no way to differentiate
9833                      the two cases.  */
9834                   if (TYPE_NFIELDS (type) > 0
9835                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9836                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9837                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9838                                                                         0))))
9839                     buf.puts (" const");
9840                 }
9841             }
9842
9843           const std::string &intermediate_name = buf.string ();
9844
9845           if (cu->language == language_cplus)
9846             canonical_name
9847               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9848                                           &objfile->per_bfd->storage_obstack);
9849
9850           /* If we only computed INTERMEDIATE_NAME, or if
9851              INTERMEDIATE_NAME is already canonical, then we need to
9852              copy it to the appropriate obstack.  */
9853           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9854             name = ((const char *)
9855                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9856                                    intermediate_name.c_str (),
9857                                    intermediate_name.length ()));
9858           else
9859             name = canonical_name;
9860         }
9861     }
9862
9863   return name;
9864 }
9865
9866 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9867    If scope qualifiers are appropriate they will be added.  The result
9868    will be allocated on the storage_obstack, or NULL if the DIE does
9869    not have a name.  NAME may either be from a previous call to
9870    dwarf2_name or NULL.
9871
9872    The output string will be canonicalized (if C++).  */
9873
9874 static const char *
9875 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9876 {
9877   return dwarf2_compute_name (name, die, cu, 0);
9878 }
9879
9880 /* Construct a physname for the given DIE in CU.  NAME may either be
9881    from a previous call to dwarf2_name or NULL.  The result will be
9882    allocated on the objfile_objstack or NULL if the DIE does not have a
9883    name.
9884
9885    The output string will be canonicalized (if C++).  */
9886
9887 static const char *
9888 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9889 {
9890   struct objfile *objfile = cu->objfile;
9891   const char *retval, *mangled = NULL, *canon = NULL;
9892   int need_copy = 1;
9893
9894   /* In this case dwarf2_compute_name is just a shortcut not building anything
9895      on its own.  */
9896   if (!die_needs_namespace (die, cu))
9897     return dwarf2_compute_name (name, die, cu, 1);
9898
9899   mangled = dw2_linkage_name (die, cu);
9900
9901   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9902      See https://github.com/rust-lang/rust/issues/32925.  */
9903   if (cu->language == language_rust && mangled != NULL
9904       && strchr (mangled, '{') != NULL)
9905     mangled = NULL;
9906
9907   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9908      has computed.  */
9909   gdb::unique_xmalloc_ptr<char> demangled;
9910   if (mangled != NULL)
9911     {
9912       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9913          type.  It is easier for GDB users to search for such functions as
9914          `name(params)' than `long name(params)'.  In such case the minimal
9915          symbol names do not match the full symbol names but for template
9916          functions there is never a need to look up their definition from their
9917          declaration so the only disadvantage remains the minimal symbol
9918          variant `long name(params)' does not have the proper inferior type.
9919          */
9920
9921       if (cu->language == language_go)
9922         {
9923           /* This is a lie, but we already lie to the caller new_symbol_full.
9924              new_symbol_full assumes we return the mangled name.
9925              This just undoes that lie until things are cleaned up.  */
9926         }
9927       else
9928         {
9929           demangled.reset (gdb_demangle (mangled,
9930                                          (DMGL_PARAMS | DMGL_ANSI
9931                                           | DMGL_RET_DROP)));
9932         }
9933       if (demangled)
9934         canon = demangled.get ();
9935       else
9936         {
9937           canon = mangled;
9938           need_copy = 0;
9939         }
9940     }
9941
9942   if (canon == NULL || check_physname)
9943     {
9944       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9945
9946       if (canon != NULL && strcmp (physname, canon) != 0)
9947         {
9948           /* It may not mean a bug in GDB.  The compiler could also
9949              compute DW_AT_linkage_name incorrectly.  But in such case
9950              GDB would need to be bug-to-bug compatible.  */
9951
9952           complaint (&symfile_complaints,
9953                      _("Computed physname <%s> does not match demangled <%s> "
9954                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9955                      physname, canon, mangled, to_underlying (die->sect_off),
9956                      objfile_name (objfile));
9957
9958           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9959              is available here - over computed PHYSNAME.  It is safer
9960              against both buggy GDB and buggy compilers.  */
9961
9962           retval = canon;
9963         }
9964       else
9965         {
9966           retval = physname;
9967           need_copy = 0;
9968         }
9969     }
9970   else
9971     retval = canon;
9972
9973   if (need_copy)
9974     retval = ((const char *)
9975               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9976                              retval, strlen (retval)));
9977
9978   return retval;
9979 }
9980
9981 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9982    a new symbol for it.
9983
9984    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9985
9986 static int
9987 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9988 {
9989   struct attribute *attr;
9990
9991   /* If the die does not have a name, this is not a namespace
9992      alias.  */
9993   attr = dwarf2_attr (die, DW_AT_name, cu);
9994   if (attr != NULL)
9995     {
9996       int num;
9997       struct die_info *d = die;
9998       struct dwarf2_cu *imported_cu = cu;
9999
10000       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10001          keep inspecting DIEs until we hit the underlying import.  */
10002 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10003       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10004         {
10005           attr = dwarf2_attr (d, DW_AT_import, cu);
10006           if (attr == NULL)
10007             break;
10008
10009           d = follow_die_ref (d, attr, &imported_cu);
10010           if (d->tag != DW_TAG_imported_declaration)
10011             break;
10012         }
10013
10014       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10015         {
10016           complaint (&symfile_complaints,
10017                      _("DIE at 0x%x has too many recursively imported "
10018                        "declarations"), to_underlying (d->sect_off));
10019           return 0;
10020         }
10021
10022       if (attr != NULL)
10023         {
10024           struct type *type;
10025           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10026
10027           type = get_die_type_at_offset (sect_off, cu->per_cu);
10028           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10029             {
10030               /* This declaration is a global namespace alias.  Add
10031                  a symbol for it whose type is the aliased namespace.  */
10032               new_symbol (die, type, cu);
10033               return 1;
10034             }
10035         }
10036     }
10037
10038   return 0;
10039 }
10040
10041 /* Return the using directives repository (global or local?) to use in the
10042    current context for LANGUAGE.
10043
10044    For Ada, imported declarations can materialize renamings, which *may* be
10045    global.  However it is impossible (for now?) in DWARF to distinguish
10046    "external" imported declarations and "static" ones.  As all imported
10047    declarations seem to be static in all other languages, make them all CU-wide
10048    global only in Ada.  */
10049
10050 static struct using_direct **
10051 using_directives (enum language language)
10052 {
10053   if (language == language_ada && context_stack_depth == 0)
10054     return &global_using_directives;
10055   else
10056     return &local_using_directives;
10057 }
10058
10059 /* Read the import statement specified by the given die and record it.  */
10060
10061 static void
10062 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10063 {
10064   struct objfile *objfile = cu->objfile;
10065   struct attribute *import_attr;
10066   struct die_info *imported_die, *child_die;
10067   struct dwarf2_cu *imported_cu;
10068   const char *imported_name;
10069   const char *imported_name_prefix;
10070   const char *canonical_name;
10071   const char *import_alias;
10072   const char *imported_declaration = NULL;
10073   const char *import_prefix;
10074   std::vector<const char *> excludes;
10075
10076   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10077   if (import_attr == NULL)
10078     {
10079       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10080                  dwarf_tag_name (die->tag));
10081       return;
10082     }
10083
10084   imported_cu = cu;
10085   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10086   imported_name = dwarf2_name (imported_die, imported_cu);
10087   if (imported_name == NULL)
10088     {
10089       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10090
10091         The import in the following code:
10092         namespace A
10093           {
10094             typedef int B;
10095           }
10096
10097         int main ()
10098           {
10099             using A::B;
10100             B b;
10101             return b;
10102           }
10103
10104         ...
10105          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10106             <52>   DW_AT_decl_file   : 1
10107             <53>   DW_AT_decl_line   : 6
10108             <54>   DW_AT_import      : <0x75>
10109          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10110             <59>   DW_AT_name        : B
10111             <5b>   DW_AT_decl_file   : 1
10112             <5c>   DW_AT_decl_line   : 2
10113             <5d>   DW_AT_type        : <0x6e>
10114         ...
10115          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10116             <76>   DW_AT_byte_size   : 4
10117             <77>   DW_AT_encoding    : 5        (signed)
10118
10119         imports the wrong die ( 0x75 instead of 0x58 ).
10120         This case will be ignored until the gcc bug is fixed.  */
10121       return;
10122     }
10123
10124   /* Figure out the local name after import.  */
10125   import_alias = dwarf2_name (die, cu);
10126
10127   /* Figure out where the statement is being imported to.  */
10128   import_prefix = determine_prefix (die, cu);
10129
10130   /* Figure out what the scope of the imported die is and prepend it
10131      to the name of the imported die.  */
10132   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10133
10134   if (imported_die->tag != DW_TAG_namespace
10135       && imported_die->tag != DW_TAG_module)
10136     {
10137       imported_declaration = imported_name;
10138       canonical_name = imported_name_prefix;
10139     }
10140   else if (strlen (imported_name_prefix) > 0)
10141     canonical_name = obconcat (&objfile->objfile_obstack,
10142                                imported_name_prefix,
10143                                (cu->language == language_d ? "." : "::"),
10144                                imported_name, (char *) NULL);
10145   else
10146     canonical_name = imported_name;
10147
10148   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10149     for (child_die = die->child; child_die && child_die->tag;
10150          child_die = sibling_die (child_die))
10151       {
10152         /* DWARF-4: A Fortran use statement with a “rename list” may be
10153            represented by an imported module entry with an import attribute
10154            referring to the module and owned entries corresponding to those
10155            entities that are renamed as part of being imported.  */
10156
10157         if (child_die->tag != DW_TAG_imported_declaration)
10158           {
10159             complaint (&symfile_complaints,
10160                        _("child DW_TAG_imported_declaration expected "
10161                          "- DIE at 0x%x [in module %s]"),
10162                        to_underlying (child_die->sect_off), objfile_name (objfile));
10163             continue;
10164           }
10165
10166         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10167         if (import_attr == NULL)
10168           {
10169             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10170                        dwarf_tag_name (child_die->tag));
10171             continue;
10172           }
10173
10174         imported_cu = cu;
10175         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10176                                               &imported_cu);
10177         imported_name = dwarf2_name (imported_die, imported_cu);
10178         if (imported_name == NULL)
10179           {
10180             complaint (&symfile_complaints,
10181                        _("child DW_TAG_imported_declaration has unknown "
10182                          "imported name - DIE at 0x%x [in module %s]"),
10183                        to_underlying (child_die->sect_off), objfile_name (objfile));
10184             continue;
10185           }
10186
10187         excludes.push_back (imported_name);
10188
10189         process_die (child_die, cu);
10190       }
10191
10192   add_using_directive (using_directives (cu->language),
10193                        import_prefix,
10194                        canonical_name,
10195                        import_alias,
10196                        imported_declaration,
10197                        excludes,
10198                        0,
10199                        &objfile->objfile_obstack);
10200 }
10201
10202 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10203    types, but gives them a size of zero.  Starting with version 14,
10204    ICC is compatible with GCC.  */
10205
10206 static int
10207 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10208 {
10209   if (!cu->checked_producer)
10210     check_producer (cu);
10211
10212   return cu->producer_is_icc_lt_14;
10213 }
10214
10215 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10216    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10217    this, it was first present in GCC release 4.3.0.  */
10218
10219 static int
10220 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10221 {
10222   if (!cu->checked_producer)
10223     check_producer (cu);
10224
10225   return cu->producer_is_gcc_lt_4_3;
10226 }
10227
10228 static file_and_directory
10229 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10230 {
10231   file_and_directory res;
10232
10233   /* Find the filename.  Do not use dwarf2_name here, since the filename
10234      is not a source language identifier.  */
10235   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10236   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10237
10238   if (res.comp_dir == NULL
10239       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10240       && IS_ABSOLUTE_PATH (res.name))
10241     {
10242       res.comp_dir_storage = ldirname (res.name);
10243       if (!res.comp_dir_storage.empty ())
10244         res.comp_dir = res.comp_dir_storage.c_str ();
10245     }
10246   if (res.comp_dir != NULL)
10247     {
10248       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10249          directory, get rid of it.  */
10250       const char *cp = strchr (res.comp_dir, ':');
10251
10252       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10253         res.comp_dir = cp + 1;
10254     }
10255
10256   if (res.name == NULL)
10257     res.name = "<unknown>";
10258
10259   return res;
10260 }
10261
10262 /* Handle DW_AT_stmt_list for a compilation unit.
10263    DIE is the DW_TAG_compile_unit die for CU.
10264    COMP_DIR is the compilation directory.  LOWPC is passed to
10265    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10266
10267 static void
10268 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10269                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
10270 {
10271   struct objfile *objfile = dwarf2_per_objfile->objfile;
10272   struct attribute *attr;
10273   struct line_header line_header_local;
10274   hashval_t line_header_local_hash;
10275   void **slot;
10276   int decode_mapping;
10277
10278   gdb_assert (! cu->per_cu->is_debug_types);
10279
10280   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10281   if (attr == NULL)
10282     return;
10283
10284   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10285
10286   /* The line header hash table is only created if needed (it exists to
10287      prevent redundant reading of the line table for partial_units).
10288      If we're given a partial_unit, we'll need it.  If we're given a
10289      compile_unit, then use the line header hash table if it's already
10290      created, but don't create one just yet.  */
10291
10292   if (dwarf2_per_objfile->line_header_hash == NULL
10293       && die->tag == DW_TAG_partial_unit)
10294     {
10295       dwarf2_per_objfile->line_header_hash
10296         = htab_create_alloc_ex (127, line_header_hash_voidp,
10297                                 line_header_eq_voidp,
10298                                 free_line_header_voidp,
10299                                 &objfile->objfile_obstack,
10300                                 hashtab_obstack_allocate,
10301                                 dummy_obstack_deallocate);
10302     }
10303
10304   line_header_local.sect_off = line_offset;
10305   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10306   line_header_local_hash = line_header_hash (&line_header_local);
10307   if (dwarf2_per_objfile->line_header_hash != NULL)
10308     {
10309       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10310                                        &line_header_local,
10311                                        line_header_local_hash, NO_INSERT);
10312
10313       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10314          is not present in *SLOT (since if there is something in *SLOT then
10315          it will be for a partial_unit).  */
10316       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10317         {
10318           gdb_assert (*slot != NULL);
10319           cu->line_header = (struct line_header *) *slot;
10320           return;
10321         }
10322     }
10323
10324   /* dwarf_decode_line_header does not yet provide sufficient information.
10325      We always have to call also dwarf_decode_lines for it.  */
10326   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10327   if (lh == NULL)
10328     return;
10329
10330   cu->line_header = lh.release ();
10331   cu->line_header_die_owner = die;
10332
10333   if (dwarf2_per_objfile->line_header_hash == NULL)
10334     slot = NULL;
10335   else
10336     {
10337       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10338                                        &line_header_local,
10339                                        line_header_local_hash, INSERT);
10340       gdb_assert (slot != NULL);
10341     }
10342   if (slot != NULL && *slot == NULL)
10343     {
10344       /* This newly decoded line number information unit will be owned
10345          by line_header_hash hash table.  */
10346       *slot = cu->line_header;
10347       cu->line_header_die_owner = NULL;
10348     }
10349   else
10350     {
10351       /* We cannot free any current entry in (*slot) as that struct line_header
10352          may be already used by multiple CUs.  Create only temporary decoded
10353          line_header for this CU - it may happen at most once for each line
10354          number information unit.  And if we're not using line_header_hash
10355          then this is what we want as well.  */
10356       gdb_assert (die->tag != DW_TAG_partial_unit);
10357     }
10358   decode_mapping = (die->tag != DW_TAG_partial_unit);
10359   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10360                       decode_mapping);
10361
10362 }
10363
10364 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10365
10366 static void
10367 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10368 {
10369   struct objfile *objfile = dwarf2_per_objfile->objfile;
10370   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10371   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10372   CORE_ADDR highpc = ((CORE_ADDR) 0);
10373   struct attribute *attr;
10374   struct die_info *child_die;
10375   CORE_ADDR baseaddr;
10376
10377   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10378
10379   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10380
10381   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10382      from finish_block.  */
10383   if (lowpc == ((CORE_ADDR) -1))
10384     lowpc = highpc;
10385   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10386
10387   file_and_directory fnd = find_file_and_directory (die, cu);
10388
10389   prepare_one_comp_unit (cu, die, cu->language);
10390
10391   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
10392      standardised yet.  As a workaround for the language detection we fall
10393      back to the DW_AT_producer string.  */
10394   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
10395     cu->language = language_opencl;
10396
10397   /* Similar hack for Go.  */
10398   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
10399     set_cu_language (DW_LANG_Go, cu);
10400
10401   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
10402
10403   /* Decode line number information if present.  We do this before
10404      processing child DIEs, so that the line header table is available
10405      for DW_AT_decl_file.  */
10406   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10407
10408   /* Process all dies in compilation unit.  */
10409   if (die->child != NULL)
10410     {
10411       child_die = die->child;
10412       while (child_die && child_die->tag)
10413         {
10414           process_die (child_die, cu);
10415           child_die = sibling_die (child_die);
10416         }
10417     }
10418
10419   /* Decode macro information, if present.  Dwarf 2 macro information
10420      refers to information in the line number info statement program
10421      header, so we can only read it if we've read the header
10422      successfully.  */
10423   attr = dwarf2_attr (die, DW_AT_macros, cu);
10424   if (attr == NULL)
10425     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10426   if (attr && cu->line_header)
10427     {
10428       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10429         complaint (&symfile_complaints,
10430                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10431
10432       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
10433     }
10434   else
10435     {
10436       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10437       if (attr && cu->line_header)
10438         {
10439           unsigned int macro_offset = DW_UNSND (attr);
10440
10441           dwarf_decode_macros (cu, macro_offset, 0);
10442         }
10443     }
10444 }
10445
10446 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
10447    Create the set of symtabs used by this TU, or if this TU is sharing
10448    symtabs with another TU and the symtabs have already been created
10449    then restore those symtabs in the line header.
10450    We don't need the pc/line-number mapping for type units.  */
10451
10452 static void
10453 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
10454 {
10455   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
10456   struct type_unit_group *tu_group;
10457   int first_time;
10458   struct attribute *attr;
10459   unsigned int i;
10460   struct signatured_type *sig_type;
10461
10462   gdb_assert (per_cu->is_debug_types);
10463   sig_type = (struct signatured_type *) per_cu;
10464
10465   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10466
10467   /* If we're using .gdb_index (includes -readnow) then
10468      per_cu->type_unit_group may not have been set up yet.  */
10469   if (sig_type->type_unit_group == NULL)
10470     sig_type->type_unit_group = get_type_unit_group (cu, attr);
10471   tu_group = sig_type->type_unit_group;
10472
10473   /* If we've already processed this stmt_list there's no real need to
10474      do it again, we could fake it and just recreate the part we need
10475      (file name,index -> symtab mapping).  If data shows this optimization
10476      is useful we can do it then.  */
10477   first_time = tu_group->compunit_symtab == NULL;
10478
10479   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10480      debug info.  */
10481   line_header_up lh;
10482   if (attr != NULL)
10483     {
10484       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10485       lh = dwarf_decode_line_header (line_offset, cu);
10486     }
10487   if (lh == NULL)
10488     {
10489       if (first_time)
10490         dwarf2_start_symtab (cu, "", NULL, 0);
10491       else
10492         {
10493           gdb_assert (tu_group->symtabs == NULL);
10494           restart_symtab (tu_group->compunit_symtab, "", 0);
10495         }
10496       return;
10497     }
10498
10499   cu->line_header = lh.release ();
10500   cu->line_header_die_owner = die;
10501
10502   if (first_time)
10503     {
10504       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
10505
10506       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10507          still initializing it, and our caller (a few levels up)
10508          process_full_type_unit still needs to know if this is the first
10509          time.  */
10510
10511       tu_group->num_symtabs = cu->line_header->file_names.size ();
10512       tu_group->symtabs = XNEWVEC (struct symtab *,
10513                                    cu->line_header->file_names.size ());
10514
10515       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10516         {
10517           file_entry &fe = cu->line_header->file_names[i];
10518
10519           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
10520
10521           if (current_subfile->symtab == NULL)
10522             {
10523               /* NOTE: start_subfile will recognize when it's been
10524                  passed a file it has already seen.  So we can't
10525                  assume there's a simple mapping from
10526                  cu->line_header->file_names to subfiles, plus
10527                  cu->line_header->file_names may contain dups.  */
10528               current_subfile->symtab
10529                 = allocate_symtab (cust, current_subfile->name);
10530             }
10531
10532           fe.symtab = current_subfile->symtab;
10533           tu_group->symtabs[i] = fe.symtab;
10534         }
10535     }
10536   else
10537     {
10538       restart_symtab (tu_group->compunit_symtab, "", 0);
10539
10540       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10541         {
10542           file_entry &fe = cu->line_header->file_names[i];
10543
10544           fe.symtab = tu_group->symtabs[i];
10545         }
10546     }
10547
10548   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10549      so they don't have a "real" (so to speak) symtab anyway.
10550      There is later code that will assign the main symtab to all symbols
10551      that don't have one.  We need to handle the case of a symbol with a
10552      missing symtab (DW_AT_decl_file) anyway.  */
10553 }
10554
10555 /* Process DW_TAG_type_unit.
10556    For TUs we want to skip the first top level sibling if it's not the
10557    actual type being defined by this TU.  In this case the first top
10558    level sibling is there to provide context only.  */
10559
10560 static void
10561 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10562 {
10563   struct die_info *child_die;
10564
10565   prepare_one_comp_unit (cu, die, language_minimal);
10566
10567   /* Initialize (or reinitialize) the machinery for building symtabs.
10568      We do this before processing child DIEs, so that the line header table
10569      is available for DW_AT_decl_file.  */
10570   setup_type_unit_groups (die, cu);
10571
10572   if (die->child != NULL)
10573     {
10574       child_die = die->child;
10575       while (child_die && child_die->tag)
10576         {
10577           process_die (child_die, cu);
10578           child_die = sibling_die (child_die);
10579         }
10580     }
10581 }
10582 \f
10583 /* DWO/DWP files.
10584
10585    http://gcc.gnu.org/wiki/DebugFission
10586    http://gcc.gnu.org/wiki/DebugFissionDWP
10587
10588    To simplify handling of both DWO files ("object" files with the DWARF info)
10589    and DWP files (a file with the DWOs packaged up into one file), we treat
10590    DWP files as having a collection of virtual DWO files.  */
10591
10592 static hashval_t
10593 hash_dwo_file (const void *item)
10594 {
10595   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10596   hashval_t hash;
10597
10598   hash = htab_hash_string (dwo_file->dwo_name);
10599   if (dwo_file->comp_dir != NULL)
10600     hash += htab_hash_string (dwo_file->comp_dir);
10601   return hash;
10602 }
10603
10604 static int
10605 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10606 {
10607   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10608   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10609
10610   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10611     return 0;
10612   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10613     return lhs->comp_dir == rhs->comp_dir;
10614   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10615 }
10616
10617 /* Allocate a hash table for DWO files.  */
10618
10619 static htab_t
10620 allocate_dwo_file_hash_table (void)
10621 {
10622   struct objfile *objfile = dwarf2_per_objfile->objfile;
10623
10624   return htab_create_alloc_ex (41,
10625                                hash_dwo_file,
10626                                eq_dwo_file,
10627                                NULL,
10628                                &objfile->objfile_obstack,
10629                                hashtab_obstack_allocate,
10630                                dummy_obstack_deallocate);
10631 }
10632
10633 /* Lookup DWO file DWO_NAME.  */
10634
10635 static void **
10636 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10637 {
10638   struct dwo_file find_entry;
10639   void **slot;
10640
10641   if (dwarf2_per_objfile->dwo_files == NULL)
10642     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10643
10644   memset (&find_entry, 0, sizeof (find_entry));
10645   find_entry.dwo_name = dwo_name;
10646   find_entry.comp_dir = comp_dir;
10647   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10648
10649   return slot;
10650 }
10651
10652 static hashval_t
10653 hash_dwo_unit (const void *item)
10654 {
10655   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10656
10657   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10658   return dwo_unit->signature;
10659 }
10660
10661 static int
10662 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10663 {
10664   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10665   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10666
10667   /* The signature is assumed to be unique within the DWO file.
10668      So while object file CU dwo_id's always have the value zero,
10669      that's OK, assuming each object file DWO file has only one CU,
10670      and that's the rule for now.  */
10671   return lhs->signature == rhs->signature;
10672 }
10673
10674 /* Allocate a hash table for DWO CUs,TUs.
10675    There is one of these tables for each of CUs,TUs for each DWO file.  */
10676
10677 static htab_t
10678 allocate_dwo_unit_table (struct objfile *objfile)
10679 {
10680   /* Start out with a pretty small number.
10681      Generally DWO files contain only one CU and maybe some TUs.  */
10682   return htab_create_alloc_ex (3,
10683                                hash_dwo_unit,
10684                                eq_dwo_unit,
10685                                NULL,
10686                                &objfile->objfile_obstack,
10687                                hashtab_obstack_allocate,
10688                                dummy_obstack_deallocate);
10689 }
10690
10691 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10692
10693 struct create_dwo_cu_data
10694 {
10695   struct dwo_file *dwo_file;
10696   struct dwo_unit dwo_unit;
10697 };
10698
10699 /* die_reader_func for create_dwo_cu.  */
10700
10701 static void
10702 create_dwo_cu_reader (const struct die_reader_specs *reader,
10703                       const gdb_byte *info_ptr,
10704                       struct die_info *comp_unit_die,
10705                       int has_children,
10706                       void *datap)
10707 {
10708   struct dwarf2_cu *cu = reader->cu;
10709   sect_offset sect_off = cu->per_cu->sect_off;
10710   struct dwarf2_section_info *section = cu->per_cu->section;
10711   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10712   struct dwo_file *dwo_file = data->dwo_file;
10713   struct dwo_unit *dwo_unit = &data->dwo_unit;
10714   struct attribute *attr;
10715
10716   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10717   if (attr == NULL)
10718     {
10719       complaint (&symfile_complaints,
10720                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10721                    " its dwo_id [in module %s]"),
10722                  to_underlying (sect_off), dwo_file->dwo_name);
10723       return;
10724     }
10725
10726   dwo_unit->dwo_file = dwo_file;
10727   dwo_unit->signature = DW_UNSND (attr);
10728   dwo_unit->section = section;
10729   dwo_unit->sect_off = sect_off;
10730   dwo_unit->length = cu->per_cu->length;
10731
10732   if (dwarf_read_debug)
10733     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10734                         to_underlying (sect_off),
10735                         hex_string (dwo_unit->signature));
10736 }
10737
10738 /* Create the dwo_units for the CUs in a DWO_FILE.
10739    Note: This function processes DWO files only, not DWP files.  */
10740
10741 static void
10742 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10743                        htab_t &cus_htab)
10744 {
10745   struct objfile *objfile = dwarf2_per_objfile->objfile;
10746   const gdb_byte *info_ptr, *end_ptr;
10747
10748   dwarf2_read_section (objfile, &section);
10749   info_ptr = section.buffer;
10750
10751   if (info_ptr == NULL)
10752     return;
10753
10754   if (dwarf_read_debug)
10755     {
10756       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10757                           get_section_name (&section),
10758                           get_section_file_name (&section));
10759     }
10760
10761   end_ptr = info_ptr + section.size;
10762   while (info_ptr < end_ptr)
10763     {
10764       struct dwarf2_per_cu_data per_cu;
10765       struct create_dwo_cu_data create_dwo_cu_data;
10766       struct dwo_unit *dwo_unit;
10767       void **slot;
10768       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10769
10770       memset (&create_dwo_cu_data.dwo_unit, 0,
10771               sizeof (create_dwo_cu_data.dwo_unit));
10772       memset (&per_cu, 0, sizeof (per_cu));
10773       per_cu.objfile = objfile;
10774       per_cu.is_debug_types = 0;
10775       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10776       per_cu.section = &section;
10777       create_dwo_cu_data.dwo_file = &dwo_file;
10778
10779       init_cutu_and_read_dies_no_follow (
10780           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10781       info_ptr += per_cu.length;
10782
10783       // If the unit could not be parsed, skip it.
10784       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10785         continue;
10786
10787       if (cus_htab == NULL)
10788         cus_htab = allocate_dwo_unit_table (objfile);
10789
10790       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10791       *dwo_unit = create_dwo_cu_data.dwo_unit;
10792       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10793       gdb_assert (slot != NULL);
10794       if (*slot != NULL)
10795         {
10796           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10797           sect_offset dup_sect_off = dup_cu->sect_off;
10798
10799           complaint (&symfile_complaints,
10800                      _("debug cu entry at offset 0x%x is duplicate to"
10801                        " the entry at offset 0x%x, signature %s"),
10802                      to_underlying (sect_off), to_underlying (dup_sect_off),
10803                      hex_string (dwo_unit->signature));
10804         }
10805       *slot = (void *)dwo_unit;
10806     }
10807 }
10808
10809 /* DWP file .debug_{cu,tu}_index section format:
10810    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10811
10812    DWP Version 1:
10813
10814    Both index sections have the same format, and serve to map a 64-bit
10815    signature to a set of section numbers.  Each section begins with a header,
10816    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10817    indexes, and a pool of 32-bit section numbers.  The index sections will be
10818    aligned at 8-byte boundaries in the file.
10819
10820    The index section header consists of:
10821
10822     V, 32 bit version number
10823     -, 32 bits unused
10824     N, 32 bit number of compilation units or type units in the index
10825     M, 32 bit number of slots in the hash table
10826
10827    Numbers are recorded using the byte order of the application binary.
10828
10829    The hash table begins at offset 16 in the section, and consists of an array
10830    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10831    order of the application binary).  Unused slots in the hash table are 0.
10832    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10833
10834    The parallel table begins immediately after the hash table
10835    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10836    array of 32-bit indexes (using the byte order of the application binary),
10837    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10838    table contains a 32-bit index into the pool of section numbers.  For unused
10839    hash table slots, the corresponding entry in the parallel table will be 0.
10840
10841    The pool of section numbers begins immediately following the hash table
10842    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10843    section numbers consists of an array of 32-bit words (using the byte order
10844    of the application binary).  Each item in the array is indexed starting
10845    from 0.  The hash table entry provides the index of the first section
10846    number in the set.  Additional section numbers in the set follow, and the
10847    set is terminated by a 0 entry (section number 0 is not used in ELF).
10848
10849    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10850    section must be the first entry in the set, and the .debug_abbrev.dwo must
10851    be the second entry. Other members of the set may follow in any order.
10852
10853    ---
10854
10855    DWP Version 2:
10856
10857    DWP Version 2 combines all the .debug_info, etc. sections into one,
10858    and the entries in the index tables are now offsets into these sections.
10859    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10860    section.
10861
10862    Index Section Contents:
10863     Header
10864     Hash Table of Signatures   dwp_hash_table.hash_table
10865     Parallel Table of Indices  dwp_hash_table.unit_table
10866     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10867     Table of Section Sizes     dwp_hash_table.v2.sizes
10868
10869    The index section header consists of:
10870
10871     V, 32 bit version number
10872     L, 32 bit number of columns in the table of section offsets
10873     N, 32 bit number of compilation units or type units in the index
10874     M, 32 bit number of slots in the hash table
10875
10876    Numbers are recorded using the byte order of the application binary.
10877
10878    The hash table has the same format as version 1.
10879    The parallel table of indices has the same format as version 1,
10880    except that the entries are origin-1 indices into the table of sections
10881    offsets and the table of section sizes.
10882
10883    The table of offsets begins immediately following the parallel table
10884    (at offset 16 + 12 * M from the beginning of the section).  The table is
10885    a two-dimensional array of 32-bit words (using the byte order of the
10886    application binary), with L columns and N+1 rows, in row-major order.
10887    Each row in the array is indexed starting from 0.  The first row provides
10888    a key to the remaining rows: each column in this row provides an identifier
10889    for a debug section, and the offsets in the same column of subsequent rows
10890    refer to that section.  The section identifiers are:
10891
10892     DW_SECT_INFO         1  .debug_info.dwo
10893     DW_SECT_TYPES        2  .debug_types.dwo
10894     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10895     DW_SECT_LINE         4  .debug_line.dwo
10896     DW_SECT_LOC          5  .debug_loc.dwo
10897     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10898     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10899     DW_SECT_MACRO        8  .debug_macro.dwo
10900
10901    The offsets provided by the CU and TU index sections are the base offsets
10902    for the contributions made by each CU or TU to the corresponding section
10903    in the package file.  Each CU and TU header contains an abbrev_offset
10904    field, used to find the abbreviations table for that CU or TU within the
10905    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10906    be interpreted as relative to the base offset given in the index section.
10907    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10908    should be interpreted as relative to the base offset for .debug_line.dwo,
10909    and offsets into other debug sections obtained from DWARF attributes should
10910    also be interpreted as relative to the corresponding base offset.
10911
10912    The table of sizes begins immediately following the table of offsets.
10913    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10914    with L columns and N rows, in row-major order.  Each row in the array is
10915    indexed starting from 1 (row 0 is shared by the two tables).
10916
10917    ---
10918
10919    Hash table lookup is handled the same in version 1 and 2:
10920
10921    We assume that N and M will not exceed 2^32 - 1.
10922    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10923
10924    Given a 64-bit compilation unit signature or a type signature S, an entry
10925    in the hash table is located as follows:
10926
10927    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10928       the low-order k bits all set to 1.
10929
10930    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10931
10932    3) If the hash table entry at index H matches the signature, use that
10933       entry.  If the hash table entry at index H is unused (all zeroes),
10934       terminate the search: the signature is not present in the table.
10935
10936    4) Let H = (H + H') modulo M. Repeat at Step 3.
10937
10938    Because M > N and H' and M are relatively prime, the search is guaranteed
10939    to stop at an unused slot or find the match.  */
10940
10941 /* Create a hash table to map DWO IDs to their CU/TU entry in
10942    .debug_{info,types}.dwo in DWP_FILE.
10943    Returns NULL if there isn't one.
10944    Note: This function processes DWP files only, not DWO files.  */
10945
10946 static struct dwp_hash_table *
10947 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10948 {
10949   struct objfile *objfile = dwarf2_per_objfile->objfile;
10950   bfd *dbfd = dwp_file->dbfd;
10951   const gdb_byte *index_ptr, *index_end;
10952   struct dwarf2_section_info *index;
10953   uint32_t version, nr_columns, nr_units, nr_slots;
10954   struct dwp_hash_table *htab;
10955
10956   if (is_debug_types)
10957     index = &dwp_file->sections.tu_index;
10958   else
10959     index = &dwp_file->sections.cu_index;
10960
10961   if (dwarf2_section_empty_p (index))
10962     return NULL;
10963   dwarf2_read_section (objfile, index);
10964
10965   index_ptr = index->buffer;
10966   index_end = index_ptr + index->size;
10967
10968   version = read_4_bytes (dbfd, index_ptr);
10969   index_ptr += 4;
10970   if (version == 2)
10971     nr_columns = read_4_bytes (dbfd, index_ptr);
10972   else
10973     nr_columns = 0;
10974   index_ptr += 4;
10975   nr_units = read_4_bytes (dbfd, index_ptr);
10976   index_ptr += 4;
10977   nr_slots = read_4_bytes (dbfd, index_ptr);
10978   index_ptr += 4;
10979
10980   if (version != 1 && version != 2)
10981     {
10982       error (_("Dwarf Error: unsupported DWP file version (%s)"
10983                " [in module %s]"),
10984              pulongest (version), dwp_file->name);
10985     }
10986   if (nr_slots != (nr_slots & -nr_slots))
10987     {
10988       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10989                " is not power of 2 [in module %s]"),
10990              pulongest (nr_slots), dwp_file->name);
10991     }
10992
10993   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10994   htab->version = version;
10995   htab->nr_columns = nr_columns;
10996   htab->nr_units = nr_units;
10997   htab->nr_slots = nr_slots;
10998   htab->hash_table = index_ptr;
10999   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11000
11001   /* Exit early if the table is empty.  */
11002   if (nr_slots == 0 || nr_units == 0
11003       || (version == 2 && nr_columns == 0))
11004     {
11005       /* All must be zero.  */
11006       if (nr_slots != 0 || nr_units != 0
11007           || (version == 2 && nr_columns != 0))
11008         {
11009           complaint (&symfile_complaints,
11010                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
11011                        " all zero [in modules %s]"),
11012                      dwp_file->name);
11013         }
11014       return htab;
11015     }
11016
11017   if (version == 1)
11018     {
11019       htab->section_pool.v1.indices =
11020         htab->unit_table + sizeof (uint32_t) * nr_slots;
11021       /* It's harder to decide whether the section is too small in v1.
11022          V1 is deprecated anyway so we punt.  */
11023     }
11024   else
11025     {
11026       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11027       int *ids = htab->section_pool.v2.section_ids;
11028       /* Reverse map for error checking.  */
11029       int ids_seen[DW_SECT_MAX + 1];
11030       int i;
11031
11032       if (nr_columns < 2)
11033         {
11034           error (_("Dwarf Error: bad DWP hash table, too few columns"
11035                    " in section table [in module %s]"),
11036                  dwp_file->name);
11037         }
11038       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11039         {
11040           error (_("Dwarf Error: bad DWP hash table, too many columns"
11041                    " in section table [in module %s]"),
11042                  dwp_file->name);
11043         }
11044       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11045       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11046       for (i = 0; i < nr_columns; ++i)
11047         {
11048           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11049
11050           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11051             {
11052               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11053                        " in section table [in module %s]"),
11054                      id, dwp_file->name);
11055             }
11056           if (ids_seen[id] != -1)
11057             {
11058               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11059                        " id %d in section table [in module %s]"),
11060                      id, dwp_file->name);
11061             }
11062           ids_seen[id] = i;
11063           ids[i] = id;
11064         }
11065       /* Must have exactly one info or types section.  */
11066       if (((ids_seen[DW_SECT_INFO] != -1)
11067            + (ids_seen[DW_SECT_TYPES] != -1))
11068           != 1)
11069         {
11070           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11071                    " DWO info/types section [in module %s]"),
11072                  dwp_file->name);
11073         }
11074       /* Must have an abbrev section.  */
11075       if (ids_seen[DW_SECT_ABBREV] == -1)
11076         {
11077           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11078                    " section [in module %s]"),
11079                  dwp_file->name);
11080         }
11081       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11082       htab->section_pool.v2.sizes =
11083         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11084                                          * nr_units * nr_columns);
11085       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11086                                           * nr_units * nr_columns))
11087           > index_end)
11088         {
11089           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11090                    " [in module %s]"),
11091                  dwp_file->name);
11092         }
11093     }
11094
11095   return htab;
11096 }
11097
11098 /* Update SECTIONS with the data from SECTP.
11099
11100    This function is like the other "locate" section routines that are
11101    passed to bfd_map_over_sections, but in this context the sections to
11102    read comes from the DWP V1 hash table, not the full ELF section table.
11103
11104    The result is non-zero for success, or zero if an error was found.  */
11105
11106 static int
11107 locate_v1_virtual_dwo_sections (asection *sectp,
11108                                 struct virtual_v1_dwo_sections *sections)
11109 {
11110   const struct dwop_section_names *names = &dwop_section_names;
11111
11112   if (section_is_p (sectp->name, &names->abbrev_dwo))
11113     {
11114       /* There can be only one.  */
11115       if (sections->abbrev.s.section != NULL)
11116         return 0;
11117       sections->abbrev.s.section = sectp;
11118       sections->abbrev.size = bfd_get_section_size (sectp);
11119     }
11120   else if (section_is_p (sectp->name, &names->info_dwo)
11121            || section_is_p (sectp->name, &names->types_dwo))
11122     {
11123       /* There can be only one.  */
11124       if (sections->info_or_types.s.section != NULL)
11125         return 0;
11126       sections->info_or_types.s.section = sectp;
11127       sections->info_or_types.size = bfd_get_section_size (sectp);
11128     }
11129   else if (section_is_p (sectp->name, &names->line_dwo))
11130     {
11131       /* There can be only one.  */
11132       if (sections->line.s.section != NULL)
11133         return 0;
11134       sections->line.s.section = sectp;
11135       sections->line.size = bfd_get_section_size (sectp);
11136     }
11137   else if (section_is_p (sectp->name, &names->loc_dwo))
11138     {
11139       /* There can be only one.  */
11140       if (sections->loc.s.section != NULL)
11141         return 0;
11142       sections->loc.s.section = sectp;
11143       sections->loc.size = bfd_get_section_size (sectp);
11144     }
11145   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11146     {
11147       /* There can be only one.  */
11148       if (sections->macinfo.s.section != NULL)
11149         return 0;
11150       sections->macinfo.s.section = sectp;
11151       sections->macinfo.size = bfd_get_section_size (sectp);
11152     }
11153   else if (section_is_p (sectp->name, &names->macro_dwo))
11154     {
11155       /* There can be only one.  */
11156       if (sections->macro.s.section != NULL)
11157         return 0;
11158       sections->macro.s.section = sectp;
11159       sections->macro.size = bfd_get_section_size (sectp);
11160     }
11161   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11162     {
11163       /* There can be only one.  */
11164       if (sections->str_offsets.s.section != NULL)
11165         return 0;
11166       sections->str_offsets.s.section = sectp;
11167       sections->str_offsets.size = bfd_get_section_size (sectp);
11168     }
11169   else
11170     {
11171       /* No other kind of section is valid.  */
11172       return 0;
11173     }
11174
11175   return 1;
11176 }
11177
11178 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11179    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11180    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11181    This is for DWP version 1 files.  */
11182
11183 static struct dwo_unit *
11184 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
11185                            uint32_t unit_index,
11186                            const char *comp_dir,
11187                            ULONGEST signature, int is_debug_types)
11188 {
11189   struct objfile *objfile = dwarf2_per_objfile->objfile;
11190   const struct dwp_hash_table *dwp_htab =
11191     is_debug_types ? dwp_file->tus : dwp_file->cus;
11192   bfd *dbfd = dwp_file->dbfd;
11193   const char *kind = is_debug_types ? "TU" : "CU";
11194   struct dwo_file *dwo_file;
11195   struct dwo_unit *dwo_unit;
11196   struct virtual_v1_dwo_sections sections;
11197   void **dwo_file_slot;
11198   int i;
11199
11200   gdb_assert (dwp_file->version == 1);
11201
11202   if (dwarf_read_debug)
11203     {
11204       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11205                           kind,
11206                           pulongest (unit_index), hex_string (signature),
11207                           dwp_file->name);
11208     }
11209
11210   /* Fetch the sections of this DWO unit.
11211      Put a limit on the number of sections we look for so that bad data
11212      doesn't cause us to loop forever.  */
11213
11214 #define MAX_NR_V1_DWO_SECTIONS \
11215   (1 /* .debug_info or .debug_types */ \
11216    + 1 /* .debug_abbrev */ \
11217    + 1 /* .debug_line */ \
11218    + 1 /* .debug_loc */ \
11219    + 1 /* .debug_str_offsets */ \
11220    + 1 /* .debug_macro or .debug_macinfo */ \
11221    + 1 /* trailing zero */)
11222
11223   memset (&sections, 0, sizeof (sections));
11224
11225   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11226     {
11227       asection *sectp;
11228       uint32_t section_nr =
11229         read_4_bytes (dbfd,
11230                       dwp_htab->section_pool.v1.indices
11231                       + (unit_index + i) * sizeof (uint32_t));
11232
11233       if (section_nr == 0)
11234         break;
11235       if (section_nr >= dwp_file->num_sections)
11236         {
11237           error (_("Dwarf Error: bad DWP hash table, section number too large"
11238                    " [in module %s]"),
11239                  dwp_file->name);
11240         }
11241
11242       sectp = dwp_file->elf_sections[section_nr];
11243       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11244         {
11245           error (_("Dwarf Error: bad DWP hash table, invalid section found"
11246                    " [in module %s]"),
11247                  dwp_file->name);
11248         }
11249     }
11250
11251   if (i < 2
11252       || dwarf2_section_empty_p (&sections.info_or_types)
11253       || dwarf2_section_empty_p (&sections.abbrev))
11254     {
11255       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11256                " [in module %s]"),
11257              dwp_file->name);
11258     }
11259   if (i == MAX_NR_V1_DWO_SECTIONS)
11260     {
11261       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11262                " [in module %s]"),
11263              dwp_file->name);
11264     }
11265
11266   /* It's easier for the rest of the code if we fake a struct dwo_file and
11267      have dwo_unit "live" in that.  At least for now.
11268
11269      The DWP file can be made up of a random collection of CUs and TUs.
11270      However, for each CU + set of TUs that came from the same original DWO
11271      file, we can combine them back into a virtual DWO file to save space
11272      (fewer struct dwo_file objects to allocate).  Remember that for really
11273      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11274
11275   std::string virtual_dwo_name =
11276     string_printf ("virtual-dwo/%d-%d-%d-%d",
11277                    get_section_id (&sections.abbrev),
11278                    get_section_id (&sections.line),
11279                    get_section_id (&sections.loc),
11280                    get_section_id (&sections.str_offsets));
11281   /* Can we use an existing virtual DWO file?  */
11282   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11283   /* Create one if necessary.  */
11284   if (*dwo_file_slot == NULL)
11285     {
11286       if (dwarf_read_debug)
11287         {
11288           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11289                               virtual_dwo_name.c_str ());
11290         }
11291       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11292       dwo_file->dwo_name
11293         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11294                                         virtual_dwo_name.c_str (),
11295                                         virtual_dwo_name.size ());
11296       dwo_file->comp_dir = comp_dir;
11297       dwo_file->sections.abbrev = sections.abbrev;
11298       dwo_file->sections.line = sections.line;
11299       dwo_file->sections.loc = sections.loc;
11300       dwo_file->sections.macinfo = sections.macinfo;
11301       dwo_file->sections.macro = sections.macro;
11302       dwo_file->sections.str_offsets = sections.str_offsets;
11303       /* The "str" section is global to the entire DWP file.  */
11304       dwo_file->sections.str = dwp_file->sections.str;
11305       /* The info or types section is assigned below to dwo_unit,
11306          there's no need to record it in dwo_file.
11307          Also, we can't simply record type sections in dwo_file because
11308          we record a pointer into the vector in dwo_unit.  As we collect more
11309          types we'll grow the vector and eventually have to reallocate space
11310          for it, invalidating all copies of pointers into the previous
11311          contents.  */
11312       *dwo_file_slot = dwo_file;
11313     }
11314   else
11315     {
11316       if (dwarf_read_debug)
11317         {
11318           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11319                               virtual_dwo_name.c_str ());
11320         }
11321       dwo_file = (struct dwo_file *) *dwo_file_slot;
11322     }
11323
11324   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11325   dwo_unit->dwo_file = dwo_file;
11326   dwo_unit->signature = signature;
11327   dwo_unit->section =
11328     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11329   *dwo_unit->section = sections.info_or_types;
11330   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11331
11332   return dwo_unit;
11333 }
11334
11335 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
11336    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
11337    piece within that section used by a TU/CU, return a virtual section
11338    of just that piece.  */
11339
11340 static struct dwarf2_section_info
11341 create_dwp_v2_section (struct dwarf2_section_info *section,
11342                        bfd_size_type offset, bfd_size_type size)
11343 {
11344   struct dwarf2_section_info result;
11345   asection *sectp;
11346
11347   gdb_assert (section != NULL);
11348   gdb_assert (!section->is_virtual);
11349
11350   memset (&result, 0, sizeof (result));
11351   result.s.containing_section = section;
11352   result.is_virtual = 1;
11353
11354   if (size == 0)
11355     return result;
11356
11357   sectp = get_section_bfd_section (section);
11358
11359   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11360      bounds of the real section.  This is a pretty-rare event, so just
11361      flag an error (easier) instead of a warning and trying to cope.  */
11362   if (sectp == NULL
11363       || offset + size > bfd_get_section_size (sectp))
11364     {
11365       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
11366                " in section %s [in module %s]"),
11367              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
11368              objfile_name (dwarf2_per_objfile->objfile));
11369     }
11370
11371   result.virtual_offset = offset;
11372   result.size = size;
11373   return result;
11374 }
11375
11376 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11377    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11378    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11379    This is for DWP version 2 files.  */
11380
11381 static struct dwo_unit *
11382 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
11383                            uint32_t unit_index,
11384                            const char *comp_dir,
11385                            ULONGEST signature, int is_debug_types)
11386 {
11387   struct objfile *objfile = dwarf2_per_objfile->objfile;
11388   const struct dwp_hash_table *dwp_htab =
11389     is_debug_types ? dwp_file->tus : dwp_file->cus;
11390   bfd *dbfd = dwp_file->dbfd;
11391   const char *kind = is_debug_types ? "TU" : "CU";
11392   struct dwo_file *dwo_file;
11393   struct dwo_unit *dwo_unit;
11394   struct virtual_v2_dwo_sections sections;
11395   void **dwo_file_slot;
11396   int i;
11397
11398   gdb_assert (dwp_file->version == 2);
11399
11400   if (dwarf_read_debug)
11401     {
11402       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
11403                           kind,
11404                           pulongest (unit_index), hex_string (signature),
11405                           dwp_file->name);
11406     }
11407
11408   /* Fetch the section offsets of this DWO unit.  */
11409
11410   memset (&sections, 0, sizeof (sections));
11411
11412   for (i = 0; i < dwp_htab->nr_columns; ++i)
11413     {
11414       uint32_t offset = read_4_bytes (dbfd,
11415                                       dwp_htab->section_pool.v2.offsets
11416                                       + (((unit_index - 1) * dwp_htab->nr_columns
11417                                           + i)
11418                                          * sizeof (uint32_t)));
11419       uint32_t size = read_4_bytes (dbfd,
11420                                     dwp_htab->section_pool.v2.sizes
11421                                     + (((unit_index - 1) * dwp_htab->nr_columns
11422                                         + i)
11423                                        * sizeof (uint32_t)));
11424
11425       switch (dwp_htab->section_pool.v2.section_ids[i])
11426         {
11427         case DW_SECT_INFO:
11428         case DW_SECT_TYPES:
11429           sections.info_or_types_offset = offset;
11430           sections.info_or_types_size = size;
11431           break;
11432         case DW_SECT_ABBREV:
11433           sections.abbrev_offset = offset;
11434           sections.abbrev_size = size;
11435           break;
11436         case DW_SECT_LINE:
11437           sections.line_offset = offset;
11438           sections.line_size = size;
11439           break;
11440         case DW_SECT_LOC:
11441           sections.loc_offset = offset;
11442           sections.loc_size = size;
11443           break;
11444         case DW_SECT_STR_OFFSETS:
11445           sections.str_offsets_offset = offset;
11446           sections.str_offsets_size = size;
11447           break;
11448         case DW_SECT_MACINFO:
11449           sections.macinfo_offset = offset;
11450           sections.macinfo_size = size;
11451           break;
11452         case DW_SECT_MACRO:
11453           sections.macro_offset = offset;
11454           sections.macro_size = size;
11455           break;
11456         }
11457     }
11458
11459   /* It's easier for the rest of the code if we fake a struct dwo_file and
11460      have dwo_unit "live" in that.  At least for now.
11461
11462      The DWP file can be made up of a random collection of CUs and TUs.
11463      However, for each CU + set of TUs that came from the same original DWO
11464      file, we can combine them back into a virtual DWO file to save space
11465      (fewer struct dwo_file objects to allocate).  Remember that for really
11466      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11467
11468   std::string virtual_dwo_name =
11469     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11470                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11471                    (long) (sections.line_size ? sections.line_offset : 0),
11472                    (long) (sections.loc_size ? sections.loc_offset : 0),
11473                    (long) (sections.str_offsets_size
11474                            ? sections.str_offsets_offset : 0));
11475   /* Can we use an existing virtual DWO file?  */
11476   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11477   /* Create one if necessary.  */
11478   if (*dwo_file_slot == NULL)
11479     {
11480       if (dwarf_read_debug)
11481         {
11482           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11483                               virtual_dwo_name.c_str ());
11484         }
11485       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11486       dwo_file->dwo_name
11487         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11488                                         virtual_dwo_name.c_str (),
11489                                         virtual_dwo_name.size ());
11490       dwo_file->comp_dir = comp_dir;
11491       dwo_file->sections.abbrev =
11492         create_dwp_v2_section (&dwp_file->sections.abbrev,
11493                                sections.abbrev_offset, sections.abbrev_size);
11494       dwo_file->sections.line =
11495         create_dwp_v2_section (&dwp_file->sections.line,
11496                                sections.line_offset, sections.line_size);
11497       dwo_file->sections.loc =
11498         create_dwp_v2_section (&dwp_file->sections.loc,
11499                                sections.loc_offset, sections.loc_size);
11500       dwo_file->sections.macinfo =
11501         create_dwp_v2_section (&dwp_file->sections.macinfo,
11502                                sections.macinfo_offset, sections.macinfo_size);
11503       dwo_file->sections.macro =
11504         create_dwp_v2_section (&dwp_file->sections.macro,
11505                                sections.macro_offset, sections.macro_size);
11506       dwo_file->sections.str_offsets =
11507         create_dwp_v2_section (&dwp_file->sections.str_offsets,
11508                                sections.str_offsets_offset,
11509                                sections.str_offsets_size);
11510       /* The "str" section is global to the entire DWP file.  */
11511       dwo_file->sections.str = dwp_file->sections.str;
11512       /* The info or types section is assigned below to dwo_unit,
11513          there's no need to record it in dwo_file.
11514          Also, we can't simply record type sections in dwo_file because
11515          we record a pointer into the vector in dwo_unit.  As we collect more
11516          types we'll grow the vector and eventually have to reallocate space
11517          for it, invalidating all copies of pointers into the previous
11518          contents.  */
11519       *dwo_file_slot = dwo_file;
11520     }
11521   else
11522     {
11523       if (dwarf_read_debug)
11524         {
11525           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11526                               virtual_dwo_name.c_str ());
11527         }
11528       dwo_file = (struct dwo_file *) *dwo_file_slot;
11529     }
11530
11531   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11532   dwo_unit->dwo_file = dwo_file;
11533   dwo_unit->signature = signature;
11534   dwo_unit->section =
11535     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11536   *dwo_unit->section = create_dwp_v2_section (is_debug_types
11537                                               ? &dwp_file->sections.types
11538                                               : &dwp_file->sections.info,
11539                                               sections.info_or_types_offset,
11540                                               sections.info_or_types_size);
11541   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11542
11543   return dwo_unit;
11544 }
11545
11546 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11547    Returns NULL if the signature isn't found.  */
11548
11549 static struct dwo_unit *
11550 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
11551                         ULONGEST signature, int is_debug_types)
11552 {
11553   const struct dwp_hash_table *dwp_htab =
11554     is_debug_types ? dwp_file->tus : dwp_file->cus;
11555   bfd *dbfd = dwp_file->dbfd;
11556   uint32_t mask = dwp_htab->nr_slots - 1;
11557   uint32_t hash = signature & mask;
11558   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11559   unsigned int i;
11560   void **slot;
11561   struct dwo_unit find_dwo_cu;
11562
11563   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11564   find_dwo_cu.signature = signature;
11565   slot = htab_find_slot (is_debug_types
11566                          ? dwp_file->loaded_tus
11567                          : dwp_file->loaded_cus,
11568                          &find_dwo_cu, INSERT);
11569
11570   if (*slot != NULL)
11571     return (struct dwo_unit *) *slot;
11572
11573   /* Use a for loop so that we don't loop forever on bad debug info.  */
11574   for (i = 0; i < dwp_htab->nr_slots; ++i)
11575     {
11576       ULONGEST signature_in_table;
11577
11578       signature_in_table =
11579         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11580       if (signature_in_table == signature)
11581         {
11582           uint32_t unit_index =
11583             read_4_bytes (dbfd,
11584                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11585
11586           if (dwp_file->version == 1)
11587             {
11588               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11589                                                  comp_dir, signature,
11590                                                  is_debug_types);
11591             }
11592           else
11593             {
11594               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11595                                                  comp_dir, signature,
11596                                                  is_debug_types);
11597             }
11598           return (struct dwo_unit *) *slot;
11599         }
11600       if (signature_in_table == 0)
11601         return NULL;
11602       hash = (hash + hash2) & mask;
11603     }
11604
11605   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11606            " [in module %s]"),
11607          dwp_file->name);
11608 }
11609
11610 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11611    Open the file specified by FILE_NAME and hand it off to BFD for
11612    preliminary analysis.  Return a newly initialized bfd *, which
11613    includes a canonicalized copy of FILE_NAME.
11614    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11615    SEARCH_CWD is true if the current directory is to be searched.
11616    It will be searched before debug-file-directory.
11617    If successful, the file is added to the bfd include table of the
11618    objfile's bfd (see gdb_bfd_record_inclusion).
11619    If unable to find/open the file, return NULL.
11620    NOTE: This function is derived from symfile_bfd_open.  */
11621
11622 static gdb_bfd_ref_ptr
11623 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11624 {
11625   int desc, flags;
11626   char *absolute_name;
11627   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11628      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11629      to debug_file_directory.  */
11630   char *search_path;
11631   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11632
11633   if (search_cwd)
11634     {
11635       if (*debug_file_directory != '\0')
11636         search_path = concat (".", dirname_separator_string,
11637                               debug_file_directory, (char *) NULL);
11638       else
11639         search_path = xstrdup (".");
11640     }
11641   else
11642     search_path = xstrdup (debug_file_directory);
11643
11644   flags = OPF_RETURN_REALPATH;
11645   if (is_dwp)
11646     flags |= OPF_SEARCH_IN_PATH;
11647   desc = openp (search_path, flags, file_name,
11648                 O_RDONLY | O_BINARY, &absolute_name);
11649   xfree (search_path);
11650   if (desc < 0)
11651     return NULL;
11652
11653   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11654   xfree (absolute_name);
11655   if (sym_bfd == NULL)
11656     return NULL;
11657   bfd_set_cacheable (sym_bfd.get (), 1);
11658
11659   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11660     return NULL;
11661
11662   /* Success.  Record the bfd as having been included by the objfile's bfd.
11663      This is important because things like demangled_names_hash lives in the
11664      objfile's per_bfd space and may have references to things like symbol
11665      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11666   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11667
11668   return sym_bfd;
11669 }
11670
11671 /* Try to open DWO file FILE_NAME.
11672    COMP_DIR is the DW_AT_comp_dir attribute.
11673    The result is the bfd handle of the file.
11674    If there is a problem finding or opening the file, return NULL.
11675    Upon success, the canonicalized path of the file is stored in the bfd,
11676    same as symfile_bfd_open.  */
11677
11678 static gdb_bfd_ref_ptr
11679 open_dwo_file (const char *file_name, const char *comp_dir)
11680 {
11681   if (IS_ABSOLUTE_PATH (file_name))
11682     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11683
11684   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11685
11686   if (comp_dir != NULL)
11687     {
11688       char *path_to_try = concat (comp_dir, SLASH_STRING,
11689                                   file_name, (char *) NULL);
11690
11691       /* NOTE: If comp_dir is a relative path, this will also try the
11692          search path, which seems useful.  */
11693       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11694                                                 1 /*search_cwd*/));
11695       xfree (path_to_try);
11696       if (abfd != NULL)
11697         return abfd;
11698     }
11699
11700   /* That didn't work, try debug-file-directory, which, despite its name,
11701      is a list of paths.  */
11702
11703   if (*debug_file_directory == '\0')
11704     return NULL;
11705
11706   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11707 }
11708
11709 /* This function is mapped across the sections and remembers the offset and
11710    size of each of the DWO debugging sections we are interested in.  */
11711
11712 static void
11713 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11714 {
11715   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11716   const struct dwop_section_names *names = &dwop_section_names;
11717
11718   if (section_is_p (sectp->name, &names->abbrev_dwo))
11719     {
11720       dwo_sections->abbrev.s.section = sectp;
11721       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11722     }
11723   else if (section_is_p (sectp->name, &names->info_dwo))
11724     {
11725       dwo_sections->info.s.section = sectp;
11726       dwo_sections->info.size = bfd_get_section_size (sectp);
11727     }
11728   else if (section_is_p (sectp->name, &names->line_dwo))
11729     {
11730       dwo_sections->line.s.section = sectp;
11731       dwo_sections->line.size = bfd_get_section_size (sectp);
11732     }
11733   else if (section_is_p (sectp->name, &names->loc_dwo))
11734     {
11735       dwo_sections->loc.s.section = sectp;
11736       dwo_sections->loc.size = bfd_get_section_size (sectp);
11737     }
11738   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11739     {
11740       dwo_sections->macinfo.s.section = sectp;
11741       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11742     }
11743   else if (section_is_p (sectp->name, &names->macro_dwo))
11744     {
11745       dwo_sections->macro.s.section = sectp;
11746       dwo_sections->macro.size = bfd_get_section_size (sectp);
11747     }
11748   else if (section_is_p (sectp->name, &names->str_dwo))
11749     {
11750       dwo_sections->str.s.section = sectp;
11751       dwo_sections->str.size = bfd_get_section_size (sectp);
11752     }
11753   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11754     {
11755       dwo_sections->str_offsets.s.section = sectp;
11756       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11757     }
11758   else if (section_is_p (sectp->name, &names->types_dwo))
11759     {
11760       struct dwarf2_section_info type_section;
11761
11762       memset (&type_section, 0, sizeof (type_section));
11763       type_section.s.section = sectp;
11764       type_section.size = bfd_get_section_size (sectp);
11765       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11766                      &type_section);
11767     }
11768 }
11769
11770 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11771    by PER_CU.  This is for the non-DWP case.
11772    The result is NULL if DWO_NAME can't be found.  */
11773
11774 static struct dwo_file *
11775 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11776                         const char *dwo_name, const char *comp_dir)
11777 {
11778   struct objfile *objfile = dwarf2_per_objfile->objfile;
11779   struct dwo_file *dwo_file;
11780   struct cleanup *cleanups;
11781
11782   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11783   if (dbfd == NULL)
11784     {
11785       if (dwarf_read_debug)
11786         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11787       return NULL;
11788     }
11789   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11790   dwo_file->dwo_name = dwo_name;
11791   dwo_file->comp_dir = comp_dir;
11792   dwo_file->dbfd = dbfd.release ();
11793
11794   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11795
11796   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11797                          &dwo_file->sections);
11798
11799   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11800
11801   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11802                                  dwo_file->tus);
11803
11804   discard_cleanups (cleanups);
11805
11806   if (dwarf_read_debug)
11807     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11808
11809   return dwo_file;
11810 }
11811
11812 /* This function is mapped across the sections and remembers the offset and
11813    size of each of the DWP debugging sections common to version 1 and 2 that
11814    we are interested in.  */
11815
11816 static void
11817 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11818                                    void *dwp_file_ptr)
11819 {
11820   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11821   const struct dwop_section_names *names = &dwop_section_names;
11822   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11823
11824   /* Record the ELF section number for later lookup: this is what the
11825      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11826   gdb_assert (elf_section_nr < dwp_file->num_sections);
11827   dwp_file->elf_sections[elf_section_nr] = sectp;
11828
11829   /* Look for specific sections that we need.  */
11830   if (section_is_p (sectp->name, &names->str_dwo))
11831     {
11832       dwp_file->sections.str.s.section = sectp;
11833       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11834     }
11835   else if (section_is_p (sectp->name, &names->cu_index))
11836     {
11837       dwp_file->sections.cu_index.s.section = sectp;
11838       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11839     }
11840   else if (section_is_p (sectp->name, &names->tu_index))
11841     {
11842       dwp_file->sections.tu_index.s.section = sectp;
11843       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11844     }
11845 }
11846
11847 /* This function is mapped across the sections and remembers the offset and
11848    size of each of the DWP version 2 debugging sections that we are interested
11849    in.  This is split into a separate function because we don't know if we
11850    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11851
11852 static void
11853 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11854 {
11855   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11856   const struct dwop_section_names *names = &dwop_section_names;
11857   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11858
11859   /* Record the ELF section number for later lookup: this is what the
11860      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11861   gdb_assert (elf_section_nr < dwp_file->num_sections);
11862   dwp_file->elf_sections[elf_section_nr] = sectp;
11863
11864   /* Look for specific sections that we need.  */
11865   if (section_is_p (sectp->name, &names->abbrev_dwo))
11866     {
11867       dwp_file->sections.abbrev.s.section = sectp;
11868       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11869     }
11870   else if (section_is_p (sectp->name, &names->info_dwo))
11871     {
11872       dwp_file->sections.info.s.section = sectp;
11873       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11874     }
11875   else if (section_is_p (sectp->name, &names->line_dwo))
11876     {
11877       dwp_file->sections.line.s.section = sectp;
11878       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11879     }
11880   else if (section_is_p (sectp->name, &names->loc_dwo))
11881     {
11882       dwp_file->sections.loc.s.section = sectp;
11883       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11884     }
11885   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11886     {
11887       dwp_file->sections.macinfo.s.section = sectp;
11888       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11889     }
11890   else if (section_is_p (sectp->name, &names->macro_dwo))
11891     {
11892       dwp_file->sections.macro.s.section = sectp;
11893       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11894     }
11895   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11896     {
11897       dwp_file->sections.str_offsets.s.section = sectp;
11898       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11899     }
11900   else if (section_is_p (sectp->name, &names->types_dwo))
11901     {
11902       dwp_file->sections.types.s.section = sectp;
11903       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11904     }
11905 }
11906
11907 /* Hash function for dwp_file loaded CUs/TUs.  */
11908
11909 static hashval_t
11910 hash_dwp_loaded_cutus (const void *item)
11911 {
11912   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11913
11914   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11915   return dwo_unit->signature;
11916 }
11917
11918 /* Equality function for dwp_file loaded CUs/TUs.  */
11919
11920 static int
11921 eq_dwp_loaded_cutus (const void *a, const void *b)
11922 {
11923   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11924   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11925
11926   return dua->signature == dub->signature;
11927 }
11928
11929 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11930
11931 static htab_t
11932 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11933 {
11934   return htab_create_alloc_ex (3,
11935                                hash_dwp_loaded_cutus,
11936                                eq_dwp_loaded_cutus,
11937                                NULL,
11938                                &objfile->objfile_obstack,
11939                                hashtab_obstack_allocate,
11940                                dummy_obstack_deallocate);
11941 }
11942
11943 /* Try to open DWP file FILE_NAME.
11944    The result is the bfd handle of the file.
11945    If there is a problem finding or opening the file, return NULL.
11946    Upon success, the canonicalized path of the file is stored in the bfd,
11947    same as symfile_bfd_open.  */
11948
11949 static gdb_bfd_ref_ptr
11950 open_dwp_file (const char *file_name)
11951 {
11952   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11953                                             1 /*search_cwd*/));
11954   if (abfd != NULL)
11955     return abfd;
11956
11957   /* Work around upstream bug 15652.
11958      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11959      [Whether that's a "bug" is debatable, but it is getting in our way.]
11960      We have no real idea where the dwp file is, because gdb's realpath-ing
11961      of the executable's path may have discarded the needed info.
11962      [IWBN if the dwp file name was recorded in the executable, akin to
11963      .gnu_debuglink, but that doesn't exist yet.]
11964      Strip the directory from FILE_NAME and search again.  */
11965   if (*debug_file_directory != '\0')
11966     {
11967       /* Don't implicitly search the current directory here.
11968          If the user wants to search "." to handle this case,
11969          it must be added to debug-file-directory.  */
11970       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11971                                  0 /*search_cwd*/);
11972     }
11973
11974   return NULL;
11975 }
11976
11977 /* Initialize the use of the DWP file for the current objfile.
11978    By convention the name of the DWP file is ${objfile}.dwp.
11979    The result is NULL if it can't be found.  */
11980
11981 static struct dwp_file *
11982 open_and_init_dwp_file (void)
11983 {
11984   struct objfile *objfile = dwarf2_per_objfile->objfile;
11985   struct dwp_file *dwp_file;
11986
11987   /* Try to find first .dwp for the binary file before any symbolic links
11988      resolving.  */
11989
11990   /* If the objfile is a debug file, find the name of the real binary
11991      file and get the name of dwp file from there.  */
11992   std::string dwp_name;
11993   if (objfile->separate_debug_objfile_backlink != NULL)
11994     {
11995       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11996       const char *backlink_basename = lbasename (backlink->original_name);
11997
11998       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11999     }
12000   else
12001     dwp_name = objfile->original_name;
12002
12003   dwp_name += ".dwp";
12004
12005   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
12006   if (dbfd == NULL
12007       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12008     {
12009       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12010       dwp_name = objfile_name (objfile);
12011       dwp_name += ".dwp";
12012       dbfd = open_dwp_file (dwp_name.c_str ());
12013     }
12014
12015   if (dbfd == NULL)
12016     {
12017       if (dwarf_read_debug)
12018         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12019       return NULL;
12020     }
12021   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
12022   dwp_file->name = bfd_get_filename (dbfd.get ());
12023   dwp_file->dbfd = dbfd.release ();
12024
12025   /* +1: section 0 is unused */
12026   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
12027   dwp_file->elf_sections =
12028     OBSTACK_CALLOC (&objfile->objfile_obstack,
12029                     dwp_file->num_sections, asection *);
12030
12031   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
12032                          dwp_file);
12033
12034   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
12035
12036   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
12037
12038   /* The DWP file version is stored in the hash table.  Oh well.  */
12039   if (dwp_file->cus && dwp_file->tus
12040       && dwp_file->cus->version != dwp_file->tus->version)
12041     {
12042       /* Technically speaking, we should try to limp along, but this is
12043          pretty bizarre.  We use pulongest here because that's the established
12044          portability solution (e.g, we cannot use %u for uint32_t).  */
12045       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12046                " TU version %s [in DWP file %s]"),
12047              pulongest (dwp_file->cus->version),
12048              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12049     }
12050
12051   if (dwp_file->cus)
12052     dwp_file->version = dwp_file->cus->version;
12053   else if (dwp_file->tus)
12054     dwp_file->version = dwp_file->tus->version;
12055   else
12056     dwp_file->version = 2;
12057
12058   if (dwp_file->version == 2)
12059     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
12060                            dwp_file);
12061
12062   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
12063   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
12064
12065   if (dwarf_read_debug)
12066     {
12067       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12068       fprintf_unfiltered (gdb_stdlog,
12069                           "    %s CUs, %s TUs\n",
12070                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12071                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12072     }
12073
12074   return dwp_file;
12075 }
12076
12077 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12078
12079 static struct dwp_file *
12080 get_dwp_file (void)
12081 {
12082   if (! dwarf2_per_objfile->dwp_checked)
12083     {
12084       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
12085       dwarf2_per_objfile->dwp_checked = 1;
12086     }
12087   return dwarf2_per_objfile->dwp_file;
12088 }
12089
12090 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12091    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12092    or in the DWP file for the objfile, referenced by THIS_UNIT.
12093    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12094    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12095
12096    This is called, for example, when wanting to read a variable with a
12097    complex location.  Therefore we don't want to do file i/o for every call.
12098    Therefore we don't want to look for a DWO file on every call.
12099    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12100    then we check if we've already seen DWO_NAME, and only THEN do we check
12101    for a DWO file.
12102
12103    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12104    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12105
12106 static struct dwo_unit *
12107 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12108                  const char *dwo_name, const char *comp_dir,
12109                  ULONGEST signature, int is_debug_types)
12110 {
12111   struct objfile *objfile = dwarf2_per_objfile->objfile;
12112   const char *kind = is_debug_types ? "TU" : "CU";
12113   void **dwo_file_slot;
12114   struct dwo_file *dwo_file;
12115   struct dwp_file *dwp_file;
12116
12117   /* First see if there's a DWP file.
12118      If we have a DWP file but didn't find the DWO inside it, don't
12119      look for the original DWO file.  It makes gdb behave differently
12120      depending on whether one is debugging in the build tree.  */
12121
12122   dwp_file = get_dwp_file ();
12123   if (dwp_file != NULL)
12124     {
12125       const struct dwp_hash_table *dwp_htab =
12126         is_debug_types ? dwp_file->tus : dwp_file->cus;
12127
12128       if (dwp_htab != NULL)
12129         {
12130           struct dwo_unit *dwo_cutu =
12131             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
12132                                     signature, is_debug_types);
12133
12134           if (dwo_cutu != NULL)
12135             {
12136               if (dwarf_read_debug)
12137                 {
12138                   fprintf_unfiltered (gdb_stdlog,
12139                                       "Virtual DWO %s %s found: @%s\n",
12140                                       kind, hex_string (signature),
12141                                       host_address_to_string (dwo_cutu));
12142                 }
12143               return dwo_cutu;
12144             }
12145         }
12146     }
12147   else
12148     {
12149       /* No DWP file, look for the DWO file.  */
12150
12151       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
12152       if (*dwo_file_slot == NULL)
12153         {
12154           /* Read in the file and build a table of the CUs/TUs it contains.  */
12155           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12156         }
12157       /* NOTE: This will be NULL if unable to open the file.  */
12158       dwo_file = (struct dwo_file *) *dwo_file_slot;
12159
12160       if (dwo_file != NULL)
12161         {
12162           struct dwo_unit *dwo_cutu = NULL;
12163
12164           if (is_debug_types && dwo_file->tus)
12165             {
12166               struct dwo_unit find_dwo_cutu;
12167
12168               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12169               find_dwo_cutu.signature = signature;
12170               dwo_cutu
12171                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
12172             }
12173           else if (!is_debug_types && dwo_file->cus)
12174             {
12175               struct dwo_unit find_dwo_cutu;
12176
12177               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12178               find_dwo_cutu.signature = signature;
12179               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
12180                                                        &find_dwo_cutu);
12181             }
12182
12183           if (dwo_cutu != NULL)
12184             {
12185               if (dwarf_read_debug)
12186                 {
12187                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12188                                       kind, dwo_name, hex_string (signature),
12189                                       host_address_to_string (dwo_cutu));
12190                 }
12191               return dwo_cutu;
12192             }
12193         }
12194     }
12195
12196   /* We didn't find it.  This could mean a dwo_id mismatch, or
12197      someone deleted the DWO/DWP file, or the search path isn't set up
12198      correctly to find the file.  */
12199
12200   if (dwarf_read_debug)
12201     {
12202       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
12203                           kind, dwo_name, hex_string (signature));
12204     }
12205
12206   /* This is a warning and not a complaint because it can be caused by
12207      pilot error (e.g., user accidentally deleting the DWO).  */
12208   {
12209     /* Print the name of the DWP file if we looked there, helps the user
12210        better diagnose the problem.  */
12211     std::string dwp_text;
12212
12213     if (dwp_file != NULL)
12214       dwp_text = string_printf (" [in DWP file %s]",
12215                                 lbasename (dwp_file->name));
12216
12217     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
12218                " [in module %s]"),
12219              kind, dwo_name, hex_string (signature),
12220              dwp_text.c_str (),
12221              this_unit->is_debug_types ? "TU" : "CU",
12222              to_underlying (this_unit->sect_off), objfile_name (objfile));
12223   }
12224   return NULL;
12225 }
12226
12227 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12228    See lookup_dwo_cutu_unit for details.  */
12229
12230 static struct dwo_unit *
12231 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
12232                       const char *dwo_name, const char *comp_dir,
12233                       ULONGEST signature)
12234 {
12235   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
12236 }
12237
12238 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12239    See lookup_dwo_cutu_unit for details.  */
12240
12241 static struct dwo_unit *
12242 lookup_dwo_type_unit (struct signatured_type *this_tu,
12243                       const char *dwo_name, const char *comp_dir)
12244 {
12245   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
12246 }
12247
12248 /* Traversal function for queue_and_load_all_dwo_tus.  */
12249
12250 static int
12251 queue_and_load_dwo_tu (void **slot, void *info)
12252 {
12253   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12254   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
12255   ULONGEST signature = dwo_unit->signature;
12256   struct signatured_type *sig_type =
12257     lookup_dwo_signatured_type (per_cu->cu, signature);
12258
12259   if (sig_type != NULL)
12260     {
12261       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
12262
12263       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12264          a real dependency of PER_CU on SIG_TYPE.  That is detected later
12265          while processing PER_CU.  */
12266       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
12267         load_full_type_unit (sig_cu);
12268       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
12269     }
12270
12271   return 1;
12272 }
12273
12274 /* Queue all TUs contained in the DWO of PER_CU to be read in.
12275    The DWO may have the only definition of the type, though it may not be
12276    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12277    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12278
12279 static void
12280 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
12281 {
12282   struct dwo_unit *dwo_unit;
12283   struct dwo_file *dwo_file;
12284
12285   gdb_assert (!per_cu->is_debug_types);
12286   gdb_assert (get_dwp_file () == NULL);
12287   gdb_assert (per_cu->cu != NULL);
12288
12289   dwo_unit = per_cu->cu->dwo_unit;
12290   gdb_assert (dwo_unit != NULL);
12291
12292   dwo_file = dwo_unit->dwo_file;
12293   if (dwo_file->tus != NULL)
12294     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
12295 }
12296
12297 /* Free all resources associated with DWO_FILE.
12298    Close the DWO file and munmap the sections.
12299    All memory should be on the objfile obstack.  */
12300
12301 static void
12302 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
12303 {
12304
12305   /* Note: dbfd is NULL for virtual DWO files.  */
12306   gdb_bfd_unref (dwo_file->dbfd);
12307
12308   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
12309 }
12310
12311 /* Wrapper for free_dwo_file for use in cleanups.  */
12312
12313 static void
12314 free_dwo_file_cleanup (void *arg)
12315 {
12316   struct dwo_file *dwo_file = (struct dwo_file *) arg;
12317   struct objfile *objfile = dwarf2_per_objfile->objfile;
12318
12319   free_dwo_file (dwo_file, objfile);
12320 }
12321
12322 /* Traversal function for free_dwo_files.  */
12323
12324 static int
12325 free_dwo_file_from_slot (void **slot, void *info)
12326 {
12327   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
12328   struct objfile *objfile = (struct objfile *) info;
12329
12330   free_dwo_file (dwo_file, objfile);
12331
12332   return 1;
12333 }
12334
12335 /* Free all resources associated with DWO_FILES.  */
12336
12337 static void
12338 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
12339 {
12340   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
12341 }
12342 \f
12343 /* Read in various DIEs.  */
12344
12345 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12346    Inherit only the children of the DW_AT_abstract_origin DIE not being
12347    already referenced by DW_AT_abstract_origin from the children of the
12348    current DIE.  */
12349
12350 static void
12351 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12352 {
12353   struct die_info *child_die;
12354   sect_offset *offsetp;
12355   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12356   struct die_info *origin_die;
12357   /* Iterator of the ORIGIN_DIE children.  */
12358   struct die_info *origin_child_die;
12359   struct attribute *attr;
12360   struct dwarf2_cu *origin_cu;
12361   struct pending **origin_previous_list_in_scope;
12362
12363   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12364   if (!attr)
12365     return;
12366
12367   /* Note that following die references may follow to a die in a
12368      different cu.  */
12369
12370   origin_cu = cu;
12371   origin_die = follow_die_ref (die, attr, &origin_cu);
12372
12373   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12374      symbols in.  */
12375   origin_previous_list_in_scope = origin_cu->list_in_scope;
12376   origin_cu->list_in_scope = cu->list_in_scope;
12377
12378   if (die->tag != origin_die->tag
12379       && !(die->tag == DW_TAG_inlined_subroutine
12380            && origin_die->tag == DW_TAG_subprogram))
12381     complaint (&symfile_complaints,
12382                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
12383                to_underlying (die->sect_off),
12384                to_underlying (origin_die->sect_off));
12385
12386   std::vector<sect_offset> offsets;
12387
12388   for (child_die = die->child;
12389        child_die && child_die->tag;
12390        child_die = sibling_die (child_die))
12391     {
12392       struct die_info *child_origin_die;
12393       struct dwarf2_cu *child_origin_cu;
12394
12395       /* We are trying to process concrete instance entries:
12396          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12397          it's not relevant to our analysis here. i.e. detecting DIEs that are
12398          present in the abstract instance but not referenced in the concrete
12399          one.  */
12400       if (child_die->tag == DW_TAG_call_site
12401           || child_die->tag == DW_TAG_GNU_call_site)
12402         continue;
12403
12404       /* For each CHILD_DIE, find the corresponding child of
12405          ORIGIN_DIE.  If there is more than one layer of
12406          DW_AT_abstract_origin, follow them all; there shouldn't be,
12407          but GCC versions at least through 4.4 generate this (GCC PR
12408          40573).  */
12409       child_origin_die = child_die;
12410       child_origin_cu = cu;
12411       while (1)
12412         {
12413           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12414                               child_origin_cu);
12415           if (attr == NULL)
12416             break;
12417           child_origin_die = follow_die_ref (child_origin_die, attr,
12418                                              &child_origin_cu);
12419         }
12420
12421       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12422          counterpart may exist.  */
12423       if (child_origin_die != child_die)
12424         {
12425           if (child_die->tag != child_origin_die->tag
12426               && !(child_die->tag == DW_TAG_inlined_subroutine
12427                    && child_origin_die->tag == DW_TAG_subprogram))
12428             complaint (&symfile_complaints,
12429                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12430                          "different tags"),
12431                        to_underlying (child_die->sect_off),
12432                        to_underlying (child_origin_die->sect_off));
12433           if (child_origin_die->parent != origin_die)
12434             complaint (&symfile_complaints,
12435                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12436                          "different parents"),
12437                        to_underlying (child_die->sect_off),
12438                        to_underlying (child_origin_die->sect_off));
12439           else
12440             offsets.push_back (child_origin_die->sect_off);
12441         }
12442     }
12443   std::sort (offsets.begin (), offsets.end ());
12444   sect_offset *offsets_end = offsets.data () + offsets.size ();
12445   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12446     if (offsetp[-1] == *offsetp)
12447       complaint (&symfile_complaints,
12448                  _("Multiple children of DIE 0x%x refer "
12449                    "to DIE 0x%x as their abstract origin"),
12450                  to_underlying (die->sect_off), to_underlying (*offsetp));
12451
12452   offsetp = offsets.data ();
12453   origin_child_die = origin_die->child;
12454   while (origin_child_die && origin_child_die->tag)
12455     {
12456       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12457       while (offsetp < offsets_end
12458              && *offsetp < origin_child_die->sect_off)
12459         offsetp++;
12460       if (offsetp >= offsets_end
12461           || *offsetp > origin_child_die->sect_off)
12462         {
12463           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12464              Check whether we're already processing ORIGIN_CHILD_DIE.
12465              This can happen with mutually referenced abstract_origins.
12466              PR 16581.  */
12467           if (!origin_child_die->in_process)
12468             process_die (origin_child_die, origin_cu);
12469         }
12470       origin_child_die = sibling_die (origin_child_die);
12471     }
12472   origin_cu->list_in_scope = origin_previous_list_in_scope;
12473 }
12474
12475 static void
12476 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12477 {
12478   struct objfile *objfile = cu->objfile;
12479   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12480   struct context_stack *newobj;
12481   CORE_ADDR lowpc;
12482   CORE_ADDR highpc;
12483   struct die_info *child_die;
12484   struct attribute *attr, *call_line, *call_file;
12485   const char *name;
12486   CORE_ADDR baseaddr;
12487   struct block *block;
12488   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12489   std::vector<struct symbol *> template_args;
12490   struct template_symbol *templ_func = NULL;
12491
12492   if (inlined_func)
12493     {
12494       /* If we do not have call site information, we can't show the
12495          caller of this inlined function.  That's too confusing, so
12496          only use the scope for local variables.  */
12497       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12498       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12499       if (call_line == NULL || call_file == NULL)
12500         {
12501           read_lexical_block_scope (die, cu);
12502           return;
12503         }
12504     }
12505
12506   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12507
12508   name = dwarf2_name (die, cu);
12509
12510   /* Ignore functions with missing or empty names.  These are actually
12511      illegal according to the DWARF standard.  */
12512   if (name == NULL)
12513     {
12514       complaint (&symfile_complaints,
12515                  _("missing name for subprogram DIE at %d"),
12516                  to_underlying (die->sect_off));
12517       return;
12518     }
12519
12520   /* Ignore functions with missing or invalid low and high pc attributes.  */
12521   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12522       <= PC_BOUNDS_INVALID)
12523     {
12524       attr = dwarf2_attr (die, DW_AT_external, cu);
12525       if (!attr || !DW_UNSND (attr))
12526         complaint (&symfile_complaints,
12527                    _("cannot get low and high bounds "
12528                      "for subprogram DIE at %d"),
12529                    to_underlying (die->sect_off));
12530       return;
12531     }
12532
12533   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12534   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12535
12536   /* If we have any template arguments, then we must allocate a
12537      different sort of symbol.  */
12538   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
12539     {
12540       if (child_die->tag == DW_TAG_template_type_param
12541           || child_die->tag == DW_TAG_template_value_param)
12542         {
12543           templ_func = allocate_template_symbol (objfile);
12544           templ_func->subclass = SYMBOL_TEMPLATE;
12545           break;
12546         }
12547     }
12548
12549   newobj = push_context (0, lowpc);
12550   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
12551                                (struct symbol *) templ_func);
12552
12553   /* If there is a location expression for DW_AT_frame_base, record
12554      it.  */
12555   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12556   if (attr)
12557     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12558
12559   /* If there is a location for the static link, record it.  */
12560   newobj->static_link = NULL;
12561   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12562   if (attr)
12563     {
12564       newobj->static_link
12565         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12566       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12567     }
12568
12569   cu->list_in_scope = &local_symbols;
12570
12571   if (die->child != NULL)
12572     {
12573       child_die = die->child;
12574       while (child_die && child_die->tag)
12575         {
12576           if (child_die->tag == DW_TAG_template_type_param
12577               || child_die->tag == DW_TAG_template_value_param)
12578             {
12579               struct symbol *arg = new_symbol (child_die, NULL, cu);
12580
12581               if (arg != NULL)
12582                 template_args.push_back (arg);
12583             }
12584           else
12585             process_die (child_die, cu);
12586           child_die = sibling_die (child_die);
12587         }
12588     }
12589
12590   inherit_abstract_dies (die, cu);
12591
12592   /* If we have a DW_AT_specification, we might need to import using
12593      directives from the context of the specification DIE.  See the
12594      comment in determine_prefix.  */
12595   if (cu->language == language_cplus
12596       && dwarf2_attr (die, DW_AT_specification, cu))
12597     {
12598       struct dwarf2_cu *spec_cu = cu;
12599       struct die_info *spec_die = die_specification (die, &spec_cu);
12600
12601       while (spec_die)
12602         {
12603           child_die = spec_die->child;
12604           while (child_die && child_die->tag)
12605             {
12606               if (child_die->tag == DW_TAG_imported_module)
12607                 process_die (child_die, spec_cu);
12608               child_die = sibling_die (child_die);
12609             }
12610
12611           /* In some cases, GCC generates specification DIEs that
12612              themselves contain DW_AT_specification attributes.  */
12613           spec_die = die_specification (spec_die, &spec_cu);
12614         }
12615     }
12616
12617   newobj = pop_context ();
12618   /* Make a block for the local symbols within.  */
12619   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12620                         newobj->static_link, lowpc, highpc);
12621
12622   /* For C++, set the block's scope.  */
12623   if ((cu->language == language_cplus
12624        || cu->language == language_fortran
12625        || cu->language == language_d
12626        || cu->language == language_rust)
12627       && cu->processing_has_namespace_info)
12628     block_set_scope (block, determine_prefix (die, cu),
12629                      &objfile->objfile_obstack);
12630
12631   /* If we have address ranges, record them.  */
12632   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12633
12634   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12635
12636   /* Attach template arguments to function.  */
12637   if (!template_args.empty ())
12638     {
12639       gdb_assert (templ_func != NULL);
12640
12641       templ_func->n_template_arguments = template_args.size ();
12642       templ_func->template_arguments
12643         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12644                      templ_func->n_template_arguments);
12645       memcpy (templ_func->template_arguments,
12646               template_args.data (),
12647               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12648     }
12649
12650   /* In C++, we can have functions nested inside functions (e.g., when
12651      a function declares a class that has methods).  This means that
12652      when we finish processing a function scope, we may need to go
12653      back to building a containing block's symbol lists.  */
12654   local_symbols = newobj->locals;
12655   local_using_directives = newobj->local_using_directives;
12656
12657   /* If we've finished processing a top-level function, subsequent
12658      symbols go in the file symbol list.  */
12659   if (outermost_context_p ())
12660     cu->list_in_scope = &file_symbols;
12661 }
12662
12663 /* Process all the DIES contained within a lexical block scope.  Start
12664    a new scope, process the dies, and then close the scope.  */
12665
12666 static void
12667 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12668 {
12669   struct objfile *objfile = cu->objfile;
12670   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12671   struct context_stack *newobj;
12672   CORE_ADDR lowpc, highpc;
12673   struct die_info *child_die;
12674   CORE_ADDR baseaddr;
12675
12676   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12677
12678   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12679   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12680      as multiple lexical blocks?  Handling children in a sane way would
12681      be nasty.  Might be easier to properly extend generic blocks to
12682      describe ranges.  */
12683   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12684     {
12685     case PC_BOUNDS_NOT_PRESENT:
12686       /* DW_TAG_lexical_block has no attributes, process its children as if
12687          there was no wrapping by that DW_TAG_lexical_block.
12688          GCC does no longer produces such DWARF since GCC r224161.  */
12689       for (child_die = die->child;
12690            child_die != NULL && child_die->tag;
12691            child_die = sibling_die (child_die))
12692         process_die (child_die, cu);
12693       return;
12694     case PC_BOUNDS_INVALID:
12695       return;
12696     }
12697   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12698   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12699
12700   push_context (0, lowpc);
12701   if (die->child != NULL)
12702     {
12703       child_die = die->child;
12704       while (child_die && child_die->tag)
12705         {
12706           process_die (child_die, cu);
12707           child_die = sibling_die (child_die);
12708         }
12709     }
12710   inherit_abstract_dies (die, cu);
12711   newobj = pop_context ();
12712
12713   if (local_symbols != NULL || local_using_directives != NULL)
12714     {
12715       struct block *block
12716         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12717                         newobj->start_addr, highpc);
12718
12719       /* Note that recording ranges after traversing children, as we
12720          do here, means that recording a parent's ranges entails
12721          walking across all its children's ranges as they appear in
12722          the address map, which is quadratic behavior.
12723
12724          It would be nicer to record the parent's ranges before
12725          traversing its children, simply overriding whatever you find
12726          there.  But since we don't even decide whether to create a
12727          block until after we've traversed its children, that's hard
12728          to do.  */
12729       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12730     }
12731   local_symbols = newobj->locals;
12732   local_using_directives = newobj->local_using_directives;
12733 }
12734
12735 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12736
12737 static void
12738 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12739 {
12740   struct objfile *objfile = cu->objfile;
12741   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12742   CORE_ADDR pc, baseaddr;
12743   struct attribute *attr;
12744   struct call_site *call_site, call_site_local;
12745   void **slot;
12746   int nparams;
12747   struct die_info *child_die;
12748
12749   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12750
12751   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12752   if (attr == NULL)
12753     {
12754       /* This was a pre-DWARF-5 GNU extension alias
12755          for DW_AT_call_return_pc.  */
12756       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12757     }
12758   if (!attr)
12759     {
12760       complaint (&symfile_complaints,
12761                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12762                    "DIE 0x%x [in module %s]"),
12763                  to_underlying (die->sect_off), objfile_name (objfile));
12764       return;
12765     }
12766   pc = attr_value_as_address (attr) + baseaddr;
12767   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12768
12769   if (cu->call_site_htab == NULL)
12770     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12771                                                NULL, &objfile->objfile_obstack,
12772                                                hashtab_obstack_allocate, NULL);
12773   call_site_local.pc = pc;
12774   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12775   if (*slot != NULL)
12776     {
12777       complaint (&symfile_complaints,
12778                  _("Duplicate PC %s for DW_TAG_call_site "
12779                    "DIE 0x%x [in module %s]"),
12780                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12781                  objfile_name (objfile));
12782       return;
12783     }
12784
12785   /* Count parameters at the caller.  */
12786
12787   nparams = 0;
12788   for (child_die = die->child; child_die && child_die->tag;
12789        child_die = sibling_die (child_die))
12790     {
12791       if (child_die->tag != DW_TAG_call_site_parameter
12792           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12793         {
12794           complaint (&symfile_complaints,
12795                      _("Tag %d is not DW_TAG_call_site_parameter in "
12796                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12797                      child_die->tag, to_underlying (child_die->sect_off),
12798                      objfile_name (objfile));
12799           continue;
12800         }
12801
12802       nparams++;
12803     }
12804
12805   call_site
12806     = ((struct call_site *)
12807        obstack_alloc (&objfile->objfile_obstack,
12808                       sizeof (*call_site)
12809                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12810   *slot = call_site;
12811   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12812   call_site->pc = pc;
12813
12814   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12815       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12816     {
12817       struct die_info *func_die;
12818
12819       /* Skip also over DW_TAG_inlined_subroutine.  */
12820       for (func_die = die->parent;
12821            func_die && func_die->tag != DW_TAG_subprogram
12822            && func_die->tag != DW_TAG_subroutine_type;
12823            func_die = func_die->parent);
12824
12825       /* DW_AT_call_all_calls is a superset
12826          of DW_AT_call_all_tail_calls.  */
12827       if (func_die
12828           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12829           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12830           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12831           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12832         {
12833           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12834              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12835              both the initial caller containing the real return address PC and
12836              the final callee containing the current PC of a chain of tail
12837              calls do not need to have the tail call list complete.  But any
12838              function candidate for a virtual tail call frame searched via
12839              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12840              determined unambiguously.  */
12841         }
12842       else
12843         {
12844           struct type *func_type = NULL;
12845
12846           if (func_die)
12847             func_type = get_die_type (func_die, cu);
12848           if (func_type != NULL)
12849             {
12850               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12851
12852               /* Enlist this call site to the function.  */
12853               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12854               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12855             }
12856           else
12857             complaint (&symfile_complaints,
12858                        _("Cannot find function owning DW_TAG_call_site "
12859                          "DIE 0x%x [in module %s]"),
12860                        to_underlying (die->sect_off), objfile_name (objfile));
12861         }
12862     }
12863
12864   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12865   if (attr == NULL)
12866     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12867   if (attr == NULL)
12868     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12869   if (attr == NULL)
12870     {
12871       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12872       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12873     }
12874   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12875   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12876     /* Keep NULL DWARF_BLOCK.  */;
12877   else if (attr_form_is_block (attr))
12878     {
12879       struct dwarf2_locexpr_baton *dlbaton;
12880
12881       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12882       dlbaton->data = DW_BLOCK (attr)->data;
12883       dlbaton->size = DW_BLOCK (attr)->size;
12884       dlbaton->per_cu = cu->per_cu;
12885
12886       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12887     }
12888   else if (attr_form_is_ref (attr))
12889     {
12890       struct dwarf2_cu *target_cu = cu;
12891       struct die_info *target_die;
12892
12893       target_die = follow_die_ref (die, attr, &target_cu);
12894       gdb_assert (target_cu->objfile == objfile);
12895       if (die_is_declaration (target_die, target_cu))
12896         {
12897           const char *target_physname;
12898
12899           /* Prefer the mangled name; otherwise compute the demangled one.  */
12900           target_physname = dw2_linkage_name (target_die, target_cu);
12901           if (target_physname == NULL)
12902             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12903           if (target_physname == NULL)
12904             complaint (&symfile_complaints,
12905                        _("DW_AT_call_target target DIE has invalid "
12906                          "physname, for referencing DIE 0x%x [in module %s]"),
12907                        to_underlying (die->sect_off), objfile_name (objfile));
12908           else
12909             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12910         }
12911       else
12912         {
12913           CORE_ADDR lowpc;
12914
12915           /* DW_AT_entry_pc should be preferred.  */
12916           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12917               <= PC_BOUNDS_INVALID)
12918             complaint (&symfile_complaints,
12919                        _("DW_AT_call_target target DIE has invalid "
12920                          "low pc, for referencing DIE 0x%x [in module %s]"),
12921                        to_underlying (die->sect_off), objfile_name (objfile));
12922           else
12923             {
12924               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12925               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12926             }
12927         }
12928     }
12929   else
12930     complaint (&symfile_complaints,
12931                _("DW_TAG_call_site DW_AT_call_target is neither "
12932                  "block nor reference, for DIE 0x%x [in module %s]"),
12933                to_underlying (die->sect_off), objfile_name (objfile));
12934
12935   call_site->per_cu = cu->per_cu;
12936
12937   for (child_die = die->child;
12938        child_die && child_die->tag;
12939        child_die = sibling_die (child_die))
12940     {
12941       struct call_site_parameter *parameter;
12942       struct attribute *loc, *origin;
12943
12944       if (child_die->tag != DW_TAG_call_site_parameter
12945           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12946         {
12947           /* Already printed the complaint above.  */
12948           continue;
12949         }
12950
12951       gdb_assert (call_site->parameter_count < nparams);
12952       parameter = &call_site->parameter[call_site->parameter_count];
12953
12954       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12955          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12956          register is contained in DW_AT_call_value.  */
12957
12958       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12959       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12960       if (origin == NULL)
12961         {
12962           /* This was a pre-DWARF-5 GNU extension alias
12963              for DW_AT_call_parameter.  */
12964           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12965         }
12966       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12967         {
12968           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12969
12970           sect_offset sect_off
12971             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12972           if (!offset_in_cu_p (&cu->header, sect_off))
12973             {
12974               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12975                  binding can be done only inside one CU.  Such referenced DIE
12976                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12977               complaint (&symfile_complaints,
12978                          _("DW_AT_call_parameter offset is not in CU for "
12979                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12980                          to_underlying (child_die->sect_off),
12981                          objfile_name (objfile));
12982               continue;
12983             }
12984           parameter->u.param_cu_off
12985             = (cu_offset) (sect_off - cu->header.sect_off);
12986         }
12987       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12988         {
12989           complaint (&symfile_complaints,
12990                      _("No DW_FORM_block* DW_AT_location for "
12991                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12992                      to_underlying (child_die->sect_off), objfile_name (objfile));
12993           continue;
12994         }
12995       else
12996         {
12997           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12998             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12999           if (parameter->u.dwarf_reg != -1)
13000             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13001           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
13002                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
13003                                              &parameter->u.fb_offset))
13004             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13005           else
13006             {
13007               complaint (&symfile_complaints,
13008                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
13009                            "for DW_FORM_block* DW_AT_location is supported for "
13010                            "DW_TAG_call_site child DIE 0x%x "
13011                            "[in module %s]"),
13012                          to_underlying (child_die->sect_off),
13013                          objfile_name (objfile));
13014               continue;
13015             }
13016         }
13017
13018       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13019       if (attr == NULL)
13020         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13021       if (!attr_form_is_block (attr))
13022         {
13023           complaint (&symfile_complaints,
13024                      _("No DW_FORM_block* DW_AT_call_value for "
13025                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13026                      to_underlying (child_die->sect_off),
13027                      objfile_name (objfile));
13028           continue;
13029         }
13030       parameter->value = DW_BLOCK (attr)->data;
13031       parameter->value_size = DW_BLOCK (attr)->size;
13032
13033       /* Parameters are not pre-cleared by memset above.  */
13034       parameter->data_value = NULL;
13035       parameter->data_value_size = 0;
13036       call_site->parameter_count++;
13037
13038       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13039       if (attr == NULL)
13040         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13041       if (attr)
13042         {
13043           if (!attr_form_is_block (attr))
13044             complaint (&symfile_complaints,
13045                        _("No DW_FORM_block* DW_AT_call_data_value for "
13046                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13047                        to_underlying (child_die->sect_off),
13048                        objfile_name (objfile));
13049           else
13050             {
13051               parameter->data_value = DW_BLOCK (attr)->data;
13052               parameter->data_value_size = DW_BLOCK (attr)->size;
13053             }
13054         }
13055     }
13056 }
13057
13058 /* Helper function for read_variable.  If DIE represents a virtual
13059    table, then return the type of the concrete object that is
13060    associated with the virtual table.  Otherwise, return NULL.  */
13061
13062 static struct type *
13063 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13064 {
13065   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13066   if (attr == NULL)
13067     return NULL;
13068
13069   /* Find the type DIE.  */
13070   struct die_info *type_die = NULL;
13071   struct dwarf2_cu *type_cu = cu;
13072
13073   if (attr_form_is_ref (attr))
13074     type_die = follow_die_ref (die, attr, &type_cu);
13075   if (type_die == NULL)
13076     return NULL;
13077
13078   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13079     return NULL;
13080   return die_containing_type (type_die, type_cu);
13081 }
13082
13083 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13084
13085 static void
13086 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13087 {
13088   struct rust_vtable_symbol *storage = NULL;
13089
13090   if (cu->language == language_rust)
13091     {
13092       struct type *containing_type = rust_containing_type (die, cu);
13093
13094       if (containing_type != NULL)
13095         {
13096           struct objfile *objfile = cu->objfile;
13097
13098           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
13099                                     struct rust_vtable_symbol);
13100           initialize_objfile_symbol (storage);
13101           storage->concrete_type = containing_type;
13102           storage->subclass = SYMBOL_RUST_VTABLE;
13103         }
13104     }
13105
13106   new_symbol_full (die, NULL, cu, storage);
13107 }
13108
13109 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13110    reading .debug_rnglists.
13111    Callback's type should be:
13112     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13113    Return true if the attributes are present and valid, otherwise,
13114    return false.  */
13115
13116 template <typename Callback>
13117 static bool
13118 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13119                          Callback &&callback)
13120 {
13121   struct objfile *objfile = cu->objfile;
13122   bfd *obfd = objfile->obfd;
13123   /* Base address selection entry.  */
13124   CORE_ADDR base;
13125   int found_base;
13126   const gdb_byte *buffer;
13127   CORE_ADDR baseaddr;
13128   bool overflow = false;
13129
13130   found_base = cu->base_known;
13131   base = cu->base_address;
13132
13133   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
13134   if (offset >= dwarf2_per_objfile->rnglists.size)
13135     {
13136       complaint (&symfile_complaints,
13137                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13138                  offset);
13139       return false;
13140     }
13141   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13142
13143   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13144
13145   while (1)
13146     {
13147       /* Initialize it due to a false compiler warning.  */
13148       CORE_ADDR range_beginning = 0, range_end = 0;
13149       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13150                                  + dwarf2_per_objfile->rnglists.size);
13151       unsigned int bytes_read;
13152
13153       if (buffer == buf_end)
13154         {
13155           overflow = true;
13156           break;
13157         }
13158       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13159       switch (rlet)
13160         {
13161         case DW_RLE_end_of_list:
13162           break;
13163         case DW_RLE_base_address:
13164           if (buffer + cu->header.addr_size > buf_end)
13165             {
13166               overflow = true;
13167               break;
13168             }
13169           base = read_address (obfd, buffer, cu, &bytes_read);
13170           found_base = 1;
13171           buffer += bytes_read;
13172           break;
13173         case DW_RLE_start_length:
13174           if (buffer + cu->header.addr_size > buf_end)
13175             {
13176               overflow = true;
13177               break;
13178             }
13179           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13180           buffer += bytes_read;
13181           range_end = (range_beginning
13182                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13183           buffer += bytes_read;
13184           if (buffer > buf_end)
13185             {
13186               overflow = true;
13187               break;
13188             }
13189           break;
13190         case DW_RLE_offset_pair:
13191           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13192           buffer += bytes_read;
13193           if (buffer > buf_end)
13194             {
13195               overflow = true;
13196               break;
13197             }
13198           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13199           buffer += bytes_read;
13200           if (buffer > buf_end)
13201             {
13202               overflow = true;
13203               break;
13204             }
13205           break;
13206         case DW_RLE_start_end:
13207           if (buffer + 2 * cu->header.addr_size > buf_end)
13208             {
13209               overflow = true;
13210               break;
13211             }
13212           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13213           buffer += bytes_read;
13214           range_end = read_address (obfd, buffer, cu, &bytes_read);
13215           buffer += bytes_read;
13216           break;
13217         default:
13218           complaint (&symfile_complaints,
13219                      _("Invalid .debug_rnglists data (no base address)"));
13220           return false;
13221         }
13222       if (rlet == DW_RLE_end_of_list || overflow)
13223         break;
13224       if (rlet == DW_RLE_base_address)
13225         continue;
13226
13227       if (!found_base)
13228         {
13229           /* We have no valid base address for the ranges
13230              data.  */
13231           complaint (&symfile_complaints,
13232                      _("Invalid .debug_rnglists data (no base address)"));
13233           return false;
13234         }
13235
13236       if (range_beginning > range_end)
13237         {
13238           /* Inverted range entries are invalid.  */
13239           complaint (&symfile_complaints,
13240                      _("Invalid .debug_rnglists data (inverted range)"));
13241           return false;
13242         }
13243
13244       /* Empty range entries have no effect.  */
13245       if (range_beginning == range_end)
13246         continue;
13247
13248       range_beginning += base;
13249       range_end += base;
13250
13251       /* A not-uncommon case of bad debug info.
13252          Don't pollute the addrmap with bad data.  */
13253       if (range_beginning + baseaddr == 0
13254           && !dwarf2_per_objfile->has_section_at_zero)
13255         {
13256           complaint (&symfile_complaints,
13257                      _(".debug_rnglists entry has start address of zero"
13258                        " [in module %s]"), objfile_name (objfile));
13259           continue;
13260         }
13261
13262       callback (range_beginning, range_end);
13263     }
13264
13265   if (overflow)
13266     {
13267       complaint (&symfile_complaints,
13268                  _("Offset %d is not terminated "
13269                    "for DW_AT_ranges attribute"),
13270                  offset);
13271       return false;
13272     }
13273
13274   return true;
13275 }
13276
13277 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13278    Callback's type should be:
13279     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13280    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13281
13282 template <typename Callback>
13283 static int
13284 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
13285                        Callback &&callback)
13286 {
13287   struct objfile *objfile = cu->objfile;
13288   struct comp_unit_head *cu_header = &cu->header;
13289   bfd *obfd = objfile->obfd;
13290   unsigned int addr_size = cu_header->addr_size;
13291   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13292   /* Base address selection entry.  */
13293   CORE_ADDR base;
13294   int found_base;
13295   unsigned int dummy;
13296   const gdb_byte *buffer;
13297   CORE_ADDR baseaddr;
13298
13299   if (cu_header->version >= 5)
13300     return dwarf2_rnglists_process (offset, cu, callback);
13301
13302   found_base = cu->base_known;
13303   base = cu->base_address;
13304
13305   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
13306   if (offset >= dwarf2_per_objfile->ranges.size)
13307     {
13308       complaint (&symfile_complaints,
13309                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13310                  offset);
13311       return 0;
13312     }
13313   buffer = dwarf2_per_objfile->ranges.buffer + offset;
13314
13315   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13316
13317   while (1)
13318     {
13319       CORE_ADDR range_beginning, range_end;
13320
13321       range_beginning = read_address (obfd, buffer, cu, &dummy);
13322       buffer += addr_size;
13323       range_end = read_address (obfd, buffer, cu, &dummy);
13324       buffer += addr_size;
13325       offset += 2 * addr_size;
13326
13327       /* An end of list marker is a pair of zero addresses.  */
13328       if (range_beginning == 0 && range_end == 0)
13329         /* Found the end of list entry.  */
13330         break;
13331
13332       /* Each base address selection entry is a pair of 2 values.
13333          The first is the largest possible address, the second is
13334          the base address.  Check for a base address here.  */
13335       if ((range_beginning & mask) == mask)
13336         {
13337           /* If we found the largest possible address, then we already
13338              have the base address in range_end.  */
13339           base = range_end;
13340           found_base = 1;
13341           continue;
13342         }
13343
13344       if (!found_base)
13345         {
13346           /* We have no valid base address for the ranges
13347              data.  */
13348           complaint (&symfile_complaints,
13349                      _("Invalid .debug_ranges data (no base address)"));
13350           return 0;
13351         }
13352
13353       if (range_beginning > range_end)
13354         {
13355           /* Inverted range entries are invalid.  */
13356           complaint (&symfile_complaints,
13357                      _("Invalid .debug_ranges data (inverted range)"));
13358           return 0;
13359         }
13360
13361       /* Empty range entries have no effect.  */
13362       if (range_beginning == range_end)
13363         continue;
13364
13365       range_beginning += base;
13366       range_end += base;
13367
13368       /* A not-uncommon case of bad debug info.
13369          Don't pollute the addrmap with bad data.  */
13370       if (range_beginning + baseaddr == 0
13371           && !dwarf2_per_objfile->has_section_at_zero)
13372         {
13373           complaint (&symfile_complaints,
13374                      _(".debug_ranges entry has start address of zero"
13375                        " [in module %s]"), objfile_name (objfile));
13376           continue;
13377         }
13378
13379       callback (range_beginning, range_end);
13380     }
13381
13382   return 1;
13383 }
13384
13385 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13386    Return 1 if the attributes are present and valid, otherwise, return 0.
13387    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
13388
13389 static int
13390 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13391                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13392                     struct partial_symtab *ranges_pst)
13393 {
13394   struct objfile *objfile = cu->objfile;
13395   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13396   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
13397                                        SECT_OFF_TEXT (objfile));
13398   int low_set = 0;
13399   CORE_ADDR low = 0;
13400   CORE_ADDR high = 0;
13401   int retval;
13402
13403   retval = dwarf2_ranges_process (offset, cu,
13404     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13405     {
13406       if (ranges_pst != NULL)
13407         {
13408           CORE_ADDR lowpc;
13409           CORE_ADDR highpc;
13410
13411           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13412                                               range_beginning + baseaddr);
13413           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13414                                                range_end + baseaddr);
13415           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
13416                              ranges_pst);
13417         }
13418
13419       /* FIXME: This is recording everything as a low-high
13420          segment of consecutive addresses.  We should have a
13421          data structure for discontiguous block ranges
13422          instead.  */
13423       if (! low_set)
13424         {
13425           low = range_beginning;
13426           high = range_end;
13427           low_set = 1;
13428         }
13429       else
13430         {
13431           if (range_beginning < low)
13432             low = range_beginning;
13433           if (range_end > high)
13434             high = range_end;
13435         }
13436     });
13437   if (!retval)
13438     return 0;
13439
13440   if (! low_set)
13441     /* If the first entry is an end-of-list marker, the range
13442        describes an empty scope, i.e. no instructions.  */
13443     return 0;
13444
13445   if (low_return)
13446     *low_return = low;
13447   if (high_return)
13448     *high_return = high;
13449   return 1;
13450 }
13451
13452 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13453    definition for the return value.  *LOWPC and *HIGHPC are set iff
13454    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13455
13456 static enum pc_bounds_kind
13457 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13458                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13459                       struct partial_symtab *pst)
13460 {
13461   struct attribute *attr;
13462   struct attribute *attr_high;
13463   CORE_ADDR low = 0;
13464   CORE_ADDR high = 0;
13465   enum pc_bounds_kind ret;
13466
13467   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13468   if (attr_high)
13469     {
13470       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13471       if (attr)
13472         {
13473           low = attr_value_as_address (attr);
13474           high = attr_value_as_address (attr_high);
13475           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13476             high += low;
13477         }
13478       else
13479         /* Found high w/o low attribute.  */
13480         return PC_BOUNDS_INVALID;
13481
13482       /* Found consecutive range of addresses.  */
13483       ret = PC_BOUNDS_HIGH_LOW;
13484     }
13485   else
13486     {
13487       attr = dwarf2_attr (die, DW_AT_ranges, cu);
13488       if (attr != NULL)
13489         {
13490           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13491              We take advantage of the fact that DW_AT_ranges does not appear
13492              in DW_TAG_compile_unit of DWO files.  */
13493           int need_ranges_base = die->tag != DW_TAG_compile_unit;
13494           unsigned int ranges_offset = (DW_UNSND (attr)
13495                                         + (need_ranges_base
13496                                            ? cu->ranges_base
13497                                            : 0));
13498
13499           /* Value of the DW_AT_ranges attribute is the offset in the
13500              .debug_ranges section.  */
13501           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
13502             return PC_BOUNDS_INVALID;
13503           /* Found discontinuous range of addresses.  */
13504           ret = PC_BOUNDS_RANGES;
13505         }
13506       else
13507         return PC_BOUNDS_NOT_PRESENT;
13508     }
13509
13510   /* read_partial_die has also the strict LOW < HIGH requirement.  */
13511   if (high <= low)
13512     return PC_BOUNDS_INVALID;
13513
13514   /* When using the GNU linker, .gnu.linkonce. sections are used to
13515      eliminate duplicate copies of functions and vtables and such.
13516      The linker will arbitrarily choose one and discard the others.
13517      The AT_*_pc values for such functions refer to local labels in
13518      these sections.  If the section from that file was discarded, the
13519      labels are not in the output, so the relocs get a value of 0.
13520      If this is a discarded function, mark the pc bounds as invalid,
13521      so that GDB will ignore it.  */
13522   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
13523     return PC_BOUNDS_INVALID;
13524
13525   *lowpc = low;
13526   if (highpc)
13527     *highpc = high;
13528   return ret;
13529 }
13530
13531 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
13532    its low and high PC addresses.  Do nothing if these addresses could not
13533    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
13534    and HIGHPC to the high address if greater than HIGHPC.  */
13535
13536 static void
13537 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
13538                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
13539                                  struct dwarf2_cu *cu)
13540 {
13541   CORE_ADDR low, high;
13542   struct die_info *child = die->child;
13543
13544   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
13545     {
13546       *lowpc = std::min (*lowpc, low);
13547       *highpc = std::max (*highpc, high);
13548     }
13549
13550   /* If the language does not allow nested subprograms (either inside
13551      subprograms or lexical blocks), we're done.  */
13552   if (cu->language != language_ada)
13553     return;
13554
13555   /* Check all the children of the given DIE.  If it contains nested
13556      subprograms, then check their pc bounds.  Likewise, we need to
13557      check lexical blocks as well, as they may also contain subprogram
13558      definitions.  */
13559   while (child && child->tag)
13560     {
13561       if (child->tag == DW_TAG_subprogram
13562           || child->tag == DW_TAG_lexical_block)
13563         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
13564       child = sibling_die (child);
13565     }
13566 }
13567
13568 /* Get the low and high pc's represented by the scope DIE, and store
13569    them in *LOWPC and *HIGHPC.  If the correct values can't be
13570    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
13571
13572 static void
13573 get_scope_pc_bounds (struct die_info *die,
13574                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
13575                      struct dwarf2_cu *cu)
13576 {
13577   CORE_ADDR best_low = (CORE_ADDR) -1;
13578   CORE_ADDR best_high = (CORE_ADDR) 0;
13579   CORE_ADDR current_low, current_high;
13580
13581   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
13582       >= PC_BOUNDS_RANGES)
13583     {
13584       best_low = current_low;
13585       best_high = current_high;
13586     }
13587   else
13588     {
13589       struct die_info *child = die->child;
13590
13591       while (child && child->tag)
13592         {
13593           switch (child->tag) {
13594           case DW_TAG_subprogram:
13595             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13596             break;
13597           case DW_TAG_namespace:
13598           case DW_TAG_module:
13599             /* FIXME: carlton/2004-01-16: Should we do this for
13600                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13601                that current GCC's always emit the DIEs corresponding
13602                to definitions of methods of classes as children of a
13603                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13604                the DIEs giving the declarations, which could be
13605                anywhere).  But I don't see any reason why the
13606                standards says that they have to be there.  */
13607             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13608
13609             if (current_low != ((CORE_ADDR) -1))
13610               {
13611                 best_low = std::min (best_low, current_low);
13612                 best_high = std::max (best_high, current_high);
13613               }
13614             break;
13615           default:
13616             /* Ignore.  */
13617             break;
13618           }
13619
13620           child = sibling_die (child);
13621         }
13622     }
13623
13624   *lowpc = best_low;
13625   *highpc = best_high;
13626 }
13627
13628 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13629    in DIE.  */
13630
13631 static void
13632 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13633                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13634 {
13635   struct objfile *objfile = cu->objfile;
13636   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13637   struct attribute *attr;
13638   struct attribute *attr_high;
13639
13640   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13641   if (attr_high)
13642     {
13643       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13644       if (attr)
13645         {
13646           CORE_ADDR low = attr_value_as_address (attr);
13647           CORE_ADDR high = attr_value_as_address (attr_high);
13648
13649           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13650             high += low;
13651
13652           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13653           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13654           record_block_range (block, low, high - 1);
13655         }
13656     }
13657
13658   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13659   if (attr)
13660     {
13661       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13662          We take advantage of the fact that DW_AT_ranges does not appear
13663          in DW_TAG_compile_unit of DWO files.  */
13664       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13665
13666       /* The value of the DW_AT_ranges attribute is the offset of the
13667          address range list in the .debug_ranges section.  */
13668       unsigned long offset = (DW_UNSND (attr)
13669                               + (need_ranges_base ? cu->ranges_base : 0));
13670       const gdb_byte *buffer;
13671
13672       /* For some target architectures, but not others, the
13673          read_address function sign-extends the addresses it returns.
13674          To recognize base address selection entries, we need a
13675          mask.  */
13676       unsigned int addr_size = cu->header.addr_size;
13677       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13678
13679       /* The base address, to which the next pair is relative.  Note
13680          that this 'base' is a DWARF concept: most entries in a range
13681          list are relative, to reduce the number of relocs against the
13682          debugging information.  This is separate from this function's
13683          'baseaddr' argument, which GDB uses to relocate debugging
13684          information from a shared library based on the address at
13685          which the library was loaded.  */
13686       CORE_ADDR base = cu->base_address;
13687       int base_known = cu->base_known;
13688
13689       dwarf2_ranges_process (offset, cu,
13690         [&] (CORE_ADDR start, CORE_ADDR end)
13691         {
13692           start += baseaddr;
13693           end += baseaddr;
13694           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13695           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13696           record_block_range (block, start, end - 1);
13697         });
13698     }
13699 }
13700
13701 /* Check whether the producer field indicates either of GCC < 4.6, or the
13702    Intel C/C++ compiler, and cache the result in CU.  */
13703
13704 static void
13705 check_producer (struct dwarf2_cu *cu)
13706 {
13707   int major, minor;
13708
13709   if (cu->producer == NULL)
13710     {
13711       /* For unknown compilers expect their behavior is DWARF version
13712          compliant.
13713
13714          GCC started to support .debug_types sections by -gdwarf-4 since
13715          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13716          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13717          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13718          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13719     }
13720   else if (producer_is_gcc (cu->producer, &major, &minor))
13721     {
13722       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13723       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13724     }
13725   else if (producer_is_icc (cu->producer, &major, &minor))
13726     cu->producer_is_icc_lt_14 = major < 14;
13727   else
13728     {
13729       /* For other non-GCC compilers, expect their behavior is DWARF version
13730          compliant.  */
13731     }
13732
13733   cu->checked_producer = 1;
13734 }
13735
13736 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13737    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13738    during 4.6.0 experimental.  */
13739
13740 static int
13741 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13742 {
13743   if (!cu->checked_producer)
13744     check_producer (cu);
13745
13746   return cu->producer_is_gxx_lt_4_6;
13747 }
13748
13749 /* Return the default accessibility type if it is not overriden by
13750    DW_AT_accessibility.  */
13751
13752 static enum dwarf_access_attribute
13753 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13754 {
13755   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13756     {
13757       /* The default DWARF 2 accessibility for members is public, the default
13758          accessibility for inheritance is private.  */
13759
13760       if (die->tag != DW_TAG_inheritance)
13761         return DW_ACCESS_public;
13762       else
13763         return DW_ACCESS_private;
13764     }
13765   else
13766     {
13767       /* DWARF 3+ defines the default accessibility a different way.  The same
13768          rules apply now for DW_TAG_inheritance as for the members and it only
13769          depends on the container kind.  */
13770
13771       if (die->parent->tag == DW_TAG_class_type)
13772         return DW_ACCESS_private;
13773       else
13774         return DW_ACCESS_public;
13775     }
13776 }
13777
13778 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13779    offset.  If the attribute was not found return 0, otherwise return
13780    1.  If it was found but could not properly be handled, set *OFFSET
13781    to 0.  */
13782
13783 static int
13784 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13785                              LONGEST *offset)
13786 {
13787   struct attribute *attr;
13788
13789   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13790   if (attr != NULL)
13791     {
13792       *offset = 0;
13793
13794       /* Note that we do not check for a section offset first here.
13795          This is because DW_AT_data_member_location is new in DWARF 4,
13796          so if we see it, we can assume that a constant form is really
13797          a constant and not a section offset.  */
13798       if (attr_form_is_constant (attr))
13799         *offset = dwarf2_get_attr_constant_value (attr, 0);
13800       else if (attr_form_is_section_offset (attr))
13801         dwarf2_complex_location_expr_complaint ();
13802       else if (attr_form_is_block (attr))
13803         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13804       else
13805         dwarf2_complex_location_expr_complaint ();
13806
13807       return 1;
13808     }
13809
13810   return 0;
13811 }
13812
13813 /* Add an aggregate field to the field list.  */
13814
13815 static void
13816 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13817                   struct dwarf2_cu *cu)
13818 {
13819   struct objfile *objfile = cu->objfile;
13820   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13821   struct nextfield *new_field;
13822   struct attribute *attr;
13823   struct field *fp;
13824   const char *fieldname = "";
13825
13826   /* Allocate a new field list entry and link it in.  */
13827   new_field = XNEW (struct nextfield);
13828   make_cleanup (xfree, new_field);
13829   memset (new_field, 0, sizeof (struct nextfield));
13830
13831   if (die->tag == DW_TAG_inheritance)
13832     {
13833       new_field->next = fip->baseclasses;
13834       fip->baseclasses = new_field;
13835     }
13836   else
13837     {
13838       new_field->next = fip->fields;
13839       fip->fields = new_field;
13840     }
13841   fip->nfields++;
13842
13843   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13844   if (attr)
13845     new_field->accessibility = DW_UNSND (attr);
13846   else
13847     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13848   if (new_field->accessibility != DW_ACCESS_public)
13849     fip->non_public_fields = 1;
13850
13851   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13852   if (attr)
13853     new_field->virtuality = DW_UNSND (attr);
13854   else
13855     new_field->virtuality = DW_VIRTUALITY_none;
13856
13857   fp = &new_field->field;
13858
13859   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13860     {
13861       LONGEST offset;
13862
13863       /* Data member other than a C++ static data member.  */
13864
13865       /* Get type of field.  */
13866       fp->type = die_type (die, cu);
13867
13868       SET_FIELD_BITPOS (*fp, 0);
13869
13870       /* Get bit size of field (zero if none).  */
13871       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13872       if (attr)
13873         {
13874           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13875         }
13876       else
13877         {
13878           FIELD_BITSIZE (*fp) = 0;
13879         }
13880
13881       /* Get bit offset of field.  */
13882       if (handle_data_member_location (die, cu, &offset))
13883         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13884       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13885       if (attr)
13886         {
13887           if (gdbarch_bits_big_endian (gdbarch))
13888             {
13889               /* For big endian bits, the DW_AT_bit_offset gives the
13890                  additional bit offset from the MSB of the containing
13891                  anonymous object to the MSB of the field.  We don't
13892                  have to do anything special since we don't need to
13893                  know the size of the anonymous object.  */
13894               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13895             }
13896           else
13897             {
13898               /* For little endian bits, compute the bit offset to the
13899                  MSB of the anonymous object, subtract off the number of
13900                  bits from the MSB of the field to the MSB of the
13901                  object, and then subtract off the number of bits of
13902                  the field itself.  The result is the bit offset of
13903                  the LSB of the field.  */
13904               int anonymous_size;
13905               int bit_offset = DW_UNSND (attr);
13906
13907               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13908               if (attr)
13909                 {
13910                   /* The size of the anonymous object containing
13911                      the bit field is explicit, so use the
13912                      indicated size (in bytes).  */
13913                   anonymous_size = DW_UNSND (attr);
13914                 }
13915               else
13916                 {
13917                   /* The size of the anonymous object containing
13918                      the bit field must be inferred from the type
13919                      attribute of the data member containing the
13920                      bit field.  */
13921                   anonymous_size = TYPE_LENGTH (fp->type);
13922                 }
13923               SET_FIELD_BITPOS (*fp,
13924                                 (FIELD_BITPOS (*fp)
13925                                  + anonymous_size * bits_per_byte
13926                                  - bit_offset - FIELD_BITSIZE (*fp)));
13927             }
13928         }
13929       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13930       if (attr != NULL)
13931         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13932                                 + dwarf2_get_attr_constant_value (attr, 0)));
13933
13934       /* Get name of field.  */
13935       fieldname = dwarf2_name (die, cu);
13936       if (fieldname == NULL)
13937         fieldname = "";
13938
13939       /* The name is already allocated along with this objfile, so we don't
13940          need to duplicate it for the type.  */
13941       fp->name = fieldname;
13942
13943       /* Change accessibility for artificial fields (e.g. virtual table
13944          pointer or virtual base class pointer) to private.  */
13945       if (dwarf2_attr (die, DW_AT_artificial, cu))
13946         {
13947           FIELD_ARTIFICIAL (*fp) = 1;
13948           new_field->accessibility = DW_ACCESS_private;
13949           fip->non_public_fields = 1;
13950         }
13951     }
13952   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13953     {
13954       /* C++ static member.  */
13955
13956       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13957          is a declaration, but all versions of G++ as of this writing
13958          (so through at least 3.2.1) incorrectly generate
13959          DW_TAG_variable tags.  */
13960
13961       const char *physname;
13962
13963       /* Get name of field.  */
13964       fieldname = dwarf2_name (die, cu);
13965       if (fieldname == NULL)
13966         return;
13967
13968       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13969       if (attr
13970           /* Only create a symbol if this is an external value.
13971              new_symbol checks this and puts the value in the global symbol
13972              table, which we want.  If it is not external, new_symbol
13973              will try to put the value in cu->list_in_scope which is wrong.  */
13974           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13975         {
13976           /* A static const member, not much different than an enum as far as
13977              we're concerned, except that we can support more types.  */
13978           new_symbol (die, NULL, cu);
13979         }
13980
13981       /* Get physical name.  */
13982       physname = dwarf2_physname (fieldname, die, cu);
13983
13984       /* The name is already allocated along with this objfile, so we don't
13985          need to duplicate it for the type.  */
13986       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13987       FIELD_TYPE (*fp) = die_type (die, cu);
13988       FIELD_NAME (*fp) = fieldname;
13989     }
13990   else if (die->tag == DW_TAG_inheritance)
13991     {
13992       LONGEST offset;
13993
13994       /* C++ base class field.  */
13995       if (handle_data_member_location (die, cu, &offset))
13996         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13997       FIELD_BITSIZE (*fp) = 0;
13998       FIELD_TYPE (*fp) = die_type (die, cu);
13999       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
14000       fip->nbaseclasses++;
14001     }
14002 }
14003
14004 /* Can the type given by DIE define another type?  */
14005
14006 static bool
14007 type_can_define_types (const struct die_info *die)
14008 {
14009   switch (die->tag)
14010     {
14011     case DW_TAG_typedef:
14012     case DW_TAG_class_type:
14013     case DW_TAG_structure_type:
14014     case DW_TAG_union_type:
14015     case DW_TAG_enumeration_type:
14016       return true;
14017
14018     default:
14019       return false;
14020     }
14021 }
14022
14023 /* Add a type definition defined in the scope of the FIP's class.  */
14024
14025 static void
14026 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14027                       struct dwarf2_cu *cu)
14028 {
14029   struct decl_field_list *new_field;
14030   struct decl_field *fp;
14031
14032   /* Allocate a new field list entry and link it in.  */
14033   new_field = XCNEW (struct decl_field_list);
14034   make_cleanup (xfree, new_field);
14035
14036   gdb_assert (type_can_define_types (die));
14037
14038   fp = &new_field->field;
14039
14040   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14041   fp->name = dwarf2_name (die, cu);
14042   fp->type = read_type_die (die, cu);
14043
14044   /* Save accessibility.  */
14045   enum dwarf_access_attribute accessibility;
14046   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14047   if (attr != NULL)
14048     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14049   else
14050     accessibility = dwarf2_default_access_attribute (die, cu);
14051   switch (accessibility)
14052     {
14053     case DW_ACCESS_public:
14054       /* The assumed value if neither private nor protected.  */
14055       break;
14056     case DW_ACCESS_private:
14057       fp->is_private = 1;
14058       break;
14059     case DW_ACCESS_protected:
14060       fp->is_protected = 1;
14061       break;
14062     default:
14063       complaint (&symfile_complaints,
14064                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14065     }
14066
14067   if (die->tag == DW_TAG_typedef)
14068     {
14069       new_field->next = fip->typedef_field_list;
14070       fip->typedef_field_list = new_field;
14071       fip->typedef_field_list_count++;
14072     }
14073   else
14074     {
14075       new_field->next = fip->nested_types_list;
14076       fip->nested_types_list = new_field;
14077       fip->nested_types_list_count++;
14078     }
14079 }
14080
14081 /* Create the vector of fields, and attach it to the type.  */
14082
14083 static void
14084 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14085                               struct dwarf2_cu *cu)
14086 {
14087   int nfields = fip->nfields;
14088
14089   /* Record the field count, allocate space for the array of fields,
14090      and create blank accessibility bitfields if necessary.  */
14091   TYPE_NFIELDS (type) = nfields;
14092   TYPE_FIELDS (type) = (struct field *)
14093     TYPE_ALLOC (type, sizeof (struct field) * nfields);
14094   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
14095
14096   if (fip->non_public_fields && cu->language != language_ada)
14097     {
14098       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14099
14100       TYPE_FIELD_PRIVATE_BITS (type) =
14101         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14102       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14103
14104       TYPE_FIELD_PROTECTED_BITS (type) =
14105         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14106       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14107
14108       TYPE_FIELD_IGNORE_BITS (type) =
14109         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14110       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14111     }
14112
14113   /* If the type has baseclasses, allocate and clear a bit vector for
14114      TYPE_FIELD_VIRTUAL_BITS.  */
14115   if (fip->nbaseclasses && cu->language != language_ada)
14116     {
14117       int num_bytes = B_BYTES (fip->nbaseclasses);
14118       unsigned char *pointer;
14119
14120       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14121       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14122       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14123       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
14124       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
14125     }
14126
14127   /* Copy the saved-up fields into the field vector.  Start from the head of
14128      the list, adding to the tail of the field array, so that they end up in
14129      the same order in the array in which they were added to the list.  */
14130   while (nfields-- > 0)
14131     {
14132       struct nextfield *fieldp;
14133
14134       if (fip->fields)
14135         {
14136           fieldp = fip->fields;
14137           fip->fields = fieldp->next;
14138         }
14139       else
14140         {
14141           fieldp = fip->baseclasses;
14142           fip->baseclasses = fieldp->next;
14143         }
14144
14145       TYPE_FIELD (type, nfields) = fieldp->field;
14146       switch (fieldp->accessibility)
14147         {
14148         case DW_ACCESS_private:
14149           if (cu->language != language_ada)
14150             SET_TYPE_FIELD_PRIVATE (type, nfields);
14151           break;
14152
14153         case DW_ACCESS_protected:
14154           if (cu->language != language_ada)
14155             SET_TYPE_FIELD_PROTECTED (type, nfields);
14156           break;
14157
14158         case DW_ACCESS_public:
14159           break;
14160
14161         default:
14162           /* Unknown accessibility.  Complain and treat it as public.  */
14163           {
14164             complaint (&symfile_complaints, _("unsupported accessibility %d"),
14165                        fieldp->accessibility);
14166           }
14167           break;
14168         }
14169       if (nfields < fip->nbaseclasses)
14170         {
14171           switch (fieldp->virtuality)
14172             {
14173             case DW_VIRTUALITY_virtual:
14174             case DW_VIRTUALITY_pure_virtual:
14175               if (cu->language == language_ada)
14176                 error (_("unexpected virtuality in component of Ada type"));
14177               SET_TYPE_FIELD_VIRTUAL (type, nfields);
14178               break;
14179             }
14180         }
14181     }
14182 }
14183
14184 /* Return true if this member function is a constructor, false
14185    otherwise.  */
14186
14187 static int
14188 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14189 {
14190   const char *fieldname;
14191   const char *type_name;
14192   int len;
14193
14194   if (die->parent == NULL)
14195     return 0;
14196
14197   if (die->parent->tag != DW_TAG_structure_type
14198       && die->parent->tag != DW_TAG_union_type
14199       && die->parent->tag != DW_TAG_class_type)
14200     return 0;
14201
14202   fieldname = dwarf2_name (die, cu);
14203   type_name = dwarf2_name (die->parent, cu);
14204   if (fieldname == NULL || type_name == NULL)
14205     return 0;
14206
14207   len = strlen (fieldname);
14208   return (strncmp (fieldname, type_name, len) == 0
14209           && (type_name[len] == '\0' || type_name[len] == '<'));
14210 }
14211
14212 /* Add a member function to the proper fieldlist.  */
14213
14214 static void
14215 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14216                       struct type *type, struct dwarf2_cu *cu)
14217 {
14218   struct objfile *objfile = cu->objfile;
14219   struct attribute *attr;
14220   struct fnfieldlist *flp;
14221   int i;
14222   struct fn_field *fnp;
14223   const char *fieldname;
14224   struct nextfnfield *new_fnfield;
14225   struct type *this_type;
14226   enum dwarf_access_attribute accessibility;
14227
14228   if (cu->language == language_ada)
14229     error (_("unexpected member function in Ada type"));
14230
14231   /* Get name of member function.  */
14232   fieldname = dwarf2_name (die, cu);
14233   if (fieldname == NULL)
14234     return;
14235
14236   /* Look up member function name in fieldlist.  */
14237   for (i = 0; i < fip->nfnfields; i++)
14238     {
14239       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
14240         break;
14241     }
14242
14243   /* Create new list element if necessary.  */
14244   if (i < fip->nfnfields)
14245     flp = &fip->fnfieldlists[i];
14246   else
14247     {
14248       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
14249         {
14250           fip->fnfieldlists = (struct fnfieldlist *)
14251             xrealloc (fip->fnfieldlists,
14252                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
14253                       * sizeof (struct fnfieldlist));
14254           if (fip->nfnfields == 0)
14255             make_cleanup (free_current_contents, &fip->fnfieldlists);
14256         }
14257       flp = &fip->fnfieldlists[fip->nfnfields];
14258       flp->name = fieldname;
14259       flp->length = 0;
14260       flp->head = NULL;
14261       i = fip->nfnfields++;
14262     }
14263
14264   /* Create a new member function field and chain it to the field list
14265      entry.  */
14266   new_fnfield = XNEW (struct nextfnfield);
14267   make_cleanup (xfree, new_fnfield);
14268   memset (new_fnfield, 0, sizeof (struct nextfnfield));
14269   new_fnfield->next = flp->head;
14270   flp->head = new_fnfield;
14271   flp->length++;
14272
14273   /* Fill in the member function field info.  */
14274   fnp = &new_fnfield->fnfield;
14275
14276   /* Delay processing of the physname until later.  */
14277   if (cu->language == language_cplus)
14278     {
14279       add_to_method_list (type, i, flp->length - 1, fieldname,
14280                           die, cu);
14281     }
14282   else
14283     {
14284       const char *physname = dwarf2_physname (fieldname, die, cu);
14285       fnp->physname = physname ? physname : "";
14286     }
14287
14288   fnp->type = alloc_type (objfile);
14289   this_type = read_type_die (die, cu);
14290   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
14291     {
14292       int nparams = TYPE_NFIELDS (this_type);
14293
14294       /* TYPE is the domain of this method, and THIS_TYPE is the type
14295            of the method itself (TYPE_CODE_METHOD).  */
14296       smash_to_method_type (fnp->type, type,
14297                             TYPE_TARGET_TYPE (this_type),
14298                             TYPE_FIELDS (this_type),
14299                             TYPE_NFIELDS (this_type),
14300                             TYPE_VARARGS (this_type));
14301
14302       /* Handle static member functions.
14303          Dwarf2 has no clean way to discern C++ static and non-static
14304          member functions.  G++ helps GDB by marking the first
14305          parameter for non-static member functions (which is the this
14306          pointer) as artificial.  We obtain this information from
14307          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
14308       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
14309         fnp->voffset = VOFFSET_STATIC;
14310     }
14311   else
14312     complaint (&symfile_complaints, _("member function type missing for '%s'"),
14313                dwarf2_full_name (fieldname, die, cu));
14314
14315   /* Get fcontext from DW_AT_containing_type if present.  */
14316   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14317     fnp->fcontext = die_containing_type (die, cu);
14318
14319   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
14320      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
14321
14322   /* Get accessibility.  */
14323   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14324   if (attr)
14325     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14326   else
14327     accessibility = dwarf2_default_access_attribute (die, cu);
14328   switch (accessibility)
14329     {
14330     case DW_ACCESS_private:
14331       fnp->is_private = 1;
14332       break;
14333     case DW_ACCESS_protected:
14334       fnp->is_protected = 1;
14335       break;
14336     }
14337
14338   /* Check for artificial methods.  */
14339   attr = dwarf2_attr (die, DW_AT_artificial, cu);
14340   if (attr && DW_UNSND (attr) != 0)
14341     fnp->is_artificial = 1;
14342
14343   fnp->is_constructor = dwarf2_is_constructor (die, cu);
14344
14345   /* Get index in virtual function table if it is a virtual member
14346      function.  For older versions of GCC, this is an offset in the
14347      appropriate virtual table, as specified by DW_AT_containing_type.
14348      For everyone else, it is an expression to be evaluated relative
14349      to the object address.  */
14350
14351   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
14352   if (attr)
14353     {
14354       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
14355         {
14356           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
14357             {
14358               /* Old-style GCC.  */
14359               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
14360             }
14361           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
14362                    || (DW_BLOCK (attr)->size > 1
14363                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
14364                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
14365             {
14366               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
14367               if ((fnp->voffset % cu->header.addr_size) != 0)
14368                 dwarf2_complex_location_expr_complaint ();
14369               else
14370                 fnp->voffset /= cu->header.addr_size;
14371               fnp->voffset += 2;
14372             }
14373           else
14374             dwarf2_complex_location_expr_complaint ();
14375
14376           if (!fnp->fcontext)
14377             {
14378               /* If there is no `this' field and no DW_AT_containing_type,
14379                  we cannot actually find a base class context for the
14380                  vtable!  */
14381               if (TYPE_NFIELDS (this_type) == 0
14382                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
14383                 {
14384                   complaint (&symfile_complaints,
14385                              _("cannot determine context for virtual member "
14386                                "function \"%s\" (offset %d)"),
14387                              fieldname, to_underlying (die->sect_off));
14388                 }
14389               else
14390                 {
14391                   fnp->fcontext
14392                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
14393                 }
14394             }
14395         }
14396       else if (attr_form_is_section_offset (attr))
14397         {
14398           dwarf2_complex_location_expr_complaint ();
14399         }
14400       else
14401         {
14402           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
14403                                                  fieldname);
14404         }
14405     }
14406   else
14407     {
14408       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14409       if (attr && DW_UNSND (attr))
14410         {
14411           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
14412           complaint (&symfile_complaints,
14413                      _("Member function \"%s\" (offset %d) is virtual "
14414                        "but the vtable offset is not specified"),
14415                      fieldname, to_underlying (die->sect_off));
14416           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14417           TYPE_CPLUS_DYNAMIC (type) = 1;
14418         }
14419     }
14420 }
14421
14422 /* Create the vector of member function fields, and attach it to the type.  */
14423
14424 static void
14425 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
14426                                  struct dwarf2_cu *cu)
14427 {
14428   struct fnfieldlist *flp;
14429   int i;
14430
14431   if (cu->language == language_ada)
14432     error (_("unexpected member functions in Ada type"));
14433
14434   ALLOCATE_CPLUS_STRUCT_TYPE (type);
14435   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
14436     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
14437
14438   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
14439     {
14440       struct nextfnfield *nfp = flp->head;
14441       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
14442       int k;
14443
14444       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
14445       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
14446       fn_flp->fn_fields = (struct fn_field *)
14447         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
14448       for (k = flp->length; (k--, nfp); nfp = nfp->next)
14449         fn_flp->fn_fields[k] = nfp->fnfield;
14450     }
14451
14452   TYPE_NFN_FIELDS (type) = fip->nfnfields;
14453 }
14454
14455 /* Returns non-zero if NAME is the name of a vtable member in CU's
14456    language, zero otherwise.  */
14457 static int
14458 is_vtable_name (const char *name, struct dwarf2_cu *cu)
14459 {
14460   static const char vptr[] = "_vptr";
14461
14462   /* Look for the C++ form of the vtable.  */
14463   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
14464     return 1;
14465
14466   return 0;
14467 }
14468
14469 /* GCC outputs unnamed structures that are really pointers to member
14470    functions, with the ABI-specified layout.  If TYPE describes
14471    such a structure, smash it into a member function type.
14472
14473    GCC shouldn't do this; it should just output pointer to member DIEs.
14474    This is GCC PR debug/28767.  */
14475
14476 static void
14477 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
14478 {
14479   struct type *pfn_type, *self_type, *new_type;
14480
14481   /* Check for a structure with no name and two children.  */
14482   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
14483     return;
14484
14485   /* Check for __pfn and __delta members.  */
14486   if (TYPE_FIELD_NAME (type, 0) == NULL
14487       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
14488       || TYPE_FIELD_NAME (type, 1) == NULL
14489       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
14490     return;
14491
14492   /* Find the type of the method.  */
14493   pfn_type = TYPE_FIELD_TYPE (type, 0);
14494   if (pfn_type == NULL
14495       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
14496       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
14497     return;
14498
14499   /* Look for the "this" argument.  */
14500   pfn_type = TYPE_TARGET_TYPE (pfn_type);
14501   if (TYPE_NFIELDS (pfn_type) == 0
14502       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
14503       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
14504     return;
14505
14506   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
14507   new_type = alloc_type (objfile);
14508   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
14509                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
14510                         TYPE_VARARGS (pfn_type));
14511   smash_to_methodptr_type (type, new_type);
14512 }
14513
14514
14515 /* Called when we find the DIE that starts a structure or union scope
14516    (definition) to create a type for the structure or union.  Fill in
14517    the type's name and general properties; the members will not be
14518    processed until process_structure_scope.  A symbol table entry for
14519    the type will also not be done until process_structure_scope (assuming
14520    the type has a name).
14521
14522    NOTE: we need to call these functions regardless of whether or not the
14523    DIE has a DW_AT_name attribute, since it might be an anonymous
14524    structure or union.  This gets the type entered into our set of
14525    user defined types.  */
14526
14527 static struct type *
14528 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
14529 {
14530   struct objfile *objfile = cu->objfile;
14531   struct type *type;
14532   struct attribute *attr;
14533   const char *name;
14534
14535   /* If the definition of this type lives in .debug_types, read that type.
14536      Don't follow DW_AT_specification though, that will take us back up
14537      the chain and we want to go down.  */
14538   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14539   if (attr)
14540     {
14541       type = get_DW_AT_signature_type (die, attr, cu);
14542
14543       /* The type's CU may not be the same as CU.
14544          Ensure TYPE is recorded with CU in die_type_hash.  */
14545       return set_die_type (die, type, cu);
14546     }
14547
14548   type = alloc_type (objfile);
14549   INIT_CPLUS_SPECIFIC (type);
14550
14551   name = dwarf2_name (die, cu);
14552   if (name != NULL)
14553     {
14554       if (cu->language == language_cplus
14555           || cu->language == language_d
14556           || cu->language == language_rust)
14557         {
14558           const char *full_name = dwarf2_full_name (name, die, cu);
14559
14560           /* dwarf2_full_name might have already finished building the DIE's
14561              type.  If so, there is no need to continue.  */
14562           if (get_die_type (die, cu) != NULL)
14563             return get_die_type (die, cu);
14564
14565           TYPE_TAG_NAME (type) = full_name;
14566           if (die->tag == DW_TAG_structure_type
14567               || die->tag == DW_TAG_class_type)
14568             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14569         }
14570       else
14571         {
14572           /* The name is already allocated along with this objfile, so
14573              we don't need to duplicate it for the type.  */
14574           TYPE_TAG_NAME (type) = name;
14575           if (die->tag == DW_TAG_class_type)
14576             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14577         }
14578     }
14579
14580   if (die->tag == DW_TAG_structure_type)
14581     {
14582       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14583     }
14584   else if (die->tag == DW_TAG_union_type)
14585     {
14586       TYPE_CODE (type) = TYPE_CODE_UNION;
14587     }
14588   else
14589     {
14590       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14591     }
14592
14593   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
14594     TYPE_DECLARED_CLASS (type) = 1;
14595
14596   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14597   if (attr)
14598     {
14599       if (attr_form_is_constant (attr))
14600         TYPE_LENGTH (type) = DW_UNSND (attr);
14601       else
14602         {
14603           /* For the moment, dynamic type sizes are not supported
14604              by GDB's struct type.  The actual size is determined
14605              on-demand when resolving the type of a given object,
14606              so set the type's length to zero for now.  Otherwise,
14607              we record an expression as the length, and that expression
14608              could lead to a very large value, which could eventually
14609              lead to us trying to allocate that much memory when creating
14610              a value of that type.  */
14611           TYPE_LENGTH (type) = 0;
14612         }
14613     }
14614   else
14615     {
14616       TYPE_LENGTH (type) = 0;
14617     }
14618
14619   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
14620     {
14621       /* ICC<14 does not output the required DW_AT_declaration on
14622          incomplete types, but gives them a size of zero.  */
14623       TYPE_STUB (type) = 1;
14624     }
14625   else
14626     TYPE_STUB_SUPPORTED (type) = 1;
14627
14628   if (die_is_declaration (die, cu))
14629     TYPE_STUB (type) = 1;
14630   else if (attr == NULL && die->child == NULL
14631            && producer_is_realview (cu->producer))
14632     /* RealView does not output the required DW_AT_declaration
14633        on incomplete types.  */
14634     TYPE_STUB (type) = 1;
14635
14636   /* We need to add the type field to the die immediately so we don't
14637      infinitely recurse when dealing with pointers to the structure
14638      type within the structure itself.  */
14639   set_die_type (die, type, cu);
14640
14641   /* set_die_type should be already done.  */
14642   set_descriptive_type (type, die, cu);
14643
14644   return type;
14645 }
14646
14647 /* Finish creating a structure or union type, including filling in
14648    its members and creating a symbol for it.  */
14649
14650 static void
14651 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14652 {
14653   struct objfile *objfile = cu->objfile;
14654   struct die_info *child_die;
14655   struct type *type;
14656
14657   type = get_die_type (die, cu);
14658   if (type == NULL)
14659     type = read_structure_type (die, cu);
14660
14661   if (die->child != NULL && ! die_is_declaration (die, cu))
14662     {
14663       struct field_info fi;
14664       std::vector<struct symbol *> template_args;
14665       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14666
14667       memset (&fi, 0, sizeof (struct field_info));
14668
14669       child_die = die->child;
14670
14671       while (child_die && child_die->tag)
14672         {
14673           if (child_die->tag == DW_TAG_member
14674               || child_die->tag == DW_TAG_variable)
14675             {
14676               /* NOTE: carlton/2002-11-05: A C++ static data member
14677                  should be a DW_TAG_member that is a declaration, but
14678                  all versions of G++ as of this writing (so through at
14679                  least 3.2.1) incorrectly generate DW_TAG_variable
14680                  tags for them instead.  */
14681               dwarf2_add_field (&fi, child_die, cu);
14682             }
14683           else if (child_die->tag == DW_TAG_subprogram)
14684             {
14685               /* Rust doesn't have member functions in the C++ sense.
14686                  However, it does emit ordinary functions as children
14687                  of a struct DIE.  */
14688               if (cu->language == language_rust)
14689                 read_func_scope (child_die, cu);
14690               else
14691                 {
14692                   /* C++ member function.  */
14693                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14694                 }
14695             }
14696           else if (child_die->tag == DW_TAG_inheritance)
14697             {
14698               /* C++ base class field.  */
14699               dwarf2_add_field (&fi, child_die, cu);
14700             }
14701           else if (type_can_define_types (child_die))
14702             dwarf2_add_type_defn (&fi, child_die, cu);
14703           else if (child_die->tag == DW_TAG_template_type_param
14704                    || child_die->tag == DW_TAG_template_value_param)
14705             {
14706               struct symbol *arg = new_symbol (child_die, NULL, cu);
14707
14708               if (arg != NULL)
14709                 template_args.push_back (arg);
14710             }
14711
14712           child_die = sibling_die (child_die);
14713         }
14714
14715       /* Attach template arguments to type.  */
14716       if (!template_args.empty ())
14717         {
14718           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14719           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
14720           TYPE_TEMPLATE_ARGUMENTS (type)
14721             = XOBNEWVEC (&objfile->objfile_obstack,
14722                          struct symbol *,
14723                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14724           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14725                   template_args.data (),
14726                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14727                    * sizeof (struct symbol *)));
14728         }
14729
14730       /* Attach fields and member functions to the type.  */
14731       if (fi.nfields)
14732         dwarf2_attach_fields_to_type (&fi, type, cu);
14733       if (fi.nfnfields)
14734         {
14735           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14736
14737           /* Get the type which refers to the base class (possibly this
14738              class itself) which contains the vtable pointer for the current
14739              class from the DW_AT_containing_type attribute.  This use of
14740              DW_AT_containing_type is a GNU extension.  */
14741
14742           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14743             {
14744               struct type *t = die_containing_type (die, cu);
14745
14746               set_type_vptr_basetype (type, t);
14747               if (type == t)
14748                 {
14749                   int i;
14750
14751                   /* Our own class provides vtbl ptr.  */
14752                   for (i = TYPE_NFIELDS (t) - 1;
14753                        i >= TYPE_N_BASECLASSES (t);
14754                        --i)
14755                     {
14756                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14757
14758                       if (is_vtable_name (fieldname, cu))
14759                         {
14760                           set_type_vptr_fieldno (type, i);
14761                           break;
14762                         }
14763                     }
14764
14765                   /* Complain if virtual function table field not found.  */
14766                   if (i < TYPE_N_BASECLASSES (t))
14767                     complaint (&symfile_complaints,
14768                                _("virtual function table pointer "
14769                                  "not found when defining class '%s'"),
14770                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14771                                "");
14772                 }
14773               else
14774                 {
14775                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14776                 }
14777             }
14778           else if (cu->producer
14779                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14780             {
14781               /* The IBM XLC compiler does not provide direct indication
14782                  of the containing type, but the vtable pointer is
14783                  always named __vfp.  */
14784
14785               int i;
14786
14787               for (i = TYPE_NFIELDS (type) - 1;
14788                    i >= TYPE_N_BASECLASSES (type);
14789                    --i)
14790                 {
14791                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14792                     {
14793                       set_type_vptr_fieldno (type, i);
14794                       set_type_vptr_basetype (type, type);
14795                       break;
14796                     }
14797                 }
14798             }
14799         }
14800
14801       /* Copy fi.typedef_field_list linked list elements content into the
14802          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14803       if (fi.typedef_field_list)
14804         {
14805           int i = fi.typedef_field_list_count;
14806
14807           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14808           TYPE_TYPEDEF_FIELD_ARRAY (type)
14809             = ((struct decl_field *)
14810                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14811           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14812
14813           /* Reverse the list order to keep the debug info elements order.  */
14814           while (--i >= 0)
14815             {
14816               struct decl_field *dest, *src;
14817
14818               dest = &TYPE_TYPEDEF_FIELD (type, i);
14819               src = &fi.typedef_field_list->field;
14820               fi.typedef_field_list = fi.typedef_field_list->next;
14821               *dest = *src;
14822             }
14823         }
14824
14825       /* Copy fi.nested_types_list linked list elements content into the
14826          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
14827       if (fi.nested_types_list != NULL && cu->language != language_ada)
14828         {
14829           int i = fi.nested_types_list_count;
14830
14831           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14832           TYPE_NESTED_TYPES_ARRAY (type)
14833             = ((struct decl_field *)
14834                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
14835           TYPE_NESTED_TYPES_COUNT (type) = i;
14836
14837           /* Reverse the list order to keep the debug info elements order.  */
14838           while (--i >= 0)
14839             {
14840               struct decl_field *dest, *src;
14841
14842               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
14843               src = &fi.nested_types_list->field;
14844               fi.nested_types_list = fi.nested_types_list->next;
14845               *dest = *src;
14846             }
14847         }
14848
14849       do_cleanups (back_to);
14850     }
14851
14852   quirk_gcc_member_function_pointer (type, objfile);
14853
14854   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14855      snapshots) has been known to create a die giving a declaration
14856      for a class that has, as a child, a die giving a definition for a
14857      nested class.  So we have to process our children even if the
14858      current die is a declaration.  Normally, of course, a declaration
14859      won't have any children at all.  */
14860
14861   child_die = die->child;
14862
14863   while (child_die != NULL && child_die->tag)
14864     {
14865       if (child_die->tag == DW_TAG_member
14866           || child_die->tag == DW_TAG_variable
14867           || child_die->tag == DW_TAG_inheritance
14868           || child_die->tag == DW_TAG_template_value_param
14869           || child_die->tag == DW_TAG_template_type_param)
14870         {
14871           /* Do nothing.  */
14872         }
14873       else
14874         process_die (child_die, cu);
14875
14876       child_die = sibling_die (child_die);
14877     }
14878
14879   /* Do not consider external references.  According to the DWARF standard,
14880      these DIEs are identified by the fact that they have no byte_size
14881      attribute, and a declaration attribute.  */
14882   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14883       || !die_is_declaration (die, cu))
14884     new_symbol (die, type, cu);
14885 }
14886
14887 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14888    update TYPE using some information only available in DIE's children.  */
14889
14890 static void
14891 update_enumeration_type_from_children (struct die_info *die,
14892                                        struct type *type,
14893                                        struct dwarf2_cu *cu)
14894 {
14895   struct die_info *child_die;
14896   int unsigned_enum = 1;
14897   int flag_enum = 1;
14898   ULONGEST mask = 0;
14899
14900   auto_obstack obstack;
14901
14902   for (child_die = die->child;
14903        child_die != NULL && child_die->tag;
14904        child_die = sibling_die (child_die))
14905     {
14906       struct attribute *attr;
14907       LONGEST value;
14908       const gdb_byte *bytes;
14909       struct dwarf2_locexpr_baton *baton;
14910       const char *name;
14911
14912       if (child_die->tag != DW_TAG_enumerator)
14913         continue;
14914
14915       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14916       if (attr == NULL)
14917         continue;
14918
14919       name = dwarf2_name (child_die, cu);
14920       if (name == NULL)
14921         name = "<anonymous enumerator>";
14922
14923       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14924                                &value, &bytes, &baton);
14925       if (value < 0)
14926         {
14927           unsigned_enum = 0;
14928           flag_enum = 0;
14929         }
14930       else if ((mask & value) != 0)
14931         flag_enum = 0;
14932       else
14933         mask |= value;
14934
14935       /* If we already know that the enum type is neither unsigned, nor
14936          a flag type, no need to look at the rest of the enumerates.  */
14937       if (!unsigned_enum && !flag_enum)
14938         break;
14939     }
14940
14941   if (unsigned_enum)
14942     TYPE_UNSIGNED (type) = 1;
14943   if (flag_enum)
14944     TYPE_FLAG_ENUM (type) = 1;
14945 }
14946
14947 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14948    complete the type's fields yet, or create any symbols.  */
14949
14950 static struct type *
14951 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14952 {
14953   struct objfile *objfile = cu->objfile;
14954   struct type *type;
14955   struct attribute *attr;
14956   const char *name;
14957
14958   /* If the definition of this type lives in .debug_types, read that type.
14959      Don't follow DW_AT_specification though, that will take us back up
14960      the chain and we want to go down.  */
14961   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14962   if (attr)
14963     {
14964       type = get_DW_AT_signature_type (die, attr, cu);
14965
14966       /* The type's CU may not be the same as CU.
14967          Ensure TYPE is recorded with CU in die_type_hash.  */
14968       return set_die_type (die, type, cu);
14969     }
14970
14971   type = alloc_type (objfile);
14972
14973   TYPE_CODE (type) = TYPE_CODE_ENUM;
14974   name = dwarf2_full_name (NULL, die, cu);
14975   if (name != NULL)
14976     TYPE_TAG_NAME (type) = name;
14977
14978   attr = dwarf2_attr (die, DW_AT_type, cu);
14979   if (attr != NULL)
14980     {
14981       struct type *underlying_type = die_type (die, cu);
14982
14983       TYPE_TARGET_TYPE (type) = underlying_type;
14984     }
14985
14986   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14987   if (attr)
14988     {
14989       TYPE_LENGTH (type) = DW_UNSND (attr);
14990     }
14991   else
14992     {
14993       TYPE_LENGTH (type) = 0;
14994     }
14995
14996   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14997      declared as private in the package spec, and then defined only
14998      inside the package body.  Such types are known as Taft Amendment
14999      Types.  When another package uses such a type, an incomplete DIE
15000      may be generated by the compiler.  */
15001   if (die_is_declaration (die, cu))
15002     TYPE_STUB (type) = 1;
15003
15004   /* Finish the creation of this type by using the enum's children.
15005      We must call this even when the underlying type has been provided
15006      so that we can determine if we're looking at a "flag" enum.  */
15007   update_enumeration_type_from_children (die, type, cu);
15008
15009   /* If this type has an underlying type that is not a stub, then we
15010      may use its attributes.  We always use the "unsigned" attribute
15011      in this situation, because ordinarily we guess whether the type
15012      is unsigned -- but the guess can be wrong and the underlying type
15013      can tell us the reality.  However, we defer to a local size
15014      attribute if one exists, because this lets the compiler override
15015      the underlying type if needed.  */
15016   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
15017     {
15018       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
15019       if (TYPE_LENGTH (type) == 0)
15020         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
15021     }
15022
15023   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
15024
15025   return set_die_type (die, type, cu);
15026 }
15027
15028 /* Given a pointer to a die which begins an enumeration, process all
15029    the dies that define the members of the enumeration, and create the
15030    symbol for the enumeration type.
15031
15032    NOTE: We reverse the order of the element list.  */
15033
15034 static void
15035 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
15036 {
15037   struct type *this_type;
15038
15039   this_type = get_die_type (die, cu);
15040   if (this_type == NULL)
15041     this_type = read_enumeration_type (die, cu);
15042
15043   if (die->child != NULL)
15044     {
15045       struct die_info *child_die;
15046       struct symbol *sym;
15047       struct field *fields = NULL;
15048       int num_fields = 0;
15049       const char *name;
15050
15051       child_die = die->child;
15052       while (child_die && child_die->tag)
15053         {
15054           if (child_die->tag != DW_TAG_enumerator)
15055             {
15056               process_die (child_die, cu);
15057             }
15058           else
15059             {
15060               name = dwarf2_name (child_die, cu);
15061               if (name)
15062                 {
15063                   sym = new_symbol (child_die, this_type, cu);
15064
15065                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
15066                     {
15067                       fields = (struct field *)
15068                         xrealloc (fields,
15069                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
15070                                   * sizeof (struct field));
15071                     }
15072
15073                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
15074                   FIELD_TYPE (fields[num_fields]) = NULL;
15075                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
15076                   FIELD_BITSIZE (fields[num_fields]) = 0;
15077
15078                   num_fields++;
15079                 }
15080             }
15081
15082           child_die = sibling_die (child_die);
15083         }
15084
15085       if (num_fields)
15086         {
15087           TYPE_NFIELDS (this_type) = num_fields;
15088           TYPE_FIELDS (this_type) = (struct field *)
15089             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
15090           memcpy (TYPE_FIELDS (this_type), fields,
15091                   sizeof (struct field) * num_fields);
15092           xfree (fields);
15093         }
15094     }
15095
15096   /* If we are reading an enum from a .debug_types unit, and the enum
15097      is a declaration, and the enum is not the signatured type in the
15098      unit, then we do not want to add a symbol for it.  Adding a
15099      symbol would in some cases obscure the true definition of the
15100      enum, giving users an incomplete type when the definition is
15101      actually available.  Note that we do not want to do this for all
15102      enums which are just declarations, because C++0x allows forward
15103      enum declarations.  */
15104   if (cu->per_cu->is_debug_types
15105       && die_is_declaration (die, cu))
15106     {
15107       struct signatured_type *sig_type;
15108
15109       sig_type = (struct signatured_type *) cu->per_cu;
15110       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
15111       if (sig_type->type_offset_in_section != die->sect_off)
15112         return;
15113     }
15114
15115   new_symbol (die, this_type, cu);
15116 }
15117
15118 /* Extract all information from a DW_TAG_array_type DIE and put it in
15119    the DIE's type field.  For now, this only handles one dimensional
15120    arrays.  */
15121
15122 static struct type *
15123 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
15124 {
15125   struct objfile *objfile = cu->objfile;
15126   struct die_info *child_die;
15127   struct type *type;
15128   struct type *element_type, *range_type, *index_type;
15129   struct attribute *attr;
15130   const char *name;
15131   unsigned int bit_stride = 0;
15132
15133   element_type = die_type (die, cu);
15134
15135   /* The die_type call above may have already set the type for this DIE.  */
15136   type = get_die_type (die, cu);
15137   if (type)
15138     return type;
15139
15140   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
15141   if (attr != NULL)
15142     bit_stride = DW_UNSND (attr) * 8;
15143
15144   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
15145   if (attr != NULL)
15146     bit_stride = DW_UNSND (attr);
15147
15148   /* Irix 6.2 native cc creates array types without children for
15149      arrays with unspecified length.  */
15150   if (die->child == NULL)
15151     {
15152       index_type = objfile_type (objfile)->builtin_int;
15153       range_type = create_static_range_type (NULL, index_type, 0, -1);
15154       type = create_array_type_with_stride (NULL, element_type, range_type,
15155                                             bit_stride);
15156       return set_die_type (die, type, cu);
15157     }
15158
15159   std::vector<struct type *> range_types;
15160   child_die = die->child;
15161   while (child_die && child_die->tag)
15162     {
15163       if (child_die->tag == DW_TAG_subrange_type)
15164         {
15165           struct type *child_type = read_type_die (child_die, cu);
15166
15167           if (child_type != NULL)
15168             {
15169               /* The range type was succesfully read.  Save it for the
15170                  array type creation.  */
15171               range_types.push_back (child_type);
15172             }
15173         }
15174       child_die = sibling_die (child_die);
15175     }
15176
15177   /* Dwarf2 dimensions are output from left to right, create the
15178      necessary array types in backwards order.  */
15179
15180   type = element_type;
15181
15182   if (read_array_order (die, cu) == DW_ORD_col_major)
15183     {
15184       int i = 0;
15185
15186       while (i < range_types.size ())
15187         type = create_array_type_with_stride (NULL, type, range_types[i++],
15188                                               bit_stride);
15189     }
15190   else
15191     {
15192       size_t ndim = range_types.size ();
15193       while (ndim-- > 0)
15194         type = create_array_type_with_stride (NULL, type, range_types[ndim],
15195                                               bit_stride);
15196     }
15197
15198   /* Understand Dwarf2 support for vector types (like they occur on
15199      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
15200      array type.  This is not part of the Dwarf2/3 standard yet, but a
15201      custom vendor extension.  The main difference between a regular
15202      array and the vector variant is that vectors are passed by value
15203      to functions.  */
15204   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
15205   if (attr)
15206     make_vector_type (type);
15207
15208   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
15209      implementation may choose to implement triple vectors using this
15210      attribute.  */
15211   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15212   if (attr)
15213     {
15214       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
15215         TYPE_LENGTH (type) = DW_UNSND (attr);
15216       else
15217         complaint (&symfile_complaints,
15218                    _("DW_AT_byte_size for array type smaller "
15219                      "than the total size of elements"));
15220     }
15221
15222   name = dwarf2_name (die, cu);
15223   if (name)
15224     TYPE_NAME (type) = name;
15225
15226   /* Install the type in the die.  */
15227   set_die_type (die, type, cu);
15228
15229   /* set_die_type should be already done.  */
15230   set_descriptive_type (type, die, cu);
15231
15232   return type;
15233 }
15234
15235 static enum dwarf_array_dim_ordering
15236 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
15237 {
15238   struct attribute *attr;
15239
15240   attr = dwarf2_attr (die, DW_AT_ordering, cu);
15241
15242   if (attr)
15243     return (enum dwarf_array_dim_ordering) DW_SND (attr);
15244
15245   /* GNU F77 is a special case, as at 08/2004 array type info is the
15246      opposite order to the dwarf2 specification, but data is still
15247      laid out as per normal fortran.
15248
15249      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
15250      version checking.  */
15251
15252   if (cu->language == language_fortran
15253       && cu->producer && strstr (cu->producer, "GNU F77"))
15254     {
15255       return DW_ORD_row_major;
15256     }
15257
15258   switch (cu->language_defn->la_array_ordering)
15259     {
15260     case array_column_major:
15261       return DW_ORD_col_major;
15262     case array_row_major:
15263     default:
15264       return DW_ORD_row_major;
15265     };
15266 }
15267
15268 /* Extract all information from a DW_TAG_set_type DIE and put it in
15269    the DIE's type field.  */
15270
15271 static struct type *
15272 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
15273 {
15274   struct type *domain_type, *set_type;
15275   struct attribute *attr;
15276
15277   domain_type = die_type (die, cu);
15278
15279   /* The die_type call above may have already set the type for this DIE.  */
15280   set_type = get_die_type (die, cu);
15281   if (set_type)
15282     return set_type;
15283
15284   set_type = create_set_type (NULL, domain_type);
15285
15286   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15287   if (attr)
15288     TYPE_LENGTH (set_type) = DW_UNSND (attr);
15289
15290   return set_die_type (die, set_type, cu);
15291 }
15292
15293 /* A helper for read_common_block that creates a locexpr baton.
15294    SYM is the symbol which we are marking as computed.
15295    COMMON_DIE is the DIE for the common block.
15296    COMMON_LOC is the location expression attribute for the common
15297    block itself.
15298    MEMBER_LOC is the location expression attribute for the particular
15299    member of the common block that we are processing.
15300    CU is the CU from which the above come.  */
15301
15302 static void
15303 mark_common_block_symbol_computed (struct symbol *sym,
15304                                    struct die_info *common_die,
15305                                    struct attribute *common_loc,
15306                                    struct attribute *member_loc,
15307                                    struct dwarf2_cu *cu)
15308 {
15309   struct objfile *objfile = dwarf2_per_objfile->objfile;
15310   struct dwarf2_locexpr_baton *baton;
15311   gdb_byte *ptr;
15312   unsigned int cu_off;
15313   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
15314   LONGEST offset = 0;
15315
15316   gdb_assert (common_loc && member_loc);
15317   gdb_assert (attr_form_is_block (common_loc));
15318   gdb_assert (attr_form_is_block (member_loc)
15319               || attr_form_is_constant (member_loc));
15320
15321   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
15322   baton->per_cu = cu->per_cu;
15323   gdb_assert (baton->per_cu);
15324
15325   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
15326
15327   if (attr_form_is_constant (member_loc))
15328     {
15329       offset = dwarf2_get_attr_constant_value (member_loc, 0);
15330       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
15331     }
15332   else
15333     baton->size += DW_BLOCK (member_loc)->size;
15334
15335   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
15336   baton->data = ptr;
15337
15338   *ptr++ = DW_OP_call4;
15339   cu_off = common_die->sect_off - cu->per_cu->sect_off;
15340   store_unsigned_integer (ptr, 4, byte_order, cu_off);
15341   ptr += 4;
15342
15343   if (attr_form_is_constant (member_loc))
15344     {
15345       *ptr++ = DW_OP_addr;
15346       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
15347       ptr += cu->header.addr_size;
15348     }
15349   else
15350     {
15351       /* We have to copy the data here, because DW_OP_call4 will only
15352          use a DW_AT_location attribute.  */
15353       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
15354       ptr += DW_BLOCK (member_loc)->size;
15355     }
15356
15357   *ptr++ = DW_OP_plus;
15358   gdb_assert (ptr - baton->data == baton->size);
15359
15360   SYMBOL_LOCATION_BATON (sym) = baton;
15361   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
15362 }
15363
15364 /* Create appropriate locally-scoped variables for all the
15365    DW_TAG_common_block entries.  Also create a struct common_block
15366    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
15367    is used to sepate the common blocks name namespace from regular
15368    variable names.  */
15369
15370 static void
15371 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
15372 {
15373   struct attribute *attr;
15374
15375   attr = dwarf2_attr (die, DW_AT_location, cu);
15376   if (attr)
15377     {
15378       /* Support the .debug_loc offsets.  */
15379       if (attr_form_is_block (attr))
15380         {
15381           /* Ok.  */
15382         }
15383       else if (attr_form_is_section_offset (attr))
15384         {
15385           dwarf2_complex_location_expr_complaint ();
15386           attr = NULL;
15387         }
15388       else
15389         {
15390           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15391                                                  "common block member");
15392           attr = NULL;
15393         }
15394     }
15395
15396   if (die->child != NULL)
15397     {
15398       struct objfile *objfile = cu->objfile;
15399       struct die_info *child_die;
15400       size_t n_entries = 0, size;
15401       struct common_block *common_block;
15402       struct symbol *sym;
15403
15404       for (child_die = die->child;
15405            child_die && child_die->tag;
15406            child_die = sibling_die (child_die))
15407         ++n_entries;
15408
15409       size = (sizeof (struct common_block)
15410               + (n_entries - 1) * sizeof (struct symbol *));
15411       common_block
15412         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
15413                                                  size);
15414       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
15415       common_block->n_entries = 0;
15416
15417       for (child_die = die->child;
15418            child_die && child_die->tag;
15419            child_die = sibling_die (child_die))
15420         {
15421           /* Create the symbol in the DW_TAG_common_block block in the current
15422              symbol scope.  */
15423           sym = new_symbol (child_die, NULL, cu);
15424           if (sym != NULL)
15425             {
15426               struct attribute *member_loc;
15427
15428               common_block->contents[common_block->n_entries++] = sym;
15429
15430               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
15431                                         cu);
15432               if (member_loc)
15433                 {
15434                   /* GDB has handled this for a long time, but it is
15435                      not specified by DWARF.  It seems to have been
15436                      emitted by gfortran at least as recently as:
15437                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
15438                   complaint (&symfile_complaints,
15439                              _("Variable in common block has "
15440                                "DW_AT_data_member_location "
15441                                "- DIE at 0x%x [in module %s]"),
15442                              to_underlying (child_die->sect_off),
15443                              objfile_name (cu->objfile));
15444
15445                   if (attr_form_is_section_offset (member_loc))
15446                     dwarf2_complex_location_expr_complaint ();
15447                   else if (attr_form_is_constant (member_loc)
15448                            || attr_form_is_block (member_loc))
15449                     {
15450                       if (attr)
15451                         mark_common_block_symbol_computed (sym, die, attr,
15452                                                            member_loc, cu);
15453                     }
15454                   else
15455                     dwarf2_complex_location_expr_complaint ();
15456                 }
15457             }
15458         }
15459
15460       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
15461       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
15462     }
15463 }
15464
15465 /* Create a type for a C++ namespace.  */
15466
15467 static struct type *
15468 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
15469 {
15470   struct objfile *objfile = cu->objfile;
15471   const char *previous_prefix, *name;
15472   int is_anonymous;
15473   struct type *type;
15474
15475   /* For extensions, reuse the type of the original namespace.  */
15476   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
15477     {
15478       struct die_info *ext_die;
15479       struct dwarf2_cu *ext_cu = cu;
15480
15481       ext_die = dwarf2_extension (die, &ext_cu);
15482       type = read_type_die (ext_die, ext_cu);
15483
15484       /* EXT_CU may not be the same as CU.
15485          Ensure TYPE is recorded with CU in die_type_hash.  */
15486       return set_die_type (die, type, cu);
15487     }
15488
15489   name = namespace_name (die, &is_anonymous, cu);
15490
15491   /* Now build the name of the current namespace.  */
15492
15493   previous_prefix = determine_prefix (die, cu);
15494   if (previous_prefix[0] != '\0')
15495     name = typename_concat (&objfile->objfile_obstack,
15496                             previous_prefix, name, 0, cu);
15497
15498   /* Create the type.  */
15499   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
15500   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15501
15502   return set_die_type (die, type, cu);
15503 }
15504
15505 /* Read a namespace scope.  */
15506
15507 static void
15508 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
15509 {
15510   struct objfile *objfile = cu->objfile;
15511   int is_anonymous;
15512
15513   /* Add a symbol associated to this if we haven't seen the namespace
15514      before.  Also, add a using directive if it's an anonymous
15515      namespace.  */
15516
15517   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
15518     {
15519       struct type *type;
15520
15521       type = read_type_die (die, cu);
15522       new_symbol (die, type, cu);
15523
15524       namespace_name (die, &is_anonymous, cu);
15525       if (is_anonymous)
15526         {
15527           const char *previous_prefix = determine_prefix (die, cu);
15528
15529           std::vector<const char *> excludes;
15530           add_using_directive (using_directives (cu->language),
15531                                previous_prefix, TYPE_NAME (type), NULL,
15532                                NULL, excludes, 0, &objfile->objfile_obstack);
15533         }
15534     }
15535
15536   if (die->child != NULL)
15537     {
15538       struct die_info *child_die = die->child;
15539
15540       while (child_die && child_die->tag)
15541         {
15542           process_die (child_die, cu);
15543           child_die = sibling_die (child_die);
15544         }
15545     }
15546 }
15547
15548 /* Read a Fortran module as type.  This DIE can be only a declaration used for
15549    imported module.  Still we need that type as local Fortran "use ... only"
15550    declaration imports depend on the created type in determine_prefix.  */
15551
15552 static struct type *
15553 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
15554 {
15555   struct objfile *objfile = cu->objfile;
15556   const char *module_name;
15557   struct type *type;
15558
15559   module_name = dwarf2_name (die, cu);
15560   if (!module_name)
15561     complaint (&symfile_complaints,
15562                _("DW_TAG_module has no name, offset 0x%x"),
15563                to_underlying (die->sect_off));
15564   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
15565
15566   /* determine_prefix uses TYPE_TAG_NAME.  */
15567   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15568
15569   return set_die_type (die, type, cu);
15570 }
15571
15572 /* Read a Fortran module.  */
15573
15574 static void
15575 read_module (struct die_info *die, struct dwarf2_cu *cu)
15576 {
15577   struct die_info *child_die = die->child;
15578   struct type *type;
15579
15580   type = read_type_die (die, cu);
15581   new_symbol (die, type, cu);
15582
15583   while (child_die && child_die->tag)
15584     {
15585       process_die (child_die, cu);
15586       child_die = sibling_die (child_die);
15587     }
15588 }
15589
15590 /* Return the name of the namespace represented by DIE.  Set
15591    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
15592    namespace.  */
15593
15594 static const char *
15595 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
15596 {
15597   struct die_info *current_die;
15598   const char *name = NULL;
15599
15600   /* Loop through the extensions until we find a name.  */
15601
15602   for (current_die = die;
15603        current_die != NULL;
15604        current_die = dwarf2_extension (die, &cu))
15605     {
15606       /* We don't use dwarf2_name here so that we can detect the absence
15607          of a name -> anonymous namespace.  */
15608       name = dwarf2_string_attr (die, DW_AT_name, cu);
15609
15610       if (name != NULL)
15611         break;
15612     }
15613
15614   /* Is it an anonymous namespace?  */
15615
15616   *is_anonymous = (name == NULL);
15617   if (*is_anonymous)
15618     name = CP_ANONYMOUS_NAMESPACE_STR;
15619
15620   return name;
15621 }
15622
15623 /* Extract all information from a DW_TAG_pointer_type DIE and add to
15624    the user defined type vector.  */
15625
15626 static struct type *
15627 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
15628 {
15629   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
15630   struct comp_unit_head *cu_header = &cu->header;
15631   struct type *type;
15632   struct attribute *attr_byte_size;
15633   struct attribute *attr_address_class;
15634   int byte_size, addr_class;
15635   struct type *target_type;
15636
15637   target_type = die_type (die, cu);
15638
15639   /* The die_type call above may have already set the type for this DIE.  */
15640   type = get_die_type (die, cu);
15641   if (type)
15642     return type;
15643
15644   type = lookup_pointer_type (target_type);
15645
15646   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
15647   if (attr_byte_size)
15648     byte_size = DW_UNSND (attr_byte_size);
15649   else
15650     byte_size = cu_header->addr_size;
15651
15652   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
15653   if (attr_address_class)
15654     addr_class = DW_UNSND (attr_address_class);
15655   else
15656     addr_class = DW_ADDR_none;
15657
15658   /* If the pointer size or address class is different than the
15659      default, create a type variant marked as such and set the
15660      length accordingly.  */
15661   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15662     {
15663       if (gdbarch_address_class_type_flags_p (gdbarch))
15664         {
15665           int type_flags;
15666
15667           type_flags = gdbarch_address_class_type_flags
15668                          (gdbarch, byte_size, addr_class);
15669           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15670                       == 0);
15671           type = make_type_with_address_space (type, type_flags);
15672         }
15673       else if (TYPE_LENGTH (type) != byte_size)
15674         {
15675           complaint (&symfile_complaints,
15676                      _("invalid pointer size %d"), byte_size);
15677         }
15678       else
15679         {
15680           /* Should we also complain about unhandled address classes?  */
15681         }
15682     }
15683
15684   TYPE_LENGTH (type) = byte_size;
15685   return set_die_type (die, type, cu);
15686 }
15687
15688 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15689    the user defined type vector.  */
15690
15691 static struct type *
15692 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15693 {
15694   struct type *type;
15695   struct type *to_type;
15696   struct type *domain;
15697
15698   to_type = die_type (die, cu);
15699   domain = die_containing_type (die, cu);
15700
15701   /* The calls above may have already set the type for this DIE.  */
15702   type = get_die_type (die, cu);
15703   if (type)
15704     return type;
15705
15706   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15707     type = lookup_methodptr_type (to_type);
15708   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15709     {
15710       struct type *new_type = alloc_type (cu->objfile);
15711
15712       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15713                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15714                             TYPE_VARARGS (to_type));
15715       type = lookup_methodptr_type (new_type);
15716     }
15717   else
15718     type = lookup_memberptr_type (to_type, domain);
15719
15720   return set_die_type (die, type, cu);
15721 }
15722
15723 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15724    the user defined type vector.  */
15725
15726 static struct type *
15727 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15728                           enum type_code refcode)
15729 {
15730   struct comp_unit_head *cu_header = &cu->header;
15731   struct type *type, *target_type;
15732   struct attribute *attr;
15733
15734   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15735
15736   target_type = die_type (die, cu);
15737
15738   /* The die_type call above may have already set the type for this DIE.  */
15739   type = get_die_type (die, cu);
15740   if (type)
15741     return type;
15742
15743   type = lookup_reference_type (target_type, refcode);
15744   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15745   if (attr)
15746     {
15747       TYPE_LENGTH (type) = DW_UNSND (attr);
15748     }
15749   else
15750     {
15751       TYPE_LENGTH (type) = cu_header->addr_size;
15752     }
15753   return set_die_type (die, type, cu);
15754 }
15755
15756 /* Add the given cv-qualifiers to the element type of the array.  GCC
15757    outputs DWARF type qualifiers that apply to an array, not the
15758    element type.  But GDB relies on the array element type to carry
15759    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15760    specification.  */
15761
15762 static struct type *
15763 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15764                    struct type *base_type, int cnst, int voltl)
15765 {
15766   struct type *el_type, *inner_array;
15767
15768   base_type = copy_type (base_type);
15769   inner_array = base_type;
15770
15771   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15772     {
15773       TYPE_TARGET_TYPE (inner_array) =
15774         copy_type (TYPE_TARGET_TYPE (inner_array));
15775       inner_array = TYPE_TARGET_TYPE (inner_array);
15776     }
15777
15778   el_type = TYPE_TARGET_TYPE (inner_array);
15779   cnst |= TYPE_CONST (el_type);
15780   voltl |= TYPE_VOLATILE (el_type);
15781   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15782
15783   return set_die_type (die, base_type, cu);
15784 }
15785
15786 static struct type *
15787 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15788 {
15789   struct type *base_type, *cv_type;
15790
15791   base_type = die_type (die, cu);
15792
15793   /* The die_type call above may have already set the type for this DIE.  */
15794   cv_type = get_die_type (die, cu);
15795   if (cv_type)
15796     return cv_type;
15797
15798   /* In case the const qualifier is applied to an array type, the element type
15799      is so qualified, not the array type (section 6.7.3 of C99).  */
15800   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15801     return add_array_cv_type (die, cu, base_type, 1, 0);
15802
15803   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15804   return set_die_type (die, cv_type, cu);
15805 }
15806
15807 static struct type *
15808 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
15809 {
15810   struct type *base_type, *cv_type;
15811
15812   base_type = die_type (die, cu);
15813
15814   /* The die_type call above may have already set the type for this DIE.  */
15815   cv_type = get_die_type (die, cu);
15816   if (cv_type)
15817     return cv_type;
15818
15819   /* In case the volatile qualifier is applied to an array type, the
15820      element type is so qualified, not the array type (section 6.7.3
15821      of C99).  */
15822   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15823     return add_array_cv_type (die, cu, base_type, 0, 1);
15824
15825   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15826   return set_die_type (die, cv_type, cu);
15827 }
15828
15829 /* Handle DW_TAG_restrict_type.  */
15830
15831 static struct type *
15832 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15833 {
15834   struct type *base_type, *cv_type;
15835
15836   base_type = die_type (die, cu);
15837
15838   /* The die_type call above may have already set the type for this DIE.  */
15839   cv_type = get_die_type (die, cu);
15840   if (cv_type)
15841     return cv_type;
15842
15843   cv_type = make_restrict_type (base_type);
15844   return set_die_type (die, cv_type, cu);
15845 }
15846
15847 /* Handle DW_TAG_atomic_type.  */
15848
15849 static struct type *
15850 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15851 {
15852   struct type *base_type, *cv_type;
15853
15854   base_type = die_type (die, cu);
15855
15856   /* The die_type call above may have already set the type for this DIE.  */
15857   cv_type = get_die_type (die, cu);
15858   if (cv_type)
15859     return cv_type;
15860
15861   cv_type = make_atomic_type (base_type);
15862   return set_die_type (die, cv_type, cu);
15863 }
15864
15865 /* Extract all information from a DW_TAG_string_type DIE and add to
15866    the user defined type vector.  It isn't really a user defined type,
15867    but it behaves like one, with other DIE's using an AT_user_def_type
15868    attribute to reference it.  */
15869
15870 static struct type *
15871 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15872 {
15873   struct objfile *objfile = cu->objfile;
15874   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15875   struct type *type, *range_type, *index_type, *char_type;
15876   struct attribute *attr;
15877   unsigned int length;
15878
15879   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15880   if (attr)
15881     {
15882       length = DW_UNSND (attr);
15883     }
15884   else
15885     {
15886       /* Check for the DW_AT_byte_size attribute.  */
15887       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15888       if (attr)
15889         {
15890           length = DW_UNSND (attr);
15891         }
15892       else
15893         {
15894           length = 1;
15895         }
15896     }
15897
15898   index_type = objfile_type (objfile)->builtin_int;
15899   range_type = create_static_range_type (NULL, index_type, 1, length);
15900   char_type = language_string_char_type (cu->language_defn, gdbarch);
15901   type = create_string_type (NULL, char_type, range_type);
15902
15903   return set_die_type (die, type, cu);
15904 }
15905
15906 /* Assuming that DIE corresponds to a function, returns nonzero
15907    if the function is prototyped.  */
15908
15909 static int
15910 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15911 {
15912   struct attribute *attr;
15913
15914   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15915   if (attr && (DW_UNSND (attr) != 0))
15916     return 1;
15917
15918   /* The DWARF standard implies that the DW_AT_prototyped attribute
15919      is only meaninful for C, but the concept also extends to other
15920      languages that allow unprototyped functions (Eg: Objective C).
15921      For all other languages, assume that functions are always
15922      prototyped.  */
15923   if (cu->language != language_c
15924       && cu->language != language_objc
15925       && cu->language != language_opencl)
15926     return 1;
15927
15928   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15929      prototyped and unprototyped functions; default to prototyped,
15930      since that is more common in modern code (and RealView warns
15931      about unprototyped functions).  */
15932   if (producer_is_realview (cu->producer))
15933     return 1;
15934
15935   return 0;
15936 }
15937
15938 /* Handle DIES due to C code like:
15939
15940    struct foo
15941    {
15942    int (*funcp)(int a, long l);
15943    int b;
15944    };
15945
15946    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15947
15948 static struct type *
15949 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15950 {
15951   struct objfile *objfile = cu->objfile;
15952   struct type *type;            /* Type that this function returns.  */
15953   struct type *ftype;           /* Function that returns above type.  */
15954   struct attribute *attr;
15955
15956   type = die_type (die, cu);
15957
15958   /* The die_type call above may have already set the type for this DIE.  */
15959   ftype = get_die_type (die, cu);
15960   if (ftype)
15961     return ftype;
15962
15963   ftype = lookup_function_type (type);
15964
15965   if (prototyped_function_p (die, cu))
15966     TYPE_PROTOTYPED (ftype) = 1;
15967
15968   /* Store the calling convention in the type if it's available in
15969      the subroutine die.  Otherwise set the calling convention to
15970      the default value DW_CC_normal.  */
15971   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15972   if (attr)
15973     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15974   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15975     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15976   else
15977     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15978
15979   /* Record whether the function returns normally to its caller or not
15980      if the DWARF producer set that information.  */
15981   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15982   if (attr && (DW_UNSND (attr) != 0))
15983     TYPE_NO_RETURN (ftype) = 1;
15984
15985   /* We need to add the subroutine type to the die immediately so
15986      we don't infinitely recurse when dealing with parameters
15987      declared as the same subroutine type.  */
15988   set_die_type (die, ftype, cu);
15989
15990   if (die->child != NULL)
15991     {
15992       struct type *void_type = objfile_type (objfile)->builtin_void;
15993       struct die_info *child_die;
15994       int nparams, iparams;
15995
15996       /* Count the number of parameters.
15997          FIXME: GDB currently ignores vararg functions, but knows about
15998          vararg member functions.  */
15999       nparams = 0;
16000       child_die = die->child;
16001       while (child_die && child_die->tag)
16002         {
16003           if (child_die->tag == DW_TAG_formal_parameter)
16004             nparams++;
16005           else if (child_die->tag == DW_TAG_unspecified_parameters)
16006             TYPE_VARARGS (ftype) = 1;
16007           child_die = sibling_die (child_die);
16008         }
16009
16010       /* Allocate storage for parameters and fill them in.  */
16011       TYPE_NFIELDS (ftype) = nparams;
16012       TYPE_FIELDS (ftype) = (struct field *)
16013         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
16014
16015       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
16016          even if we error out during the parameters reading below.  */
16017       for (iparams = 0; iparams < nparams; iparams++)
16018         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
16019
16020       iparams = 0;
16021       child_die = die->child;
16022       while (child_die && child_die->tag)
16023         {
16024           if (child_die->tag == DW_TAG_formal_parameter)
16025             {
16026               struct type *arg_type;
16027
16028               /* DWARF version 2 has no clean way to discern C++
16029                  static and non-static member functions.  G++ helps
16030                  GDB by marking the first parameter for non-static
16031                  member functions (which is the this pointer) as
16032                  artificial.  We pass this information to
16033                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
16034
16035                  DWARF version 3 added DW_AT_object_pointer, which GCC
16036                  4.5 does not yet generate.  */
16037               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
16038               if (attr)
16039                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
16040               else
16041                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
16042               arg_type = die_type (child_die, cu);
16043
16044               /* RealView does not mark THIS as const, which the testsuite
16045                  expects.  GCC marks THIS as const in method definitions,
16046                  but not in the class specifications (GCC PR 43053).  */
16047               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
16048                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
16049                 {
16050                   int is_this = 0;
16051                   struct dwarf2_cu *arg_cu = cu;
16052                   const char *name = dwarf2_name (child_die, cu);
16053
16054                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
16055                   if (attr)
16056                     {
16057                       /* If the compiler emits this, use it.  */
16058                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
16059                         is_this = 1;
16060                     }
16061                   else if (name && strcmp (name, "this") == 0)
16062                     /* Function definitions will have the argument names.  */
16063                     is_this = 1;
16064                   else if (name == NULL && iparams == 0)
16065                     /* Declarations may not have the names, so like
16066                        elsewhere in GDB, assume an artificial first
16067                        argument is "this".  */
16068                     is_this = 1;
16069
16070                   if (is_this)
16071                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
16072                                              arg_type, 0);
16073                 }
16074
16075               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
16076               iparams++;
16077             }
16078           child_die = sibling_die (child_die);
16079         }
16080     }
16081
16082   return ftype;
16083 }
16084
16085 static struct type *
16086 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
16087 {
16088   struct objfile *objfile = cu->objfile;
16089   const char *name = NULL;
16090   struct type *this_type, *target_type;
16091
16092   name = dwarf2_full_name (NULL, die, cu);
16093   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
16094   TYPE_TARGET_STUB (this_type) = 1;
16095   set_die_type (die, this_type, cu);
16096   target_type = die_type (die, cu);
16097   if (target_type != this_type)
16098     TYPE_TARGET_TYPE (this_type) = target_type;
16099   else
16100     {
16101       /* Self-referential typedefs are, it seems, not allowed by the DWARF
16102          spec and cause infinite loops in GDB.  */
16103       complaint (&symfile_complaints,
16104                  _("Self-referential DW_TAG_typedef "
16105                    "- DIE at 0x%x [in module %s]"),
16106                  to_underlying (die->sect_off), objfile_name (objfile));
16107       TYPE_TARGET_TYPE (this_type) = NULL;
16108     }
16109   return this_type;
16110 }
16111
16112 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
16113    (which may be different from NAME) to the architecture back-end to allow
16114    it to guess the correct format if necessary.  */
16115
16116 static struct type *
16117 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
16118                         const char *name_hint)
16119 {
16120   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16121   const struct floatformat **format;
16122   struct type *type;
16123
16124   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
16125   if (format)
16126     type = init_float_type (objfile, bits, name, format);
16127   else
16128     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16129
16130   return type;
16131 }
16132
16133 /* Find a representation of a given base type and install
16134    it in the TYPE field of the die.  */
16135
16136 static struct type *
16137 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
16138 {
16139   struct objfile *objfile = cu->objfile;
16140   struct type *type;
16141   struct attribute *attr;
16142   int encoding = 0, bits = 0;
16143   const char *name;
16144
16145   attr = dwarf2_attr (die, DW_AT_encoding, cu);
16146   if (attr)
16147     {
16148       encoding = DW_UNSND (attr);
16149     }
16150   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16151   if (attr)
16152     {
16153       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
16154     }
16155   name = dwarf2_name (die, cu);
16156   if (!name)
16157     {
16158       complaint (&symfile_complaints,
16159                  _("DW_AT_name missing from DW_TAG_base_type"));
16160     }
16161
16162   switch (encoding)
16163     {
16164       case DW_ATE_address:
16165         /* Turn DW_ATE_address into a void * pointer.  */
16166         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
16167         type = init_pointer_type (objfile, bits, name, type);
16168         break;
16169       case DW_ATE_boolean:
16170         type = init_boolean_type (objfile, bits, 1, name);
16171         break;
16172       case DW_ATE_complex_float:
16173         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
16174         type = init_complex_type (objfile, name, type);
16175         break;
16176       case DW_ATE_decimal_float:
16177         type = init_decfloat_type (objfile, bits, name);
16178         break;
16179       case DW_ATE_float:
16180         type = dwarf2_init_float_type (objfile, bits, name, name);
16181         break;
16182       case DW_ATE_signed:
16183         type = init_integer_type (objfile, bits, 0, name);
16184         break;
16185       case DW_ATE_unsigned:
16186         if (cu->language == language_fortran
16187             && name
16188             && startswith (name, "character("))
16189           type = init_character_type (objfile, bits, 1, name);
16190         else
16191           type = init_integer_type (objfile, bits, 1, name);
16192         break;
16193       case DW_ATE_signed_char:
16194         if (cu->language == language_ada || cu->language == language_m2
16195             || cu->language == language_pascal
16196             || cu->language == language_fortran)
16197           type = init_character_type (objfile, bits, 0, name);
16198         else
16199           type = init_integer_type (objfile, bits, 0, name);
16200         break;
16201       case DW_ATE_unsigned_char:
16202         if (cu->language == language_ada || cu->language == language_m2
16203             || cu->language == language_pascal
16204             || cu->language == language_fortran
16205             || cu->language == language_rust)
16206           type = init_character_type (objfile, bits, 1, name);
16207         else
16208           type = init_integer_type (objfile, bits, 1, name);
16209         break;
16210       case DW_ATE_UTF:
16211         {
16212           gdbarch *arch = get_objfile_arch (objfile);
16213
16214           if (bits == 16)
16215             type = builtin_type (arch)->builtin_char16;
16216           else if (bits == 32)
16217             type = builtin_type (arch)->builtin_char32;
16218           else
16219             {
16220               complaint (&symfile_complaints,
16221                          _("unsupported DW_ATE_UTF bit size: '%d'"),
16222                          bits);
16223               type = init_integer_type (objfile, bits, 1, name);
16224             }
16225           return set_die_type (die, type, cu);
16226         }
16227         break;
16228
16229       default:
16230         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
16231                    dwarf_type_encoding_name (encoding));
16232         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16233         break;
16234     }
16235
16236   if (name && strcmp (name, "char") == 0)
16237     TYPE_NOSIGN (type) = 1;
16238
16239   return set_die_type (die, type, cu);
16240 }
16241
16242 /* Parse dwarf attribute if it's a block, reference or constant and put the
16243    resulting value of the attribute into struct bound_prop.
16244    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
16245
16246 static int
16247 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
16248                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
16249 {
16250   struct dwarf2_property_baton *baton;
16251   struct obstack *obstack = &cu->objfile->objfile_obstack;
16252
16253   if (attr == NULL || prop == NULL)
16254     return 0;
16255
16256   if (attr_form_is_block (attr))
16257     {
16258       baton = XOBNEW (obstack, struct dwarf2_property_baton);
16259       baton->referenced_type = NULL;
16260       baton->locexpr.per_cu = cu->per_cu;
16261       baton->locexpr.size = DW_BLOCK (attr)->size;
16262       baton->locexpr.data = DW_BLOCK (attr)->data;
16263       prop->data.baton = baton;
16264       prop->kind = PROP_LOCEXPR;
16265       gdb_assert (prop->data.baton != NULL);
16266     }
16267   else if (attr_form_is_ref (attr))
16268     {
16269       struct dwarf2_cu *target_cu = cu;
16270       struct die_info *target_die;
16271       struct attribute *target_attr;
16272
16273       target_die = follow_die_ref (die, attr, &target_cu);
16274       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
16275       if (target_attr == NULL)
16276         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
16277                                    target_cu);
16278       if (target_attr == NULL)
16279         return 0;
16280
16281       switch (target_attr->name)
16282         {
16283           case DW_AT_location:
16284             if (attr_form_is_section_offset (target_attr))
16285               {
16286                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16287                 baton->referenced_type = die_type (target_die, target_cu);
16288                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
16289                 prop->data.baton = baton;
16290                 prop->kind = PROP_LOCLIST;
16291                 gdb_assert (prop->data.baton != NULL);
16292               }
16293             else if (attr_form_is_block (target_attr))
16294               {
16295                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16296                 baton->referenced_type = die_type (target_die, target_cu);
16297                 baton->locexpr.per_cu = cu->per_cu;
16298                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
16299                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
16300                 prop->data.baton = baton;
16301                 prop->kind = PROP_LOCEXPR;
16302                 gdb_assert (prop->data.baton != NULL);
16303               }
16304             else
16305               {
16306                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16307                                                        "dynamic property");
16308                 return 0;
16309               }
16310             break;
16311           case DW_AT_data_member_location:
16312             {
16313               LONGEST offset;
16314
16315               if (!handle_data_member_location (target_die, target_cu,
16316                                                 &offset))
16317                 return 0;
16318
16319               baton = XOBNEW (obstack, struct dwarf2_property_baton);
16320               baton->referenced_type = read_type_die (target_die->parent,
16321                                                       target_cu);
16322               baton->offset_info.offset = offset;
16323               baton->offset_info.type = die_type (target_die, target_cu);
16324               prop->data.baton = baton;
16325               prop->kind = PROP_ADDR_OFFSET;
16326               break;
16327             }
16328         }
16329     }
16330   else if (attr_form_is_constant (attr))
16331     {
16332       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
16333       prop->kind = PROP_CONST;
16334     }
16335   else
16336     {
16337       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
16338                                              dwarf2_name (die, cu));
16339       return 0;
16340     }
16341
16342   return 1;
16343 }
16344
16345 /* Read the given DW_AT_subrange DIE.  */
16346
16347 static struct type *
16348 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
16349 {
16350   struct type *base_type, *orig_base_type;
16351   struct type *range_type;
16352   struct attribute *attr;
16353   struct dynamic_prop low, high;
16354   int low_default_is_valid;
16355   int high_bound_is_count = 0;
16356   const char *name;
16357   LONGEST negative_mask;
16358
16359   orig_base_type = die_type (die, cu);
16360   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
16361      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
16362      creating the range type, but we use the result of check_typedef
16363      when examining properties of the type.  */
16364   base_type = check_typedef (orig_base_type);
16365
16366   /* The die_type call above may have already set the type for this DIE.  */
16367   range_type = get_die_type (die, cu);
16368   if (range_type)
16369     return range_type;
16370
16371   low.kind = PROP_CONST;
16372   high.kind = PROP_CONST;
16373   high.data.const_val = 0;
16374
16375   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
16376      omitting DW_AT_lower_bound.  */
16377   switch (cu->language)
16378     {
16379     case language_c:
16380     case language_cplus:
16381       low.data.const_val = 0;
16382       low_default_is_valid = 1;
16383       break;
16384     case language_fortran:
16385       low.data.const_val = 1;
16386       low_default_is_valid = 1;
16387       break;
16388     case language_d:
16389     case language_objc:
16390     case language_rust:
16391       low.data.const_val = 0;
16392       low_default_is_valid = (cu->header.version >= 4);
16393       break;
16394     case language_ada:
16395     case language_m2:
16396     case language_pascal:
16397       low.data.const_val = 1;
16398       low_default_is_valid = (cu->header.version >= 4);
16399       break;
16400     default:
16401       low.data.const_val = 0;
16402       low_default_is_valid = 0;
16403       break;
16404     }
16405
16406   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
16407   if (attr)
16408     attr_to_dynamic_prop (attr, die, cu, &low);
16409   else if (!low_default_is_valid)
16410     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
16411                                       "- DIE at 0x%x [in module %s]"),
16412                to_underlying (die->sect_off), objfile_name (cu->objfile));
16413
16414   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
16415   if (!attr_to_dynamic_prop (attr, die, cu, &high))
16416     {
16417       attr = dwarf2_attr (die, DW_AT_count, cu);
16418       if (attr_to_dynamic_prop (attr, die, cu, &high))
16419         {
16420           /* If bounds are constant do the final calculation here.  */
16421           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
16422             high.data.const_val = low.data.const_val + high.data.const_val - 1;
16423           else
16424             high_bound_is_count = 1;
16425         }
16426     }
16427
16428   /* Dwarf-2 specifications explicitly allows to create subrange types
16429      without specifying a base type.
16430      In that case, the base type must be set to the type of
16431      the lower bound, upper bound or count, in that order, if any of these
16432      three attributes references an object that has a type.
16433      If no base type is found, the Dwarf-2 specifications say that
16434      a signed integer type of size equal to the size of an address should
16435      be used.
16436      For the following C code: `extern char gdb_int [];'
16437      GCC produces an empty range DIE.
16438      FIXME: muller/2010-05-28: Possible references to object for low bound,
16439      high bound or count are not yet handled by this code.  */
16440   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
16441     {
16442       struct objfile *objfile = cu->objfile;
16443       struct gdbarch *gdbarch = get_objfile_arch (objfile);
16444       int addr_size = gdbarch_addr_bit (gdbarch) /8;
16445       struct type *int_type = objfile_type (objfile)->builtin_int;
16446
16447       /* Test "int", "long int", and "long long int" objfile types,
16448          and select the first one having a size above or equal to the
16449          architecture address size.  */
16450       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16451         base_type = int_type;
16452       else
16453         {
16454           int_type = objfile_type (objfile)->builtin_long;
16455           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16456             base_type = int_type;
16457           else
16458             {
16459               int_type = objfile_type (objfile)->builtin_long_long;
16460               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16461                 base_type = int_type;
16462             }
16463         }
16464     }
16465
16466   /* Normally, the DWARF producers are expected to use a signed
16467      constant form (Eg. DW_FORM_sdata) to express negative bounds.
16468      But this is unfortunately not always the case, as witnessed
16469      with GCC, for instance, where the ambiguous DW_FORM_dataN form
16470      is used instead.  To work around that ambiguity, we treat
16471      the bounds as signed, and thus sign-extend their values, when
16472      the base type is signed.  */
16473   negative_mask =
16474     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
16475   if (low.kind == PROP_CONST
16476       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
16477     low.data.const_val |= negative_mask;
16478   if (high.kind == PROP_CONST
16479       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
16480     high.data.const_val |= negative_mask;
16481
16482   range_type = create_range_type (NULL, orig_base_type, &low, &high);
16483
16484   if (high_bound_is_count)
16485     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
16486
16487   /* Ada expects an empty array on no boundary attributes.  */
16488   if (attr == NULL && cu->language != language_ada)
16489     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
16490
16491   name = dwarf2_name (die, cu);
16492   if (name)
16493     TYPE_NAME (range_type) = name;
16494
16495   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16496   if (attr)
16497     TYPE_LENGTH (range_type) = DW_UNSND (attr);
16498
16499   set_die_type (die, range_type, cu);
16500
16501   /* set_die_type should be already done.  */
16502   set_descriptive_type (range_type, die, cu);
16503
16504   return range_type;
16505 }
16506
16507 static struct type *
16508 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
16509 {
16510   struct type *type;
16511
16512   /* For now, we only support the C meaning of an unspecified type: void.  */
16513
16514   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
16515   TYPE_NAME (type) = dwarf2_name (die, cu);
16516
16517   return set_die_type (die, type, cu);
16518 }
16519
16520 /* Read a single die and all its descendents.  Set the die's sibling
16521    field to NULL; set other fields in the die correctly, and set all
16522    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
16523    location of the info_ptr after reading all of those dies.  PARENT
16524    is the parent of the die in question.  */
16525
16526 static struct die_info *
16527 read_die_and_children (const struct die_reader_specs *reader,
16528                        const gdb_byte *info_ptr,
16529                        const gdb_byte **new_info_ptr,
16530                        struct die_info *parent)
16531 {
16532   struct die_info *die;
16533   const gdb_byte *cur_ptr;
16534   int has_children;
16535
16536   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
16537   if (die == NULL)
16538     {
16539       *new_info_ptr = cur_ptr;
16540       return NULL;
16541     }
16542   store_in_ref_table (die, reader->cu);
16543
16544   if (has_children)
16545     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
16546   else
16547     {
16548       die->child = NULL;
16549       *new_info_ptr = cur_ptr;
16550     }
16551
16552   die->sibling = NULL;
16553   die->parent = parent;
16554   return die;
16555 }
16556
16557 /* Read a die, all of its descendents, and all of its siblings; set
16558    all of the fields of all of the dies correctly.  Arguments are as
16559    in read_die_and_children.  */
16560
16561 static struct die_info *
16562 read_die_and_siblings_1 (const struct die_reader_specs *reader,
16563                          const gdb_byte *info_ptr,
16564                          const gdb_byte **new_info_ptr,
16565                          struct die_info *parent)
16566 {
16567   struct die_info *first_die, *last_sibling;
16568   const gdb_byte *cur_ptr;
16569
16570   cur_ptr = info_ptr;
16571   first_die = last_sibling = NULL;
16572
16573   while (1)
16574     {
16575       struct die_info *die
16576         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
16577
16578       if (die == NULL)
16579         {
16580           *new_info_ptr = cur_ptr;
16581           return first_die;
16582         }
16583
16584       if (!first_die)
16585         first_die = die;
16586       else
16587         last_sibling->sibling = die;
16588
16589       last_sibling = die;
16590     }
16591 }
16592
16593 /* Read a die, all of its descendents, and all of its siblings; set
16594    all of the fields of all of the dies correctly.  Arguments are as
16595    in read_die_and_children.
16596    This the main entry point for reading a DIE and all its children.  */
16597
16598 static struct die_info *
16599 read_die_and_siblings (const struct die_reader_specs *reader,
16600                        const gdb_byte *info_ptr,
16601                        const gdb_byte **new_info_ptr,
16602                        struct die_info *parent)
16603 {
16604   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
16605                                                   new_info_ptr, parent);
16606
16607   if (dwarf_die_debug)
16608     {
16609       fprintf_unfiltered (gdb_stdlog,
16610                           "Read die from %s@0x%x of %s:\n",
16611                           get_section_name (reader->die_section),
16612                           (unsigned) (info_ptr - reader->die_section->buffer),
16613                           bfd_get_filename (reader->abfd));
16614       dump_die (die, dwarf_die_debug);
16615     }
16616
16617   return die;
16618 }
16619
16620 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
16621    attributes.
16622    The caller is responsible for filling in the extra attributes
16623    and updating (*DIEP)->num_attrs.
16624    Set DIEP to point to a newly allocated die with its information,
16625    except for its child, sibling, and parent fields.
16626    Set HAS_CHILDREN to tell whether the die has children or not.  */
16627
16628 static const gdb_byte *
16629 read_full_die_1 (const struct die_reader_specs *reader,
16630                  struct die_info **diep, const gdb_byte *info_ptr,
16631                  int *has_children, int num_extra_attrs)
16632 {
16633   unsigned int abbrev_number, bytes_read, i;
16634   struct abbrev_info *abbrev;
16635   struct die_info *die;
16636   struct dwarf2_cu *cu = reader->cu;
16637   bfd *abfd = reader->abfd;
16638
16639   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
16640   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16641   info_ptr += bytes_read;
16642   if (!abbrev_number)
16643     {
16644       *diep = NULL;
16645       *has_children = 0;
16646       return info_ptr;
16647     }
16648
16649   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
16650   if (!abbrev)
16651     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
16652            abbrev_number,
16653            bfd_get_filename (abfd));
16654
16655   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16656   die->sect_off = sect_off;
16657   die->tag = abbrev->tag;
16658   die->abbrev = abbrev_number;
16659
16660   /* Make the result usable.
16661      The caller needs to update num_attrs after adding the extra
16662      attributes.  */
16663   die->num_attrs = abbrev->num_attrs;
16664
16665   for (i = 0; i < abbrev->num_attrs; ++i)
16666     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16667                                info_ptr);
16668
16669   *diep = die;
16670   *has_children = abbrev->has_children;
16671   return info_ptr;
16672 }
16673
16674 /* Read a die and all its attributes.
16675    Set DIEP to point to a newly allocated die with its information,
16676    except for its child, sibling, and parent fields.
16677    Set HAS_CHILDREN to tell whether the die has children or not.  */
16678
16679 static const gdb_byte *
16680 read_full_die (const struct die_reader_specs *reader,
16681                struct die_info **diep, const gdb_byte *info_ptr,
16682                int *has_children)
16683 {
16684   const gdb_byte *result;
16685
16686   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16687
16688   if (dwarf_die_debug)
16689     {
16690       fprintf_unfiltered (gdb_stdlog,
16691                           "Read die from %s@0x%x of %s:\n",
16692                           get_section_name (reader->die_section),
16693                           (unsigned) (info_ptr - reader->die_section->buffer),
16694                           bfd_get_filename (reader->abfd));
16695       dump_die (*diep, dwarf_die_debug);
16696     }
16697
16698   return result;
16699 }
16700 \f
16701 /* Abbreviation tables.
16702
16703    In DWARF version 2, the description of the debugging information is
16704    stored in a separate .debug_abbrev section.  Before we read any
16705    dies from a section we read in all abbreviations and install them
16706    in a hash table.  */
16707
16708 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16709
16710 static struct abbrev_info *
16711 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16712 {
16713   struct abbrev_info *abbrev;
16714
16715   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16716   memset (abbrev, 0, sizeof (struct abbrev_info));
16717
16718   return abbrev;
16719 }
16720
16721 /* Add an abbreviation to the table.  */
16722
16723 static void
16724 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16725                          unsigned int abbrev_number,
16726                          struct abbrev_info *abbrev)
16727 {
16728   unsigned int hash_number;
16729
16730   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16731   abbrev->next = abbrev_table->abbrevs[hash_number];
16732   abbrev_table->abbrevs[hash_number] = abbrev;
16733 }
16734
16735 /* Look up an abbrev in the table.
16736    Returns NULL if the abbrev is not found.  */
16737
16738 static struct abbrev_info *
16739 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16740                             unsigned int abbrev_number)
16741 {
16742   unsigned int hash_number;
16743   struct abbrev_info *abbrev;
16744
16745   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16746   abbrev = abbrev_table->abbrevs[hash_number];
16747
16748   while (abbrev)
16749     {
16750       if (abbrev->number == abbrev_number)
16751         return abbrev;
16752       abbrev = abbrev->next;
16753     }
16754   return NULL;
16755 }
16756
16757 /* Read in an abbrev table.  */
16758
16759 static struct abbrev_table *
16760 abbrev_table_read_table (struct dwarf2_section_info *section,
16761                          sect_offset sect_off)
16762 {
16763   struct objfile *objfile = dwarf2_per_objfile->objfile;
16764   bfd *abfd = get_section_bfd_owner (section);
16765   struct abbrev_table *abbrev_table;
16766   const gdb_byte *abbrev_ptr;
16767   struct abbrev_info *cur_abbrev;
16768   unsigned int abbrev_number, bytes_read, abbrev_name;
16769   unsigned int abbrev_form;
16770   struct attr_abbrev *cur_attrs;
16771   unsigned int allocated_attrs;
16772
16773   abbrev_table = XNEW (struct abbrev_table);
16774   abbrev_table->sect_off = sect_off;
16775   obstack_init (&abbrev_table->abbrev_obstack);
16776   abbrev_table->abbrevs =
16777     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16778                ABBREV_HASH_SIZE);
16779   memset (abbrev_table->abbrevs, 0,
16780           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16781
16782   dwarf2_read_section (objfile, section);
16783   abbrev_ptr = section->buffer + to_underlying (sect_off);
16784   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16785   abbrev_ptr += bytes_read;
16786
16787   allocated_attrs = ATTR_ALLOC_CHUNK;
16788   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16789
16790   /* Loop until we reach an abbrev number of 0.  */
16791   while (abbrev_number)
16792     {
16793       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16794
16795       /* read in abbrev header */
16796       cur_abbrev->number = abbrev_number;
16797       cur_abbrev->tag
16798         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16799       abbrev_ptr += bytes_read;
16800       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16801       abbrev_ptr += 1;
16802
16803       /* now read in declarations */
16804       for (;;)
16805         {
16806           LONGEST implicit_const;
16807
16808           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16809           abbrev_ptr += bytes_read;
16810           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16811           abbrev_ptr += bytes_read;
16812           if (abbrev_form == DW_FORM_implicit_const)
16813             {
16814               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16815                                                    &bytes_read);
16816               abbrev_ptr += bytes_read;
16817             }
16818           else
16819             {
16820               /* Initialize it due to a false compiler warning.  */
16821               implicit_const = -1;
16822             }
16823
16824           if (abbrev_name == 0)
16825             break;
16826
16827           if (cur_abbrev->num_attrs == allocated_attrs)
16828             {
16829               allocated_attrs += ATTR_ALLOC_CHUNK;
16830               cur_attrs
16831                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16832             }
16833
16834           cur_attrs[cur_abbrev->num_attrs].name
16835             = (enum dwarf_attribute) abbrev_name;
16836           cur_attrs[cur_abbrev->num_attrs].form
16837             = (enum dwarf_form) abbrev_form;
16838           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16839           ++cur_abbrev->num_attrs;
16840         }
16841
16842       cur_abbrev->attrs =
16843         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16844                    cur_abbrev->num_attrs);
16845       memcpy (cur_abbrev->attrs, cur_attrs,
16846               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16847
16848       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16849
16850       /* Get next abbreviation.
16851          Under Irix6 the abbreviations for a compilation unit are not
16852          always properly terminated with an abbrev number of 0.
16853          Exit loop if we encounter an abbreviation which we have
16854          already read (which means we are about to read the abbreviations
16855          for the next compile unit) or if the end of the abbreviation
16856          table is reached.  */
16857       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16858         break;
16859       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16860       abbrev_ptr += bytes_read;
16861       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16862         break;
16863     }
16864
16865   xfree (cur_attrs);
16866   return abbrev_table;
16867 }
16868
16869 /* Free the resources held by ABBREV_TABLE.  */
16870
16871 static void
16872 abbrev_table_free (struct abbrev_table *abbrev_table)
16873 {
16874   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16875   xfree (abbrev_table);
16876 }
16877
16878 /* Same as abbrev_table_free but as a cleanup.
16879    We pass in a pointer to the pointer to the table so that we can
16880    set the pointer to NULL when we're done.  It also simplifies
16881    build_type_psymtabs_1.  */
16882
16883 static void
16884 abbrev_table_free_cleanup (void *table_ptr)
16885 {
16886   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16887
16888   if (*abbrev_table_ptr != NULL)
16889     abbrev_table_free (*abbrev_table_ptr);
16890   *abbrev_table_ptr = NULL;
16891 }
16892
16893 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16894
16895 static void
16896 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16897                      struct dwarf2_section_info *abbrev_section)
16898 {
16899   cu->abbrev_table =
16900     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16901 }
16902
16903 /* Release the memory used by the abbrev table for a compilation unit.  */
16904
16905 static void
16906 dwarf2_free_abbrev_table (void *ptr_to_cu)
16907 {
16908   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16909
16910   if (cu->abbrev_table != NULL)
16911     abbrev_table_free (cu->abbrev_table);
16912   /* Set this to NULL so that we SEGV if we try to read it later,
16913      and also because free_comp_unit verifies this is NULL.  */
16914   cu->abbrev_table = NULL;
16915 }
16916 \f
16917 /* Returns nonzero if TAG represents a type that we might generate a partial
16918    symbol for.  */
16919
16920 static int
16921 is_type_tag_for_partial (int tag)
16922 {
16923   switch (tag)
16924     {
16925 #if 0
16926     /* Some types that would be reasonable to generate partial symbols for,
16927        that we don't at present.  */
16928     case DW_TAG_array_type:
16929     case DW_TAG_file_type:
16930     case DW_TAG_ptr_to_member_type:
16931     case DW_TAG_set_type:
16932     case DW_TAG_string_type:
16933     case DW_TAG_subroutine_type:
16934 #endif
16935     case DW_TAG_base_type:
16936     case DW_TAG_class_type:
16937     case DW_TAG_interface_type:
16938     case DW_TAG_enumeration_type:
16939     case DW_TAG_structure_type:
16940     case DW_TAG_subrange_type:
16941     case DW_TAG_typedef:
16942     case DW_TAG_union_type:
16943       return 1;
16944     default:
16945       return 0;
16946     }
16947 }
16948
16949 /* Load all DIEs that are interesting for partial symbols into memory.  */
16950
16951 static struct partial_die_info *
16952 load_partial_dies (const struct die_reader_specs *reader,
16953                    const gdb_byte *info_ptr, int building_psymtab)
16954 {
16955   struct dwarf2_cu *cu = reader->cu;
16956   struct objfile *objfile = cu->objfile;
16957   struct partial_die_info *part_die;
16958   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16959   struct abbrev_info *abbrev;
16960   unsigned int bytes_read;
16961   unsigned int load_all = 0;
16962   int nesting_level = 1;
16963
16964   parent_die = NULL;
16965   last_die = NULL;
16966
16967   gdb_assert (cu->per_cu != NULL);
16968   if (cu->per_cu->load_all_dies)
16969     load_all = 1;
16970
16971   cu->partial_dies
16972     = htab_create_alloc_ex (cu->header.length / 12,
16973                             partial_die_hash,
16974                             partial_die_eq,
16975                             NULL,
16976                             &cu->comp_unit_obstack,
16977                             hashtab_obstack_allocate,
16978                             dummy_obstack_deallocate);
16979
16980   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16981
16982   while (1)
16983     {
16984       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16985
16986       /* A NULL abbrev means the end of a series of children.  */
16987       if (abbrev == NULL)
16988         {
16989           if (--nesting_level == 0)
16990             {
16991               /* PART_DIE was probably the last thing allocated on the
16992                  comp_unit_obstack, so we could call obstack_free
16993                  here.  We don't do that because the waste is small,
16994                  and will be cleaned up when we're done with this
16995                  compilation unit.  This way, we're also more robust
16996                  against other users of the comp_unit_obstack.  */
16997               return first_die;
16998             }
16999           info_ptr += bytes_read;
17000           last_die = parent_die;
17001           parent_die = parent_die->die_parent;
17002           continue;
17003         }
17004
17005       /* Check for template arguments.  We never save these; if
17006          they're seen, we just mark the parent, and go on our way.  */
17007       if (parent_die != NULL
17008           && cu->language == language_cplus
17009           && (abbrev->tag == DW_TAG_template_type_param
17010               || abbrev->tag == DW_TAG_template_value_param))
17011         {
17012           parent_die->has_template_arguments = 1;
17013
17014           if (!load_all)
17015             {
17016               /* We don't need a partial DIE for the template argument.  */
17017               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17018               continue;
17019             }
17020         }
17021
17022       /* We only recurse into c++ subprograms looking for template arguments.
17023          Skip their other children.  */
17024       if (!load_all
17025           && cu->language == language_cplus
17026           && parent_die != NULL
17027           && parent_die->tag == DW_TAG_subprogram)
17028         {
17029           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17030           continue;
17031         }
17032
17033       /* Check whether this DIE is interesting enough to save.  Normally
17034          we would not be interested in members here, but there may be
17035          later variables referencing them via DW_AT_specification (for
17036          static members).  */
17037       if (!load_all
17038           && !is_type_tag_for_partial (abbrev->tag)
17039           && abbrev->tag != DW_TAG_constant
17040           && abbrev->tag != DW_TAG_enumerator
17041           && abbrev->tag != DW_TAG_subprogram
17042           && abbrev->tag != DW_TAG_lexical_block
17043           && abbrev->tag != DW_TAG_variable
17044           && abbrev->tag != DW_TAG_namespace
17045           && abbrev->tag != DW_TAG_module
17046           && abbrev->tag != DW_TAG_member
17047           && abbrev->tag != DW_TAG_imported_unit
17048           && abbrev->tag != DW_TAG_imported_declaration)
17049         {
17050           /* Otherwise we skip to the next sibling, if any.  */
17051           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17052           continue;
17053         }
17054
17055       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
17056                                    info_ptr);
17057
17058       /* This two-pass algorithm for processing partial symbols has a
17059          high cost in cache pressure.  Thus, handle some simple cases
17060          here which cover the majority of C partial symbols.  DIEs
17061          which neither have specification tags in them, nor could have
17062          specification tags elsewhere pointing at them, can simply be
17063          processed and discarded.
17064
17065          This segment is also optional; scan_partial_symbols and
17066          add_partial_symbol will handle these DIEs if we chain
17067          them in normally.  When compilers which do not emit large
17068          quantities of duplicate debug information are more common,
17069          this code can probably be removed.  */
17070
17071       /* Any complete simple types at the top level (pretty much all
17072          of them, for a language without namespaces), can be processed
17073          directly.  */
17074       if (parent_die == NULL
17075           && part_die->has_specification == 0
17076           && part_die->is_declaration == 0
17077           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
17078               || part_die->tag == DW_TAG_base_type
17079               || part_die->tag == DW_TAG_subrange_type))
17080         {
17081           if (building_psymtab && part_die->name != NULL)
17082             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17083                                  VAR_DOMAIN, LOC_TYPEDEF,
17084                                  &objfile->static_psymbols,
17085                                  0, cu->language, objfile);
17086           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17087           continue;
17088         }
17089
17090       /* The exception for DW_TAG_typedef with has_children above is
17091          a workaround of GCC PR debug/47510.  In the case of this complaint
17092          type_name_no_tag_or_error will error on such types later.
17093
17094          GDB skipped children of DW_TAG_typedef by the shortcut above and then
17095          it could not find the child DIEs referenced later, this is checked
17096          above.  In correct DWARF DW_TAG_typedef should have no children.  */
17097
17098       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
17099         complaint (&symfile_complaints,
17100                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
17101                      "- DIE at 0x%x [in module %s]"),
17102                    to_underlying (part_die->sect_off), objfile_name (objfile));
17103
17104       /* If we're at the second level, and we're an enumerator, and
17105          our parent has no specification (meaning possibly lives in a
17106          namespace elsewhere), then we can add the partial symbol now
17107          instead of queueing it.  */
17108       if (part_die->tag == DW_TAG_enumerator
17109           && parent_die != NULL
17110           && parent_die->die_parent == NULL
17111           && parent_die->tag == DW_TAG_enumeration_type
17112           && parent_die->has_specification == 0)
17113         {
17114           if (part_die->name == NULL)
17115             complaint (&symfile_complaints,
17116                        _("malformed enumerator DIE ignored"));
17117           else if (building_psymtab)
17118             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17119                                  VAR_DOMAIN, LOC_CONST,
17120                                  cu->language == language_cplus
17121                                  ? &objfile->global_psymbols
17122                                  : &objfile->static_psymbols,
17123                                  0, cu->language, objfile);
17124
17125           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17126           continue;
17127         }
17128
17129       /* We'll save this DIE so link it in.  */
17130       part_die->die_parent = parent_die;
17131       part_die->die_sibling = NULL;
17132       part_die->die_child = NULL;
17133
17134       if (last_die && last_die == parent_die)
17135         last_die->die_child = part_die;
17136       else if (last_die)
17137         last_die->die_sibling = part_die;
17138
17139       last_die = part_die;
17140
17141       if (first_die == NULL)
17142         first_die = part_die;
17143
17144       /* Maybe add the DIE to the hash table.  Not all DIEs that we
17145          find interesting need to be in the hash table, because we
17146          also have the parent/sibling/child chains; only those that we
17147          might refer to by offset later during partial symbol reading.
17148
17149          For now this means things that might have be the target of a
17150          DW_AT_specification, DW_AT_abstract_origin, or
17151          DW_AT_extension.  DW_AT_extension will refer only to
17152          namespaces; DW_AT_abstract_origin refers to functions (and
17153          many things under the function DIE, but we do not recurse
17154          into function DIEs during partial symbol reading) and
17155          possibly variables as well; DW_AT_specification refers to
17156          declarations.  Declarations ought to have the DW_AT_declaration
17157          flag.  It happens that GCC forgets to put it in sometimes, but
17158          only for functions, not for types.
17159
17160          Adding more things than necessary to the hash table is harmless
17161          except for the performance cost.  Adding too few will result in
17162          wasted time in find_partial_die, when we reread the compilation
17163          unit with load_all_dies set.  */
17164
17165       if (load_all
17166           || abbrev->tag == DW_TAG_constant
17167           || abbrev->tag == DW_TAG_subprogram
17168           || abbrev->tag == DW_TAG_variable
17169           || abbrev->tag == DW_TAG_namespace
17170           || part_die->is_declaration)
17171         {
17172           void **slot;
17173
17174           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
17175                                            to_underlying (part_die->sect_off),
17176                                            INSERT);
17177           *slot = part_die;
17178         }
17179
17180       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
17181
17182       /* For some DIEs we want to follow their children (if any).  For C
17183          we have no reason to follow the children of structures; for other
17184          languages we have to, so that we can get at method physnames
17185          to infer fully qualified class names, for DW_AT_specification,
17186          and for C++ template arguments.  For C++, we also look one level
17187          inside functions to find template arguments (if the name of the
17188          function does not already contain the template arguments).
17189
17190          For Ada, we need to scan the children of subprograms and lexical
17191          blocks as well because Ada allows the definition of nested
17192          entities that could be interesting for the debugger, such as
17193          nested subprograms for instance.  */
17194       if (last_die->has_children
17195           && (load_all
17196               || last_die->tag == DW_TAG_namespace
17197               || last_die->tag == DW_TAG_module
17198               || last_die->tag == DW_TAG_enumeration_type
17199               || (cu->language == language_cplus
17200                   && last_die->tag == DW_TAG_subprogram
17201                   && (last_die->name == NULL
17202                       || strchr (last_die->name, '<') == NULL))
17203               || (cu->language != language_c
17204                   && (last_die->tag == DW_TAG_class_type
17205                       || last_die->tag == DW_TAG_interface_type
17206                       || last_die->tag == DW_TAG_structure_type
17207                       || last_die->tag == DW_TAG_union_type))
17208               || (cu->language == language_ada
17209                   && (last_die->tag == DW_TAG_subprogram
17210                       || last_die->tag == DW_TAG_lexical_block))))
17211         {
17212           nesting_level++;
17213           parent_die = last_die;
17214           continue;
17215         }
17216
17217       /* Otherwise we skip to the next sibling, if any.  */
17218       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
17219
17220       /* Back to the top, do it again.  */
17221     }
17222 }
17223
17224 /* Read a minimal amount of information into the minimal die structure.  */
17225
17226 static const gdb_byte *
17227 read_partial_die (const struct die_reader_specs *reader,
17228                   struct partial_die_info *part_die,
17229                   struct abbrev_info *abbrev, unsigned int abbrev_len,
17230                   const gdb_byte *info_ptr)
17231 {
17232   struct dwarf2_cu *cu = reader->cu;
17233   struct objfile *objfile = cu->objfile;
17234   const gdb_byte *buffer = reader->buffer;
17235   unsigned int i;
17236   struct attribute attr;
17237   int has_low_pc_attr = 0;
17238   int has_high_pc_attr = 0;
17239   int high_pc_relative = 0;
17240
17241   memset (part_die, 0, sizeof (struct partial_die_info));
17242
17243   part_die->sect_off = (sect_offset) (info_ptr - buffer);
17244
17245   info_ptr += abbrev_len;
17246
17247   if (abbrev == NULL)
17248     return info_ptr;
17249
17250   part_die->tag = abbrev->tag;
17251   part_die->has_children = abbrev->has_children;
17252
17253   for (i = 0; i < abbrev->num_attrs; ++i)
17254     {
17255       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
17256
17257       /* Store the data if it is of an attribute we want to keep in a
17258          partial symbol table.  */
17259       switch (attr.name)
17260         {
17261         case DW_AT_name:
17262           switch (part_die->tag)
17263             {
17264             case DW_TAG_compile_unit:
17265             case DW_TAG_partial_unit:
17266             case DW_TAG_type_unit:
17267               /* Compilation units have a DW_AT_name that is a filename, not
17268                  a source language identifier.  */
17269             case DW_TAG_enumeration_type:
17270             case DW_TAG_enumerator:
17271               /* These tags always have simple identifiers already; no need
17272                  to canonicalize them.  */
17273               part_die->name = DW_STRING (&attr);
17274               break;
17275             default:
17276               part_die->name
17277                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
17278                                             &objfile->per_bfd->storage_obstack);
17279               break;
17280             }
17281           break;
17282         case DW_AT_linkage_name:
17283         case DW_AT_MIPS_linkage_name:
17284           /* Note that both forms of linkage name might appear.  We
17285              assume they will be the same, and we only store the last
17286              one we see.  */
17287           if (cu->language == language_ada)
17288             part_die->name = DW_STRING (&attr);
17289           part_die->linkage_name = DW_STRING (&attr);
17290           break;
17291         case DW_AT_low_pc:
17292           has_low_pc_attr = 1;
17293           part_die->lowpc = attr_value_as_address (&attr);
17294           break;
17295         case DW_AT_high_pc:
17296           has_high_pc_attr = 1;
17297           part_die->highpc = attr_value_as_address (&attr);
17298           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
17299                 high_pc_relative = 1;
17300           break;
17301         case DW_AT_location:
17302           /* Support the .debug_loc offsets.  */
17303           if (attr_form_is_block (&attr))
17304             {
17305                part_die->d.locdesc = DW_BLOCK (&attr);
17306             }
17307           else if (attr_form_is_section_offset (&attr))
17308             {
17309               dwarf2_complex_location_expr_complaint ();
17310             }
17311           else
17312             {
17313               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17314                                                      "partial symbol information");
17315             }
17316           break;
17317         case DW_AT_external:
17318           part_die->is_external = DW_UNSND (&attr);
17319           break;
17320         case DW_AT_declaration:
17321           part_die->is_declaration = DW_UNSND (&attr);
17322           break;
17323         case DW_AT_type:
17324           part_die->has_type = 1;
17325           break;
17326         case DW_AT_abstract_origin:
17327         case DW_AT_specification:
17328         case DW_AT_extension:
17329           part_die->has_specification = 1;
17330           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
17331           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17332                                    || cu->per_cu->is_dwz);
17333           break;
17334         case DW_AT_sibling:
17335           /* Ignore absolute siblings, they might point outside of
17336              the current compile unit.  */
17337           if (attr.form == DW_FORM_ref_addr)
17338             complaint (&symfile_complaints,
17339                        _("ignoring absolute DW_AT_sibling"));
17340           else
17341             {
17342               sect_offset off = dwarf2_get_ref_die_offset (&attr);
17343               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
17344
17345               if (sibling_ptr < info_ptr)
17346                 complaint (&symfile_complaints,
17347                            _("DW_AT_sibling points backwards"));
17348               else if (sibling_ptr > reader->buffer_end)
17349                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
17350               else
17351                 part_die->sibling = sibling_ptr;
17352             }
17353           break;
17354         case DW_AT_byte_size:
17355           part_die->has_byte_size = 1;
17356           break;
17357         case DW_AT_const_value:
17358           part_die->has_const_value = 1;
17359           break;
17360         case DW_AT_calling_convention:
17361           /* DWARF doesn't provide a way to identify a program's source-level
17362              entry point.  DW_AT_calling_convention attributes are only meant
17363              to describe functions' calling conventions.
17364
17365              However, because it's a necessary piece of information in
17366              Fortran, and before DWARF 4 DW_CC_program was the only
17367              piece of debugging information whose definition refers to
17368              a 'main program' at all, several compilers marked Fortran
17369              main programs with DW_CC_program --- even when those
17370              functions use the standard calling conventions.
17371
17372              Although DWARF now specifies a way to provide this
17373              information, we support this practice for backward
17374              compatibility.  */
17375           if (DW_UNSND (&attr) == DW_CC_program
17376               && cu->language == language_fortran)
17377             part_die->main_subprogram = 1;
17378           break;
17379         case DW_AT_inline:
17380           if (DW_UNSND (&attr) == DW_INL_inlined
17381               || DW_UNSND (&attr) == DW_INL_declared_inlined)
17382             part_die->may_be_inlined = 1;
17383           break;
17384
17385         case DW_AT_import:
17386           if (part_die->tag == DW_TAG_imported_unit)
17387             {
17388               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
17389               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17390                                   || cu->per_cu->is_dwz);
17391             }
17392           break;
17393
17394         case DW_AT_main_subprogram:
17395           part_die->main_subprogram = DW_UNSND (&attr);
17396           break;
17397
17398         default:
17399           break;
17400         }
17401     }
17402
17403   if (high_pc_relative)
17404     part_die->highpc += part_die->lowpc;
17405
17406   if (has_low_pc_attr && has_high_pc_attr)
17407     {
17408       /* When using the GNU linker, .gnu.linkonce. sections are used to
17409          eliminate duplicate copies of functions and vtables and such.
17410          The linker will arbitrarily choose one and discard the others.
17411          The AT_*_pc values for such functions refer to local labels in
17412          these sections.  If the section from that file was discarded, the
17413          labels are not in the output, so the relocs get a value of 0.
17414          If this is a discarded function, mark the pc bounds as invalid,
17415          so that GDB will ignore it.  */
17416       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
17417         {
17418           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17419
17420           complaint (&symfile_complaints,
17421                      _("DW_AT_low_pc %s is zero "
17422                        "for DIE at 0x%x [in module %s]"),
17423                      paddress (gdbarch, part_die->lowpc),
17424                      to_underlying (part_die->sect_off), objfile_name (objfile));
17425         }
17426       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
17427       else if (part_die->lowpc >= part_die->highpc)
17428         {
17429           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17430
17431           complaint (&symfile_complaints,
17432                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
17433                        "for DIE at 0x%x [in module %s]"),
17434                      paddress (gdbarch, part_die->lowpc),
17435                      paddress (gdbarch, part_die->highpc),
17436                      to_underlying (part_die->sect_off),
17437                      objfile_name (objfile));
17438         }
17439       else
17440         part_die->has_pc_info = 1;
17441     }
17442
17443   return info_ptr;
17444 }
17445
17446 /* Find a cached partial DIE at OFFSET in CU.  */
17447
17448 static struct partial_die_info *
17449 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
17450 {
17451   struct partial_die_info *lookup_die = NULL;
17452   struct partial_die_info part_die;
17453
17454   part_die.sect_off = sect_off;
17455   lookup_die = ((struct partial_die_info *)
17456                 htab_find_with_hash (cu->partial_dies, &part_die,
17457                                      to_underlying (sect_off)));
17458
17459   return lookup_die;
17460 }
17461
17462 /* Find a partial DIE at OFFSET, which may or may not be in CU,
17463    except in the case of .debug_types DIEs which do not reference
17464    outside their CU (they do however referencing other types via
17465    DW_FORM_ref_sig8).  */
17466
17467 static struct partial_die_info *
17468 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
17469 {
17470   struct objfile *objfile = cu->objfile;
17471   struct dwarf2_per_cu_data *per_cu = NULL;
17472   struct partial_die_info *pd = NULL;
17473
17474   if (offset_in_dwz == cu->per_cu->is_dwz
17475       && offset_in_cu_p (&cu->header, sect_off))
17476     {
17477       pd = find_partial_die_in_comp_unit (sect_off, cu);
17478       if (pd != NULL)
17479         return pd;
17480       /* We missed recording what we needed.
17481          Load all dies and try again.  */
17482       per_cu = cu->per_cu;
17483     }
17484   else
17485     {
17486       /* TUs don't reference other CUs/TUs (except via type signatures).  */
17487       if (cu->per_cu->is_debug_types)
17488         {
17489           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
17490                    " external reference to offset 0x%x [in module %s].\n"),
17491                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
17492                  bfd_get_filename (objfile->obfd));
17493         }
17494       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
17495                                                  objfile);
17496
17497       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
17498         load_partial_comp_unit (per_cu);
17499
17500       per_cu->cu->last_used = 0;
17501       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17502     }
17503
17504   /* If we didn't find it, and not all dies have been loaded,
17505      load them all and try again.  */
17506
17507   if (pd == NULL && per_cu->load_all_dies == 0)
17508     {
17509       per_cu->load_all_dies = 1;
17510
17511       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
17512          THIS_CU->cu may already be in use.  So we can't just free it and
17513          replace its DIEs with the ones we read in.  Instead, we leave those
17514          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
17515          and clobber THIS_CU->cu->partial_dies with the hash table for the new
17516          set.  */
17517       load_partial_comp_unit (per_cu);
17518
17519       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17520     }
17521
17522   if (pd == NULL)
17523     internal_error (__FILE__, __LINE__,
17524                     _("could not find partial DIE 0x%x "
17525                       "in cache [from module %s]\n"),
17526                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
17527   return pd;
17528 }
17529
17530 /* See if we can figure out if the class lives in a namespace.  We do
17531    this by looking for a member function; its demangled name will
17532    contain namespace info, if there is any.  */
17533
17534 static void
17535 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
17536                                   struct dwarf2_cu *cu)
17537 {
17538   /* NOTE: carlton/2003-10-07: Getting the info this way changes
17539      what template types look like, because the demangler
17540      frequently doesn't give the same name as the debug info.  We
17541      could fix this by only using the demangled name to get the
17542      prefix (but see comment in read_structure_type).  */
17543
17544   struct partial_die_info *real_pdi;
17545   struct partial_die_info *child_pdi;
17546
17547   /* If this DIE (this DIE's specification, if any) has a parent, then
17548      we should not do this.  We'll prepend the parent's fully qualified
17549      name when we create the partial symbol.  */
17550
17551   real_pdi = struct_pdi;
17552   while (real_pdi->has_specification)
17553     real_pdi = find_partial_die (real_pdi->spec_offset,
17554                                  real_pdi->spec_is_dwz, cu);
17555
17556   if (real_pdi->die_parent != NULL)
17557     return;
17558
17559   for (child_pdi = struct_pdi->die_child;
17560        child_pdi != NULL;
17561        child_pdi = child_pdi->die_sibling)
17562     {
17563       if (child_pdi->tag == DW_TAG_subprogram
17564           && child_pdi->linkage_name != NULL)
17565         {
17566           char *actual_class_name
17567             = language_class_name_from_physname (cu->language_defn,
17568                                                  child_pdi->linkage_name);
17569           if (actual_class_name != NULL)
17570             {
17571               struct_pdi->name
17572                 = ((const char *)
17573                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17574                                   actual_class_name,
17575                                   strlen (actual_class_name)));
17576               xfree (actual_class_name);
17577             }
17578           break;
17579         }
17580     }
17581 }
17582
17583 /* Adjust PART_DIE before generating a symbol for it.  This function
17584    may set the is_external flag or change the DIE's name.  */
17585
17586 static void
17587 fixup_partial_die (struct partial_die_info *part_die,
17588                    struct dwarf2_cu *cu)
17589 {
17590   /* Once we've fixed up a die, there's no point in doing so again.
17591      This also avoids a memory leak if we were to call
17592      guess_partial_die_structure_name multiple times.  */
17593   if (part_die->fixup_called)
17594     return;
17595
17596   /* If we found a reference attribute and the DIE has no name, try
17597      to find a name in the referred to DIE.  */
17598
17599   if (part_die->name == NULL && part_die->has_specification)
17600     {
17601       struct partial_die_info *spec_die;
17602
17603       spec_die = find_partial_die (part_die->spec_offset,
17604                                    part_die->spec_is_dwz, cu);
17605
17606       fixup_partial_die (spec_die, cu);
17607
17608       if (spec_die->name)
17609         {
17610           part_die->name = spec_die->name;
17611
17612           /* Copy DW_AT_external attribute if it is set.  */
17613           if (spec_die->is_external)
17614             part_die->is_external = spec_die->is_external;
17615         }
17616     }
17617
17618   /* Set default names for some unnamed DIEs.  */
17619
17620   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
17621     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
17622
17623   /* If there is no parent die to provide a namespace, and there are
17624      children, see if we can determine the namespace from their linkage
17625      name.  */
17626   if (cu->language == language_cplus
17627       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17628       && part_die->die_parent == NULL
17629       && part_die->has_children
17630       && (part_die->tag == DW_TAG_class_type
17631           || part_die->tag == DW_TAG_structure_type
17632           || part_die->tag == DW_TAG_union_type))
17633     guess_partial_die_structure_name (part_die, cu);
17634
17635   /* GCC might emit a nameless struct or union that has a linkage
17636      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17637   if (part_die->name == NULL
17638       && (part_die->tag == DW_TAG_class_type
17639           || part_die->tag == DW_TAG_interface_type
17640           || part_die->tag == DW_TAG_structure_type
17641           || part_die->tag == DW_TAG_union_type)
17642       && part_die->linkage_name != NULL)
17643     {
17644       char *demangled;
17645
17646       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
17647       if (demangled)
17648         {
17649           const char *base;
17650
17651           /* Strip any leading namespaces/classes, keep only the base name.
17652              DW_AT_name for named DIEs does not contain the prefixes.  */
17653           base = strrchr (demangled, ':');
17654           if (base && base > demangled && base[-1] == ':')
17655             base++;
17656           else
17657             base = demangled;
17658
17659           part_die->name
17660             = ((const char *)
17661                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17662                               base, strlen (base)));
17663           xfree (demangled);
17664         }
17665     }
17666
17667   part_die->fixup_called = 1;
17668 }
17669
17670 /* Read an attribute value described by an attribute form.  */
17671
17672 static const gdb_byte *
17673 read_attribute_value (const struct die_reader_specs *reader,
17674                       struct attribute *attr, unsigned form,
17675                       LONGEST implicit_const, const gdb_byte *info_ptr)
17676 {
17677   struct dwarf2_cu *cu = reader->cu;
17678   struct objfile *objfile = cu->objfile;
17679   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17680   bfd *abfd = reader->abfd;
17681   struct comp_unit_head *cu_header = &cu->header;
17682   unsigned int bytes_read;
17683   struct dwarf_block *blk;
17684
17685   attr->form = (enum dwarf_form) form;
17686   switch (form)
17687     {
17688     case DW_FORM_ref_addr:
17689       if (cu->header.version == 2)
17690         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17691       else
17692         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17693                                        &cu->header, &bytes_read);
17694       info_ptr += bytes_read;
17695       break;
17696     case DW_FORM_GNU_ref_alt:
17697       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17698       info_ptr += bytes_read;
17699       break;
17700     case DW_FORM_addr:
17701       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17702       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17703       info_ptr += bytes_read;
17704       break;
17705     case DW_FORM_block2:
17706       blk = dwarf_alloc_block (cu);
17707       blk->size = read_2_bytes (abfd, info_ptr);
17708       info_ptr += 2;
17709       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17710       info_ptr += blk->size;
17711       DW_BLOCK (attr) = blk;
17712       break;
17713     case DW_FORM_block4:
17714       blk = dwarf_alloc_block (cu);
17715       blk->size = read_4_bytes (abfd, info_ptr);
17716       info_ptr += 4;
17717       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17718       info_ptr += blk->size;
17719       DW_BLOCK (attr) = blk;
17720       break;
17721     case DW_FORM_data2:
17722       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17723       info_ptr += 2;
17724       break;
17725     case DW_FORM_data4:
17726       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17727       info_ptr += 4;
17728       break;
17729     case DW_FORM_data8:
17730       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17731       info_ptr += 8;
17732       break;
17733     case DW_FORM_data16:
17734       blk = dwarf_alloc_block (cu);
17735       blk->size = 16;
17736       blk->data = read_n_bytes (abfd, info_ptr, 16);
17737       info_ptr += 16;
17738       DW_BLOCK (attr) = blk;
17739       break;
17740     case DW_FORM_sec_offset:
17741       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17742       info_ptr += bytes_read;
17743       break;
17744     case DW_FORM_string:
17745       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17746       DW_STRING_IS_CANONICAL (attr) = 0;
17747       info_ptr += bytes_read;
17748       break;
17749     case DW_FORM_strp:
17750       if (!cu->per_cu->is_dwz)
17751         {
17752           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17753                                                    &bytes_read);
17754           DW_STRING_IS_CANONICAL (attr) = 0;
17755           info_ptr += bytes_read;
17756           break;
17757         }
17758       /* FALLTHROUGH */
17759     case DW_FORM_line_strp:
17760       if (!cu->per_cu->is_dwz)
17761         {
17762           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17763                                                         cu_header, &bytes_read);
17764           DW_STRING_IS_CANONICAL (attr) = 0;
17765           info_ptr += bytes_read;
17766           break;
17767         }
17768       /* FALLTHROUGH */
17769     case DW_FORM_GNU_strp_alt:
17770       {
17771         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17772         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17773                                           &bytes_read);
17774
17775         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17776         DW_STRING_IS_CANONICAL (attr) = 0;
17777         info_ptr += bytes_read;
17778       }
17779       break;
17780     case DW_FORM_exprloc:
17781     case DW_FORM_block:
17782       blk = dwarf_alloc_block (cu);
17783       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17784       info_ptr += bytes_read;
17785       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17786       info_ptr += blk->size;
17787       DW_BLOCK (attr) = blk;
17788       break;
17789     case DW_FORM_block1:
17790       blk = dwarf_alloc_block (cu);
17791       blk->size = read_1_byte (abfd, info_ptr);
17792       info_ptr += 1;
17793       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17794       info_ptr += blk->size;
17795       DW_BLOCK (attr) = blk;
17796       break;
17797     case DW_FORM_data1:
17798       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17799       info_ptr += 1;
17800       break;
17801     case DW_FORM_flag:
17802       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17803       info_ptr += 1;
17804       break;
17805     case DW_FORM_flag_present:
17806       DW_UNSND (attr) = 1;
17807       break;
17808     case DW_FORM_sdata:
17809       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17810       info_ptr += bytes_read;
17811       break;
17812     case DW_FORM_udata:
17813       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17814       info_ptr += bytes_read;
17815       break;
17816     case DW_FORM_ref1:
17817       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17818                          + read_1_byte (abfd, info_ptr));
17819       info_ptr += 1;
17820       break;
17821     case DW_FORM_ref2:
17822       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17823                          + read_2_bytes (abfd, info_ptr));
17824       info_ptr += 2;
17825       break;
17826     case DW_FORM_ref4:
17827       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17828                          + read_4_bytes (abfd, info_ptr));
17829       info_ptr += 4;
17830       break;
17831     case DW_FORM_ref8:
17832       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17833                          + read_8_bytes (abfd, info_ptr));
17834       info_ptr += 8;
17835       break;
17836     case DW_FORM_ref_sig8:
17837       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17838       info_ptr += 8;
17839       break;
17840     case DW_FORM_ref_udata:
17841       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17842                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17843       info_ptr += bytes_read;
17844       break;
17845     case DW_FORM_indirect:
17846       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17847       info_ptr += bytes_read;
17848       if (form == DW_FORM_implicit_const)
17849         {
17850           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17851           info_ptr += bytes_read;
17852         }
17853       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17854                                        info_ptr);
17855       break;
17856     case DW_FORM_implicit_const:
17857       DW_SND (attr) = implicit_const;
17858       break;
17859     case DW_FORM_GNU_addr_index:
17860       if (reader->dwo_file == NULL)
17861         {
17862           /* For now flag a hard error.
17863              Later we can turn this into a complaint.  */
17864           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17865                  dwarf_form_name (form),
17866                  bfd_get_filename (abfd));
17867         }
17868       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17869       info_ptr += bytes_read;
17870       break;
17871     case DW_FORM_GNU_str_index:
17872       if (reader->dwo_file == NULL)
17873         {
17874           /* For now flag a hard error.
17875              Later we can turn this into a complaint if warranted.  */
17876           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17877                  dwarf_form_name (form),
17878                  bfd_get_filename (abfd));
17879         }
17880       {
17881         ULONGEST str_index =
17882           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17883
17884         DW_STRING (attr) = read_str_index (reader, str_index);
17885         DW_STRING_IS_CANONICAL (attr) = 0;
17886         info_ptr += bytes_read;
17887       }
17888       break;
17889     default:
17890       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17891              dwarf_form_name (form),
17892              bfd_get_filename (abfd));
17893     }
17894
17895   /* Super hack.  */
17896   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17897     attr->form = DW_FORM_GNU_ref_alt;
17898
17899   /* We have seen instances where the compiler tried to emit a byte
17900      size attribute of -1 which ended up being encoded as an unsigned
17901      0xffffffff.  Although 0xffffffff is technically a valid size value,
17902      an object of this size seems pretty unlikely so we can relatively
17903      safely treat these cases as if the size attribute was invalid and
17904      treat them as zero by default.  */
17905   if (attr->name == DW_AT_byte_size
17906       && form == DW_FORM_data4
17907       && DW_UNSND (attr) >= 0xffffffff)
17908     {
17909       complaint
17910         (&symfile_complaints,
17911          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17912          hex_string (DW_UNSND (attr)));
17913       DW_UNSND (attr) = 0;
17914     }
17915
17916   return info_ptr;
17917 }
17918
17919 /* Read an attribute described by an abbreviated attribute.  */
17920
17921 static const gdb_byte *
17922 read_attribute (const struct die_reader_specs *reader,
17923                 struct attribute *attr, struct attr_abbrev *abbrev,
17924                 const gdb_byte *info_ptr)
17925 {
17926   attr->name = abbrev->name;
17927   return read_attribute_value (reader, attr, abbrev->form,
17928                                abbrev->implicit_const, info_ptr);
17929 }
17930
17931 /* Read dwarf information from a buffer.  */
17932
17933 static unsigned int
17934 read_1_byte (bfd *abfd, const gdb_byte *buf)
17935 {
17936   return bfd_get_8 (abfd, buf);
17937 }
17938
17939 static int
17940 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17941 {
17942   return bfd_get_signed_8 (abfd, buf);
17943 }
17944
17945 static unsigned int
17946 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17947 {
17948   return bfd_get_16 (abfd, buf);
17949 }
17950
17951 static int
17952 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17953 {
17954   return bfd_get_signed_16 (abfd, buf);
17955 }
17956
17957 static unsigned int
17958 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17959 {
17960   return bfd_get_32 (abfd, buf);
17961 }
17962
17963 static int
17964 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17965 {
17966   return bfd_get_signed_32 (abfd, buf);
17967 }
17968
17969 static ULONGEST
17970 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17971 {
17972   return bfd_get_64 (abfd, buf);
17973 }
17974
17975 static CORE_ADDR
17976 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17977               unsigned int *bytes_read)
17978 {
17979   struct comp_unit_head *cu_header = &cu->header;
17980   CORE_ADDR retval = 0;
17981
17982   if (cu_header->signed_addr_p)
17983     {
17984       switch (cu_header->addr_size)
17985         {
17986         case 2:
17987           retval = bfd_get_signed_16 (abfd, buf);
17988           break;
17989         case 4:
17990           retval = bfd_get_signed_32 (abfd, buf);
17991           break;
17992         case 8:
17993           retval = bfd_get_signed_64 (abfd, buf);
17994           break;
17995         default:
17996           internal_error (__FILE__, __LINE__,
17997                           _("read_address: bad switch, signed [in module %s]"),
17998                           bfd_get_filename (abfd));
17999         }
18000     }
18001   else
18002     {
18003       switch (cu_header->addr_size)
18004         {
18005         case 2:
18006           retval = bfd_get_16 (abfd, buf);
18007           break;
18008         case 4:
18009           retval = bfd_get_32 (abfd, buf);
18010           break;
18011         case 8:
18012           retval = bfd_get_64 (abfd, buf);
18013           break;
18014         default:
18015           internal_error (__FILE__, __LINE__,
18016                           _("read_address: bad switch, "
18017                             "unsigned [in module %s]"),
18018                           bfd_get_filename (abfd));
18019         }
18020     }
18021
18022   *bytes_read = cu_header->addr_size;
18023   return retval;
18024 }
18025
18026 /* Read the initial length from a section.  The (draft) DWARF 3
18027    specification allows the initial length to take up either 4 bytes
18028    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
18029    bytes describe the length and all offsets will be 8 bytes in length
18030    instead of 4.
18031
18032    An older, non-standard 64-bit format is also handled by this
18033    function.  The older format in question stores the initial length
18034    as an 8-byte quantity without an escape value.  Lengths greater
18035    than 2^32 aren't very common which means that the initial 4 bytes
18036    is almost always zero.  Since a length value of zero doesn't make
18037    sense for the 32-bit format, this initial zero can be considered to
18038    be an escape value which indicates the presence of the older 64-bit
18039    format.  As written, the code can't detect (old format) lengths
18040    greater than 4GB.  If it becomes necessary to handle lengths
18041    somewhat larger than 4GB, we could allow other small values (such
18042    as the non-sensical values of 1, 2, and 3) to also be used as
18043    escape values indicating the presence of the old format.
18044
18045    The value returned via bytes_read should be used to increment the
18046    relevant pointer after calling read_initial_length().
18047
18048    [ Note:  read_initial_length() and read_offset() are based on the
18049      document entitled "DWARF Debugging Information Format", revision
18050      3, draft 8, dated November 19, 2001.  This document was obtained
18051      from:
18052
18053         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
18054
18055      This document is only a draft and is subject to change.  (So beware.)
18056
18057      Details regarding the older, non-standard 64-bit format were
18058      determined empirically by examining 64-bit ELF files produced by
18059      the SGI toolchain on an IRIX 6.5 machine.
18060
18061      - Kevin, July 16, 2002
18062    ] */
18063
18064 static LONGEST
18065 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
18066 {
18067   LONGEST length = bfd_get_32 (abfd, buf);
18068
18069   if (length == 0xffffffff)
18070     {
18071       length = bfd_get_64 (abfd, buf + 4);
18072       *bytes_read = 12;
18073     }
18074   else if (length == 0)
18075     {
18076       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
18077       length = bfd_get_64 (abfd, buf);
18078       *bytes_read = 8;
18079     }
18080   else
18081     {
18082       *bytes_read = 4;
18083     }
18084
18085   return length;
18086 }
18087
18088 /* Cover function for read_initial_length.
18089    Returns the length of the object at BUF, and stores the size of the
18090    initial length in *BYTES_READ and stores the size that offsets will be in
18091    *OFFSET_SIZE.
18092    If the initial length size is not equivalent to that specified in
18093    CU_HEADER then issue a complaint.
18094    This is useful when reading non-comp-unit headers.  */
18095
18096 static LONGEST
18097 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
18098                                         const struct comp_unit_head *cu_header,
18099                                         unsigned int *bytes_read,
18100                                         unsigned int *offset_size)
18101 {
18102   LONGEST length = read_initial_length (abfd, buf, bytes_read);
18103
18104   gdb_assert (cu_header->initial_length_size == 4
18105               || cu_header->initial_length_size == 8
18106               || cu_header->initial_length_size == 12);
18107
18108   if (cu_header->initial_length_size != *bytes_read)
18109     complaint (&symfile_complaints,
18110                _("intermixed 32-bit and 64-bit DWARF sections"));
18111
18112   *offset_size = (*bytes_read == 4) ? 4 : 8;
18113   return length;
18114 }
18115
18116 /* Read an offset from the data stream.  The size of the offset is
18117    given by cu_header->offset_size.  */
18118
18119 static LONGEST
18120 read_offset (bfd *abfd, const gdb_byte *buf,
18121              const struct comp_unit_head *cu_header,
18122              unsigned int *bytes_read)
18123 {
18124   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
18125
18126   *bytes_read = cu_header->offset_size;
18127   return offset;
18128 }
18129
18130 /* Read an offset from the data stream.  */
18131
18132 static LONGEST
18133 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
18134 {
18135   LONGEST retval = 0;
18136
18137   switch (offset_size)
18138     {
18139     case 4:
18140       retval = bfd_get_32 (abfd, buf);
18141       break;
18142     case 8:
18143       retval = bfd_get_64 (abfd, buf);
18144       break;
18145     default:
18146       internal_error (__FILE__, __LINE__,
18147                       _("read_offset_1: bad switch [in module %s]"),
18148                       bfd_get_filename (abfd));
18149     }
18150
18151   return retval;
18152 }
18153
18154 static const gdb_byte *
18155 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
18156 {
18157   /* If the size of a host char is 8 bits, we can return a pointer
18158      to the buffer, otherwise we have to copy the data to a buffer
18159      allocated on the temporary obstack.  */
18160   gdb_assert (HOST_CHAR_BIT == 8);
18161   return buf;
18162 }
18163
18164 static const char *
18165 read_direct_string (bfd *abfd, const gdb_byte *buf,
18166                     unsigned int *bytes_read_ptr)
18167 {
18168   /* If the size of a host char is 8 bits, we can return a pointer
18169      to the string, otherwise we have to copy the string to a buffer
18170      allocated on the temporary obstack.  */
18171   gdb_assert (HOST_CHAR_BIT == 8);
18172   if (*buf == '\0')
18173     {
18174       *bytes_read_ptr = 1;
18175       return NULL;
18176     }
18177   *bytes_read_ptr = strlen ((const char *) buf) + 1;
18178   return (const char *) buf;
18179 }
18180
18181 /* Return pointer to string at section SECT offset STR_OFFSET with error
18182    reporting strings FORM_NAME and SECT_NAME.  */
18183
18184 static const char *
18185 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
18186                                      struct dwarf2_section_info *sect,
18187                                      const char *form_name,
18188                                      const char *sect_name)
18189 {
18190   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
18191   if (sect->buffer == NULL)
18192     error (_("%s used without %s section [in module %s]"),
18193            form_name, sect_name, bfd_get_filename (abfd));
18194   if (str_offset >= sect->size)
18195     error (_("%s pointing outside of %s section [in module %s]"),
18196            form_name, sect_name, bfd_get_filename (abfd));
18197   gdb_assert (HOST_CHAR_BIT == 8);
18198   if (sect->buffer[str_offset] == '\0')
18199     return NULL;
18200   return (const char *) (sect->buffer + str_offset);
18201 }
18202
18203 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
18204
18205 static const char *
18206 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
18207 {
18208   return read_indirect_string_at_offset_from (abfd, str_offset,
18209                                               &dwarf2_per_objfile->str,
18210                                               "DW_FORM_strp", ".debug_str");
18211 }
18212
18213 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
18214
18215 static const char *
18216 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
18217 {
18218   return read_indirect_string_at_offset_from (abfd, str_offset,
18219                                               &dwarf2_per_objfile->line_str,
18220                                               "DW_FORM_line_strp",
18221                                               ".debug_line_str");
18222 }
18223
18224 /* Read a string at offset STR_OFFSET in the .debug_str section from
18225    the .dwz file DWZ.  Throw an error if the offset is too large.  If
18226    the string consists of a single NUL byte, return NULL; otherwise
18227    return a pointer to the string.  */
18228
18229 static const char *
18230 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
18231 {
18232   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
18233
18234   if (dwz->str.buffer == NULL)
18235     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
18236              "section [in module %s]"),
18237            bfd_get_filename (dwz->dwz_bfd));
18238   if (str_offset >= dwz->str.size)
18239     error (_("DW_FORM_GNU_strp_alt pointing outside of "
18240              ".debug_str section [in module %s]"),
18241            bfd_get_filename (dwz->dwz_bfd));
18242   gdb_assert (HOST_CHAR_BIT == 8);
18243   if (dwz->str.buffer[str_offset] == '\0')
18244     return NULL;
18245   return (const char *) (dwz->str.buffer + str_offset);
18246 }
18247
18248 /* Return pointer to string at .debug_str offset as read from BUF.
18249    BUF is assumed to be in a compilation unit described by CU_HEADER.
18250    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18251
18252 static const char *
18253 read_indirect_string (bfd *abfd, const gdb_byte *buf,
18254                       const struct comp_unit_head *cu_header,
18255                       unsigned int *bytes_read_ptr)
18256 {
18257   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18258
18259   return read_indirect_string_at_offset (abfd, str_offset);
18260 }
18261
18262 /* Return pointer to string at .debug_line_str offset as read from BUF.
18263    BUF is assumed to be in a compilation unit described by CU_HEADER.
18264    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18265
18266 static const char *
18267 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
18268                            const struct comp_unit_head *cu_header,
18269                            unsigned int *bytes_read_ptr)
18270 {
18271   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18272
18273   return read_indirect_line_string_at_offset (abfd, str_offset);
18274 }
18275
18276 ULONGEST
18277 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
18278                           unsigned int *bytes_read_ptr)
18279 {
18280   ULONGEST result;
18281   unsigned int num_read;
18282   int shift;
18283   unsigned char byte;
18284
18285   result = 0;
18286   shift = 0;
18287   num_read = 0;
18288   while (1)
18289     {
18290       byte = bfd_get_8 (abfd, buf);
18291       buf++;
18292       num_read++;
18293       result |= ((ULONGEST) (byte & 127) << shift);
18294       if ((byte & 128) == 0)
18295         {
18296           break;
18297         }
18298       shift += 7;
18299     }
18300   *bytes_read_ptr = num_read;
18301   return result;
18302 }
18303
18304 static LONGEST
18305 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
18306                     unsigned int *bytes_read_ptr)
18307 {
18308   LONGEST result;
18309   int shift, num_read;
18310   unsigned char byte;
18311
18312   result = 0;
18313   shift = 0;
18314   num_read = 0;
18315   while (1)
18316     {
18317       byte = bfd_get_8 (abfd, buf);
18318       buf++;
18319       num_read++;
18320       result |= ((LONGEST) (byte & 127) << shift);
18321       shift += 7;
18322       if ((byte & 128) == 0)
18323         {
18324           break;
18325         }
18326     }
18327   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
18328     result |= -(((LONGEST) 1) << shift);
18329   *bytes_read_ptr = num_read;
18330   return result;
18331 }
18332
18333 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
18334    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
18335    ADDR_SIZE is the size of addresses from the CU header.  */
18336
18337 static CORE_ADDR
18338 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
18339 {
18340   struct objfile *objfile = dwarf2_per_objfile->objfile;
18341   bfd *abfd = objfile->obfd;
18342   const gdb_byte *info_ptr;
18343
18344   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
18345   if (dwarf2_per_objfile->addr.buffer == NULL)
18346     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
18347            objfile_name (objfile));
18348   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
18349     error (_("DW_FORM_addr_index pointing outside of "
18350              ".debug_addr section [in module %s]"),
18351            objfile_name (objfile));
18352   info_ptr = (dwarf2_per_objfile->addr.buffer
18353               + addr_base + addr_index * addr_size);
18354   if (addr_size == 4)
18355     return bfd_get_32 (abfd, info_ptr);
18356   else
18357     return bfd_get_64 (abfd, info_ptr);
18358 }
18359
18360 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
18361
18362 static CORE_ADDR
18363 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
18364 {
18365   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
18366 }
18367
18368 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
18369
18370 static CORE_ADDR
18371 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
18372                              unsigned int *bytes_read)
18373 {
18374   bfd *abfd = cu->objfile->obfd;
18375   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
18376
18377   return read_addr_index (cu, addr_index);
18378 }
18379
18380 /* Data structure to pass results from dwarf2_read_addr_index_reader
18381    back to dwarf2_read_addr_index.  */
18382
18383 struct dwarf2_read_addr_index_data
18384 {
18385   ULONGEST addr_base;
18386   int addr_size;
18387 };
18388
18389 /* die_reader_func for dwarf2_read_addr_index.  */
18390
18391 static void
18392 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
18393                                const gdb_byte *info_ptr,
18394                                struct die_info *comp_unit_die,
18395                                int has_children,
18396                                void *data)
18397 {
18398   struct dwarf2_cu *cu = reader->cu;
18399   struct dwarf2_read_addr_index_data *aidata =
18400     (struct dwarf2_read_addr_index_data *) data;
18401
18402   aidata->addr_base = cu->addr_base;
18403   aidata->addr_size = cu->header.addr_size;
18404 }
18405
18406 /* Given an index in .debug_addr, fetch the value.
18407    NOTE: This can be called during dwarf expression evaluation,
18408    long after the debug information has been read, and thus per_cu->cu
18409    may no longer exist.  */
18410
18411 CORE_ADDR
18412 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
18413                         unsigned int addr_index)
18414 {
18415   struct objfile *objfile = per_cu->objfile;
18416   struct dwarf2_cu *cu = per_cu->cu;
18417   ULONGEST addr_base;
18418   int addr_size;
18419
18420   /* This is intended to be called from outside this file.  */
18421   dw2_setup (objfile);
18422
18423   /* We need addr_base and addr_size.
18424      If we don't have PER_CU->cu, we have to get it.
18425      Nasty, but the alternative is storing the needed info in PER_CU,
18426      which at this point doesn't seem justified: it's not clear how frequently
18427      it would get used and it would increase the size of every PER_CU.
18428      Entry points like dwarf2_per_cu_addr_size do a similar thing
18429      so we're not in uncharted territory here.
18430      Alas we need to be a bit more complicated as addr_base is contained
18431      in the DIE.
18432
18433      We don't need to read the entire CU(/TU).
18434      We just need the header and top level die.
18435
18436      IWBN to use the aging mechanism to let us lazily later discard the CU.
18437      For now we skip this optimization.  */
18438
18439   if (cu != NULL)
18440     {
18441       addr_base = cu->addr_base;
18442       addr_size = cu->header.addr_size;
18443     }
18444   else
18445     {
18446       struct dwarf2_read_addr_index_data aidata;
18447
18448       /* Note: We can't use init_cutu_and_read_dies_simple here,
18449          we need addr_base.  */
18450       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
18451                                dwarf2_read_addr_index_reader, &aidata);
18452       addr_base = aidata.addr_base;
18453       addr_size = aidata.addr_size;
18454     }
18455
18456   return read_addr_index_1 (addr_index, addr_base, addr_size);
18457 }
18458
18459 /* Given a DW_FORM_GNU_str_index, fetch the string.
18460    This is only used by the Fission support.  */
18461
18462 static const char *
18463 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
18464 {
18465   struct objfile *objfile = dwarf2_per_objfile->objfile;
18466   const char *objf_name = objfile_name (objfile);
18467   bfd *abfd = objfile->obfd;
18468   struct dwarf2_cu *cu = reader->cu;
18469   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
18470   struct dwarf2_section_info *str_offsets_section =
18471     &reader->dwo_file->sections.str_offsets;
18472   const gdb_byte *info_ptr;
18473   ULONGEST str_offset;
18474   static const char form_name[] = "DW_FORM_GNU_str_index";
18475
18476   dwarf2_read_section (objfile, str_section);
18477   dwarf2_read_section (objfile, str_offsets_section);
18478   if (str_section->buffer == NULL)
18479     error (_("%s used without .debug_str.dwo section"
18480              " in CU at offset 0x%x [in module %s]"),
18481            form_name, to_underlying (cu->header.sect_off), objf_name);
18482   if (str_offsets_section->buffer == NULL)
18483     error (_("%s used without .debug_str_offsets.dwo section"
18484              " in CU at offset 0x%x [in module %s]"),
18485            form_name, to_underlying (cu->header.sect_off), objf_name);
18486   if (str_index * cu->header.offset_size >= str_offsets_section->size)
18487     error (_("%s pointing outside of .debug_str_offsets.dwo"
18488              " section in CU at offset 0x%x [in module %s]"),
18489            form_name, to_underlying (cu->header.sect_off), objf_name);
18490   info_ptr = (str_offsets_section->buffer
18491               + str_index * cu->header.offset_size);
18492   if (cu->header.offset_size == 4)
18493     str_offset = bfd_get_32 (abfd, info_ptr);
18494   else
18495     str_offset = bfd_get_64 (abfd, info_ptr);
18496   if (str_offset >= str_section->size)
18497     error (_("Offset from %s pointing outside of"
18498              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
18499            form_name, to_underlying (cu->header.sect_off), objf_name);
18500   return (const char *) (str_section->buffer + str_offset);
18501 }
18502
18503 /* Return the length of an LEB128 number in BUF.  */
18504
18505 static int
18506 leb128_size (const gdb_byte *buf)
18507 {
18508   const gdb_byte *begin = buf;
18509   gdb_byte byte;
18510
18511   while (1)
18512     {
18513       byte = *buf++;
18514       if ((byte & 128) == 0)
18515         return buf - begin;
18516     }
18517 }
18518
18519 static void
18520 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
18521 {
18522   switch (lang)
18523     {
18524     case DW_LANG_C89:
18525     case DW_LANG_C99:
18526     case DW_LANG_C11:
18527     case DW_LANG_C:
18528     case DW_LANG_UPC:
18529       cu->language = language_c;
18530       break;
18531     case DW_LANG_Java:
18532     case DW_LANG_C_plus_plus:
18533     case DW_LANG_C_plus_plus_11:
18534     case DW_LANG_C_plus_plus_14:
18535       cu->language = language_cplus;
18536       break;
18537     case DW_LANG_D:
18538       cu->language = language_d;
18539       break;
18540     case DW_LANG_Fortran77:
18541     case DW_LANG_Fortran90:
18542     case DW_LANG_Fortran95:
18543     case DW_LANG_Fortran03:
18544     case DW_LANG_Fortran08:
18545       cu->language = language_fortran;
18546       break;
18547     case DW_LANG_Go:
18548       cu->language = language_go;
18549       break;
18550     case DW_LANG_Mips_Assembler:
18551       cu->language = language_asm;
18552       break;
18553     case DW_LANG_Ada83:
18554     case DW_LANG_Ada95:
18555       cu->language = language_ada;
18556       break;
18557     case DW_LANG_Modula2:
18558       cu->language = language_m2;
18559       break;
18560     case DW_LANG_Pascal83:
18561       cu->language = language_pascal;
18562       break;
18563     case DW_LANG_ObjC:
18564       cu->language = language_objc;
18565       break;
18566     case DW_LANG_Rust:
18567     case DW_LANG_Rust_old:
18568       cu->language = language_rust;
18569       break;
18570     case DW_LANG_Cobol74:
18571     case DW_LANG_Cobol85:
18572     default:
18573       cu->language = language_minimal;
18574       break;
18575     }
18576   cu->language_defn = language_def (cu->language);
18577 }
18578
18579 /* Return the named attribute or NULL if not there.  */
18580
18581 static struct attribute *
18582 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18583 {
18584   for (;;)
18585     {
18586       unsigned int i;
18587       struct attribute *spec = NULL;
18588
18589       for (i = 0; i < die->num_attrs; ++i)
18590         {
18591           if (die->attrs[i].name == name)
18592             return &die->attrs[i];
18593           if (die->attrs[i].name == DW_AT_specification
18594               || die->attrs[i].name == DW_AT_abstract_origin)
18595             spec = &die->attrs[i];
18596         }
18597
18598       if (!spec)
18599         break;
18600
18601       die = follow_die_ref (die, spec, &cu);
18602     }
18603
18604   return NULL;
18605 }
18606
18607 /* Return the named attribute or NULL if not there,
18608    but do not follow DW_AT_specification, etc.
18609    This is for use in contexts where we're reading .debug_types dies.
18610    Following DW_AT_specification, DW_AT_abstract_origin will take us
18611    back up the chain, and we want to go down.  */
18612
18613 static struct attribute *
18614 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
18615 {
18616   unsigned int i;
18617
18618   for (i = 0; i < die->num_attrs; ++i)
18619     if (die->attrs[i].name == name)
18620       return &die->attrs[i];
18621
18622   return NULL;
18623 }
18624
18625 /* Return the string associated with a string-typed attribute, or NULL if it
18626    is either not found or is of an incorrect type.  */
18627
18628 static const char *
18629 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18630 {
18631   struct attribute *attr;
18632   const char *str = NULL;
18633
18634   attr = dwarf2_attr (die, name, cu);
18635
18636   if (attr != NULL)
18637     {
18638       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
18639           || attr->form == DW_FORM_string
18640           || attr->form == DW_FORM_GNU_str_index
18641           || attr->form == DW_FORM_GNU_strp_alt)
18642         str = DW_STRING (attr);
18643       else
18644         complaint (&symfile_complaints,
18645                    _("string type expected for attribute %s for "
18646                      "DIE at 0x%x in module %s"),
18647                    dwarf_attr_name (name), to_underlying (die->sect_off),
18648                    objfile_name (cu->objfile));
18649     }
18650
18651   return str;
18652 }
18653
18654 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18655    and holds a non-zero value.  This function should only be used for
18656    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18657
18658 static int
18659 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18660 {
18661   struct attribute *attr = dwarf2_attr (die, name, cu);
18662
18663   return (attr && DW_UNSND (attr));
18664 }
18665
18666 static int
18667 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18668 {
18669   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18670      which value is non-zero.  However, we have to be careful with
18671      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18672      (via dwarf2_flag_true_p) follows this attribute.  So we may
18673      end up accidently finding a declaration attribute that belongs
18674      to a different DIE referenced by the specification attribute,
18675      even though the given DIE does not have a declaration attribute.  */
18676   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18677           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18678 }
18679
18680 /* Return the die giving the specification for DIE, if there is
18681    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18682    containing the return value on output.  If there is no
18683    specification, but there is an abstract origin, that is
18684    returned.  */
18685
18686 static struct die_info *
18687 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18688 {
18689   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18690                                              *spec_cu);
18691
18692   if (spec_attr == NULL)
18693     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18694
18695   if (spec_attr == NULL)
18696     return NULL;
18697   else
18698     return follow_die_ref (die, spec_attr, spec_cu);
18699 }
18700
18701 /* Stub for free_line_header to match void * callback types.  */
18702
18703 static void
18704 free_line_header_voidp (void *arg)
18705 {
18706   struct line_header *lh = (struct line_header *) arg;
18707
18708   delete lh;
18709 }
18710
18711 void
18712 line_header::add_include_dir (const char *include_dir)
18713 {
18714   if (dwarf_line_debug >= 2)
18715     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18716                         include_dirs.size () + 1, include_dir);
18717
18718   include_dirs.push_back (include_dir);
18719 }
18720
18721 void
18722 line_header::add_file_name (const char *name,
18723                             dir_index d_index,
18724                             unsigned int mod_time,
18725                             unsigned int length)
18726 {
18727   if (dwarf_line_debug >= 2)
18728     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18729                         (unsigned) file_names.size () + 1, name);
18730
18731   file_names.emplace_back (name, d_index, mod_time, length);
18732 }
18733
18734 /* A convenience function to find the proper .debug_line section for a CU.  */
18735
18736 static struct dwarf2_section_info *
18737 get_debug_line_section (struct dwarf2_cu *cu)
18738 {
18739   struct dwarf2_section_info *section;
18740
18741   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18742      DWO file.  */
18743   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18744     section = &cu->dwo_unit->dwo_file->sections.line;
18745   else if (cu->per_cu->is_dwz)
18746     {
18747       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18748
18749       section = &dwz->line;
18750     }
18751   else
18752     section = &dwarf2_per_objfile->line;
18753
18754   return section;
18755 }
18756
18757 /* Read directory or file name entry format, starting with byte of
18758    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18759    entries count and the entries themselves in the described entry
18760    format.  */
18761
18762 static void
18763 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18764                         struct line_header *lh,
18765                         const struct comp_unit_head *cu_header,
18766                         void (*callback) (struct line_header *lh,
18767                                           const char *name,
18768                                           dir_index d_index,
18769                                           unsigned int mod_time,
18770                                           unsigned int length))
18771 {
18772   gdb_byte format_count, formati;
18773   ULONGEST data_count, datai;
18774   const gdb_byte *buf = *bufp;
18775   const gdb_byte *format_header_data;
18776   unsigned int bytes_read;
18777
18778   format_count = read_1_byte (abfd, buf);
18779   buf += 1;
18780   format_header_data = buf;
18781   for (formati = 0; formati < format_count; formati++)
18782     {
18783       read_unsigned_leb128 (abfd, buf, &bytes_read);
18784       buf += bytes_read;
18785       read_unsigned_leb128 (abfd, buf, &bytes_read);
18786       buf += bytes_read;
18787     }
18788
18789   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18790   buf += bytes_read;
18791   for (datai = 0; datai < data_count; datai++)
18792     {
18793       const gdb_byte *format = format_header_data;
18794       struct file_entry fe;
18795
18796       for (formati = 0; formati < format_count; formati++)
18797         {
18798           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18799           format += bytes_read;
18800
18801           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18802           format += bytes_read;
18803
18804           gdb::optional<const char *> string;
18805           gdb::optional<unsigned int> uint;
18806
18807           switch (form)
18808             {
18809             case DW_FORM_string:
18810               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18811               buf += bytes_read;
18812               break;
18813
18814             case DW_FORM_line_strp:
18815               string.emplace (read_indirect_line_string (abfd, buf,
18816                                                          cu_header,
18817                                                          &bytes_read));
18818               buf += bytes_read;
18819               break;
18820
18821             case DW_FORM_data1:
18822               uint.emplace (read_1_byte (abfd, buf));
18823               buf += 1;
18824               break;
18825
18826             case DW_FORM_data2:
18827               uint.emplace (read_2_bytes (abfd, buf));
18828               buf += 2;
18829               break;
18830
18831             case DW_FORM_data4:
18832               uint.emplace (read_4_bytes (abfd, buf));
18833               buf += 4;
18834               break;
18835
18836             case DW_FORM_data8:
18837               uint.emplace (read_8_bytes (abfd, buf));
18838               buf += 8;
18839               break;
18840
18841             case DW_FORM_udata:
18842               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18843               buf += bytes_read;
18844               break;
18845
18846             case DW_FORM_block:
18847               /* It is valid only for DW_LNCT_timestamp which is ignored by
18848                  current GDB.  */
18849               break;
18850             }
18851
18852           switch (content_type)
18853             {
18854             case DW_LNCT_path:
18855               if (string.has_value ())
18856                 fe.name = *string;
18857               break;
18858             case DW_LNCT_directory_index:
18859               if (uint.has_value ())
18860                 fe.d_index = (dir_index) *uint;
18861               break;
18862             case DW_LNCT_timestamp:
18863               if (uint.has_value ())
18864                 fe.mod_time = *uint;
18865               break;
18866             case DW_LNCT_size:
18867               if (uint.has_value ())
18868                 fe.length = *uint;
18869               break;
18870             case DW_LNCT_MD5:
18871               break;
18872             default:
18873               complaint (&symfile_complaints,
18874                          _("Unknown format content type %s"),
18875                          pulongest (content_type));
18876             }
18877         }
18878
18879       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18880     }
18881
18882   *bufp = buf;
18883 }
18884
18885 /* Read the statement program header starting at OFFSET in
18886    .debug_line, or .debug_line.dwo.  Return a pointer
18887    to a struct line_header, allocated using xmalloc.
18888    Returns NULL if there is a problem reading the header, e.g., if it
18889    has a version we don't understand.
18890
18891    NOTE: the strings in the include directory and file name tables of
18892    the returned object point into the dwarf line section buffer,
18893    and must not be freed.  */
18894
18895 static line_header_up
18896 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18897 {
18898   const gdb_byte *line_ptr;
18899   unsigned int bytes_read, offset_size;
18900   int i;
18901   const char *cur_dir, *cur_file;
18902   struct dwarf2_section_info *section;
18903   bfd *abfd;
18904
18905   section = get_debug_line_section (cu);
18906   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18907   if (section->buffer == NULL)
18908     {
18909       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18910         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18911       else
18912         complaint (&symfile_complaints, _("missing .debug_line section"));
18913       return 0;
18914     }
18915
18916   /* We can't do this until we know the section is non-empty.
18917      Only then do we know we have such a section.  */
18918   abfd = get_section_bfd_owner (section);
18919
18920   /* Make sure that at least there's room for the total_length field.
18921      That could be 12 bytes long, but we're just going to fudge that.  */
18922   if (to_underlying (sect_off) + 4 >= section->size)
18923     {
18924       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18925       return 0;
18926     }
18927
18928   line_header_up lh (new line_header ());
18929
18930   lh->sect_off = sect_off;
18931   lh->offset_in_dwz = cu->per_cu->is_dwz;
18932
18933   line_ptr = section->buffer + to_underlying (sect_off);
18934
18935   /* Read in the header.  */
18936   lh->total_length =
18937     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18938                                             &bytes_read, &offset_size);
18939   line_ptr += bytes_read;
18940   if (line_ptr + lh->total_length > (section->buffer + section->size))
18941     {
18942       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18943       return 0;
18944     }
18945   lh->statement_program_end = line_ptr + lh->total_length;
18946   lh->version = read_2_bytes (abfd, line_ptr);
18947   line_ptr += 2;
18948   if (lh->version > 5)
18949     {
18950       /* This is a version we don't understand.  The format could have
18951          changed in ways we don't handle properly so just punt.  */
18952       complaint (&symfile_complaints,
18953                  _("unsupported version in .debug_line section"));
18954       return NULL;
18955     }
18956   if (lh->version >= 5)
18957     {
18958       gdb_byte segment_selector_size;
18959
18960       /* Skip address size.  */
18961       read_1_byte (abfd, line_ptr);
18962       line_ptr += 1;
18963
18964       segment_selector_size = read_1_byte (abfd, line_ptr);
18965       line_ptr += 1;
18966       if (segment_selector_size != 0)
18967         {
18968           complaint (&symfile_complaints,
18969                      _("unsupported segment selector size %u "
18970                        "in .debug_line section"),
18971                      segment_selector_size);
18972           return NULL;
18973         }
18974     }
18975   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18976   line_ptr += offset_size;
18977   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18978   line_ptr += 1;
18979   if (lh->version >= 4)
18980     {
18981       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18982       line_ptr += 1;
18983     }
18984   else
18985     lh->maximum_ops_per_instruction = 1;
18986
18987   if (lh->maximum_ops_per_instruction == 0)
18988     {
18989       lh->maximum_ops_per_instruction = 1;
18990       complaint (&symfile_complaints,
18991                  _("invalid maximum_ops_per_instruction "
18992                    "in `.debug_line' section"));
18993     }
18994
18995   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18996   line_ptr += 1;
18997   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18998   line_ptr += 1;
18999   lh->line_range = read_1_byte (abfd, line_ptr);
19000   line_ptr += 1;
19001   lh->opcode_base = read_1_byte (abfd, line_ptr);
19002   line_ptr += 1;
19003   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
19004
19005   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
19006   for (i = 1; i < lh->opcode_base; ++i)
19007     {
19008       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
19009       line_ptr += 1;
19010     }
19011
19012   if (lh->version >= 5)
19013     {
19014       /* Read directory table.  */
19015       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19016                               [] (struct line_header *lh, const char *name,
19017                                   dir_index d_index, unsigned int mod_time,
19018                                   unsigned int length)
19019         {
19020           lh->add_include_dir (name);
19021         });
19022
19023       /* Read file name table.  */
19024       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19025                               [] (struct line_header *lh, const char *name,
19026                                   dir_index d_index, unsigned int mod_time,
19027                                   unsigned int length)
19028         {
19029           lh->add_file_name (name, d_index, mod_time, length);
19030         });
19031     }
19032   else
19033     {
19034       /* Read directory table.  */
19035       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19036         {
19037           line_ptr += bytes_read;
19038           lh->add_include_dir (cur_dir);
19039         }
19040       line_ptr += bytes_read;
19041
19042       /* Read file name table.  */
19043       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19044         {
19045           unsigned int mod_time, length;
19046           dir_index d_index;
19047
19048           line_ptr += bytes_read;
19049           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19050           line_ptr += bytes_read;
19051           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19052           line_ptr += bytes_read;
19053           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19054           line_ptr += bytes_read;
19055
19056           lh->add_file_name (cur_file, d_index, mod_time, length);
19057         }
19058       line_ptr += bytes_read;
19059     }
19060   lh->statement_program_start = line_ptr;
19061
19062   if (line_ptr > (section->buffer + section->size))
19063     complaint (&symfile_complaints,
19064                _("line number info header doesn't "
19065                  "fit in `.debug_line' section"));
19066
19067   return lh;
19068 }
19069
19070 /* Subroutine of dwarf_decode_lines to simplify it.
19071    Return the file name of the psymtab for included file FILE_INDEX
19072    in line header LH of PST.
19073    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19074    If space for the result is malloc'd, it will be freed by a cleanup.
19075    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
19076
19077    The function creates dangling cleanup registration.  */
19078
19079 static const char *
19080 psymtab_include_file_name (const struct line_header *lh, int file_index,
19081                            const struct partial_symtab *pst,
19082                            const char *comp_dir)
19083 {
19084   const file_entry &fe = lh->file_names[file_index];
19085   const char *include_name = fe.name;
19086   const char *include_name_to_compare = include_name;
19087   const char *pst_filename;
19088   char *copied_name = NULL;
19089   int file_is_pst;
19090
19091   const char *dir_name = fe.include_dir (lh);
19092
19093   if (!IS_ABSOLUTE_PATH (include_name)
19094       && (dir_name != NULL || comp_dir != NULL))
19095     {
19096       /* Avoid creating a duplicate psymtab for PST.
19097          We do this by comparing INCLUDE_NAME and PST_FILENAME.
19098          Before we do the comparison, however, we need to account
19099          for DIR_NAME and COMP_DIR.
19100          First prepend dir_name (if non-NULL).  If we still don't
19101          have an absolute path prepend comp_dir (if non-NULL).
19102          However, the directory we record in the include-file's
19103          psymtab does not contain COMP_DIR (to match the
19104          corresponding symtab(s)).
19105
19106          Example:
19107
19108          bash$ cd /tmp
19109          bash$ gcc -g ./hello.c
19110          include_name = "hello.c"
19111          dir_name = "."
19112          DW_AT_comp_dir = comp_dir = "/tmp"
19113          DW_AT_name = "./hello.c"
19114
19115       */
19116
19117       if (dir_name != NULL)
19118         {
19119           char *tem = concat (dir_name, SLASH_STRING,
19120                               include_name, (char *)NULL);
19121
19122           make_cleanup (xfree, tem);
19123           include_name = tem;
19124           include_name_to_compare = include_name;
19125         }
19126       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
19127         {
19128           char *tem = concat (comp_dir, SLASH_STRING,
19129                               include_name, (char *)NULL);
19130
19131           make_cleanup (xfree, tem);
19132           include_name_to_compare = tem;
19133         }
19134     }
19135
19136   pst_filename = pst->filename;
19137   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
19138     {
19139       copied_name = concat (pst->dirname, SLASH_STRING,
19140                             pst_filename, (char *)NULL);
19141       pst_filename = copied_name;
19142     }
19143
19144   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
19145
19146   if (copied_name != NULL)
19147     xfree (copied_name);
19148
19149   if (file_is_pst)
19150     return NULL;
19151   return include_name;
19152 }
19153
19154 /* State machine to track the state of the line number program.  */
19155
19156 class lnp_state_machine
19157 {
19158 public:
19159   /* Initialize a machine state for the start of a line number
19160      program.  */
19161   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
19162
19163   file_entry *current_file ()
19164   {
19165     /* lh->file_names is 0-based, but the file name numbers in the
19166        statement program are 1-based.  */
19167     return m_line_header->file_name_at (m_file);
19168   }
19169
19170   /* Record the line in the state machine.  END_SEQUENCE is true if
19171      we're processing the end of a sequence.  */
19172   void record_line (bool end_sequence);
19173
19174   /* Check address and if invalid nop-out the rest of the lines in this
19175      sequence.  */
19176   void check_line_address (struct dwarf2_cu *cu,
19177                            const gdb_byte *line_ptr,
19178                            CORE_ADDR lowpc, CORE_ADDR address);
19179
19180   void handle_set_discriminator (unsigned int discriminator)
19181   {
19182     m_discriminator = discriminator;
19183     m_line_has_non_zero_discriminator |= discriminator != 0;
19184   }
19185
19186   /* Handle DW_LNE_set_address.  */
19187   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
19188   {
19189     m_op_index = 0;
19190     address += baseaddr;
19191     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
19192   }
19193
19194   /* Handle DW_LNS_advance_pc.  */
19195   void handle_advance_pc (CORE_ADDR adjust);
19196
19197   /* Handle a special opcode.  */
19198   void handle_special_opcode (unsigned char op_code);
19199
19200   /* Handle DW_LNS_advance_line.  */
19201   void handle_advance_line (int line_delta)
19202   {
19203     advance_line (line_delta);
19204   }
19205
19206   /* Handle DW_LNS_set_file.  */
19207   void handle_set_file (file_name_index file);
19208
19209   /* Handle DW_LNS_negate_stmt.  */
19210   void handle_negate_stmt ()
19211   {
19212     m_is_stmt = !m_is_stmt;
19213   }
19214
19215   /* Handle DW_LNS_const_add_pc.  */
19216   void handle_const_add_pc ();
19217
19218   /* Handle DW_LNS_fixed_advance_pc.  */
19219   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
19220   {
19221     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19222     m_op_index = 0;
19223   }
19224
19225   /* Handle DW_LNS_copy.  */
19226   void handle_copy ()
19227   {
19228     record_line (false);
19229     m_discriminator = 0;
19230   }
19231
19232   /* Handle DW_LNE_end_sequence.  */
19233   void handle_end_sequence ()
19234   {
19235     m_record_line_callback = ::record_line;
19236   }
19237
19238 private:
19239   /* Advance the line by LINE_DELTA.  */
19240   void advance_line (int line_delta)
19241   {
19242     m_line += line_delta;
19243
19244     if (line_delta != 0)
19245       m_line_has_non_zero_discriminator = m_discriminator != 0;
19246   }
19247
19248   gdbarch *m_gdbarch;
19249
19250   /* True if we're recording lines.
19251      Otherwise we're building partial symtabs and are just interested in
19252      finding include files mentioned by the line number program.  */
19253   bool m_record_lines_p;
19254
19255   /* The line number header.  */
19256   line_header *m_line_header;
19257
19258   /* These are part of the standard DWARF line number state machine,
19259      and initialized according to the DWARF spec.  */
19260
19261   unsigned char m_op_index = 0;
19262   /* The line table index (1-based) of the current file.  */
19263   file_name_index m_file = (file_name_index) 1;
19264   unsigned int m_line = 1;
19265
19266   /* These are initialized in the constructor.  */
19267
19268   CORE_ADDR m_address;
19269   bool m_is_stmt;
19270   unsigned int m_discriminator;
19271
19272   /* Additional bits of state we need to track.  */
19273
19274   /* The last file that we called dwarf2_start_subfile for.
19275      This is only used for TLLs.  */
19276   unsigned int m_last_file = 0;
19277   /* The last file a line number was recorded for.  */
19278   struct subfile *m_last_subfile = NULL;
19279
19280   /* The function to call to record a line.  */
19281   record_line_ftype *m_record_line_callback = NULL;
19282
19283   /* The last line number that was recorded, used to coalesce
19284      consecutive entries for the same line.  This can happen, for
19285      example, when discriminators are present.  PR 17276.  */
19286   unsigned int m_last_line = 0;
19287   bool m_line_has_non_zero_discriminator = false;
19288 };
19289
19290 void
19291 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
19292 {
19293   CORE_ADDR addr_adj = (((m_op_index + adjust)
19294                          / m_line_header->maximum_ops_per_instruction)
19295                         * m_line_header->minimum_instruction_length);
19296   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19297   m_op_index = ((m_op_index + adjust)
19298                 % m_line_header->maximum_ops_per_instruction);
19299 }
19300
19301 void
19302 lnp_state_machine::handle_special_opcode (unsigned char op_code)
19303 {
19304   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
19305   CORE_ADDR addr_adj = (((m_op_index
19306                           + (adj_opcode / m_line_header->line_range))
19307                          / m_line_header->maximum_ops_per_instruction)
19308                         * m_line_header->minimum_instruction_length);
19309   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19310   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
19311                 % m_line_header->maximum_ops_per_instruction);
19312
19313   int line_delta = (m_line_header->line_base
19314                     + (adj_opcode % m_line_header->line_range));
19315   advance_line (line_delta);
19316   record_line (false);
19317   m_discriminator = 0;
19318 }
19319
19320 void
19321 lnp_state_machine::handle_set_file (file_name_index file)
19322 {
19323   m_file = file;
19324
19325   const file_entry *fe = current_file ();
19326   if (fe == NULL)
19327     dwarf2_debug_line_missing_file_complaint ();
19328   else if (m_record_lines_p)
19329     {
19330       const char *dir = fe->include_dir (m_line_header);
19331
19332       m_last_subfile = current_subfile;
19333       m_line_has_non_zero_discriminator = m_discriminator != 0;
19334       dwarf2_start_subfile (fe->name, dir);
19335     }
19336 }
19337
19338 void
19339 lnp_state_machine::handle_const_add_pc ()
19340 {
19341   CORE_ADDR adjust
19342     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
19343
19344   CORE_ADDR addr_adj
19345     = (((m_op_index + adjust)
19346         / m_line_header->maximum_ops_per_instruction)
19347        * m_line_header->minimum_instruction_length);
19348
19349   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19350   m_op_index = ((m_op_index + adjust)
19351                 % m_line_header->maximum_ops_per_instruction);
19352 }
19353
19354 /* Ignore this record_line request.  */
19355
19356 static void
19357 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
19358 {
19359   return;
19360 }
19361
19362 /* Return non-zero if we should add LINE to the line number table.
19363    LINE is the line to add, LAST_LINE is the last line that was added,
19364    LAST_SUBFILE is the subfile for LAST_LINE.
19365    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
19366    had a non-zero discriminator.
19367
19368    We have to be careful in the presence of discriminators.
19369    E.g., for this line:
19370
19371      for (i = 0; i < 100000; i++);
19372
19373    clang can emit four line number entries for that one line,
19374    each with a different discriminator.
19375    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
19376
19377    However, we want gdb to coalesce all four entries into one.
19378    Otherwise the user could stepi into the middle of the line and
19379    gdb would get confused about whether the pc really was in the
19380    middle of the line.
19381
19382    Things are further complicated by the fact that two consecutive
19383    line number entries for the same line is a heuristic used by gcc
19384    to denote the end of the prologue.  So we can't just discard duplicate
19385    entries, we have to be selective about it.  The heuristic we use is
19386    that we only collapse consecutive entries for the same line if at least
19387    one of those entries has a non-zero discriminator.  PR 17276.
19388
19389    Note: Addresses in the line number state machine can never go backwards
19390    within one sequence, thus this coalescing is ok.  */
19391
19392 static int
19393 dwarf_record_line_p (unsigned int line, unsigned int last_line,
19394                      int line_has_non_zero_discriminator,
19395                      struct subfile *last_subfile)
19396 {
19397   if (current_subfile != last_subfile)
19398     return 1;
19399   if (line != last_line)
19400     return 1;
19401   /* Same line for the same file that we've seen already.
19402      As a last check, for pr 17276, only record the line if the line
19403      has never had a non-zero discriminator.  */
19404   if (!line_has_non_zero_discriminator)
19405     return 1;
19406   return 0;
19407 }
19408
19409 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
19410    in the line table of subfile SUBFILE.  */
19411
19412 static void
19413 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
19414                      unsigned int line, CORE_ADDR address,
19415                      record_line_ftype p_record_line)
19416 {
19417   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
19418
19419   if (dwarf_line_debug)
19420     {
19421       fprintf_unfiltered (gdb_stdlog,
19422                           "Recording line %u, file %s, address %s\n",
19423                           line, lbasename (subfile->name),
19424                           paddress (gdbarch, address));
19425     }
19426
19427   (*p_record_line) (subfile, line, addr);
19428 }
19429
19430 /* Subroutine of dwarf_decode_lines_1 to simplify it.
19431    Mark the end of a set of line number records.
19432    The arguments are the same as for dwarf_record_line_1.
19433    If SUBFILE is NULL the request is ignored.  */
19434
19435 static void
19436 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
19437                    CORE_ADDR address, record_line_ftype p_record_line)
19438 {
19439   if (subfile == NULL)
19440     return;
19441
19442   if (dwarf_line_debug)
19443     {
19444       fprintf_unfiltered (gdb_stdlog,
19445                           "Finishing current line, file %s, address %s\n",
19446                           lbasename (subfile->name),
19447                           paddress (gdbarch, address));
19448     }
19449
19450   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
19451 }
19452
19453 void
19454 lnp_state_machine::record_line (bool end_sequence)
19455 {
19456   if (dwarf_line_debug)
19457     {
19458       fprintf_unfiltered (gdb_stdlog,
19459                           "Processing actual line %u: file %u,"
19460                           " address %s, is_stmt %u, discrim %u\n",
19461                           m_line, to_underlying (m_file),
19462                           paddress (m_gdbarch, m_address),
19463                           m_is_stmt, m_discriminator);
19464     }
19465
19466   file_entry *fe = current_file ();
19467
19468   if (fe == NULL)
19469     dwarf2_debug_line_missing_file_complaint ();
19470   /* For now we ignore lines not starting on an instruction boundary.
19471      But not when processing end_sequence for compatibility with the
19472      previous version of the code.  */
19473   else if (m_op_index == 0 || end_sequence)
19474     {
19475       fe->included_p = 1;
19476       if (m_record_lines_p && m_is_stmt)
19477         {
19478           if (m_last_subfile != current_subfile || end_sequence)
19479             {
19480               dwarf_finish_line (m_gdbarch, m_last_subfile,
19481                                  m_address, m_record_line_callback);
19482             }
19483
19484           if (!end_sequence)
19485             {
19486               if (dwarf_record_line_p (m_line, m_last_line,
19487                                        m_line_has_non_zero_discriminator,
19488                                        m_last_subfile))
19489                 {
19490                   dwarf_record_line_1 (m_gdbarch, current_subfile,
19491                                        m_line, m_address,
19492                                        m_record_line_callback);
19493                 }
19494               m_last_subfile = current_subfile;
19495               m_last_line = m_line;
19496             }
19497         }
19498     }
19499 }
19500
19501 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
19502                                       bool record_lines_p)
19503 {
19504   m_gdbarch = arch;
19505   m_record_lines_p = record_lines_p;
19506   m_line_header = lh;
19507
19508   m_record_line_callback = ::record_line;
19509
19510   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
19511      was a line entry for it so that the backend has a chance to adjust it
19512      and also record it in case it needs it.  This is currently used by MIPS
19513      code, cf. `mips_adjust_dwarf2_line'.  */
19514   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
19515   m_is_stmt = lh->default_is_stmt;
19516   m_discriminator = 0;
19517 }
19518
19519 void
19520 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
19521                                        const gdb_byte *line_ptr,
19522                                        CORE_ADDR lowpc, CORE_ADDR address)
19523 {
19524   /* If address < lowpc then it's not a usable value, it's outside the
19525      pc range of the CU.  However, we restrict the test to only address
19526      values of zero to preserve GDB's previous behaviour which is to
19527      handle the specific case of a function being GC'd by the linker.  */
19528
19529   if (address == 0 && address < lowpc)
19530     {
19531       /* This line table is for a function which has been
19532          GCd by the linker.  Ignore it.  PR gdb/12528 */
19533
19534       struct objfile *objfile = cu->objfile;
19535       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
19536
19537       complaint (&symfile_complaints,
19538                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
19539                  line_offset, objfile_name (objfile));
19540       m_record_line_callback = noop_record_line;
19541       /* Note: record_line_callback is left as noop_record_line until
19542          we see DW_LNE_end_sequence.  */
19543     }
19544 }
19545
19546 /* Subroutine of dwarf_decode_lines to simplify it.
19547    Process the line number information in LH.
19548    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
19549    program in order to set included_p for every referenced header.  */
19550
19551 static void
19552 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
19553                       const int decode_for_pst_p, CORE_ADDR lowpc)
19554 {
19555   const gdb_byte *line_ptr, *extended_end;
19556   const gdb_byte *line_end;
19557   unsigned int bytes_read, extended_len;
19558   unsigned char op_code, extended_op;
19559   CORE_ADDR baseaddr;
19560   struct objfile *objfile = cu->objfile;
19561   bfd *abfd = objfile->obfd;
19562   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19563   /* True if we're recording line info (as opposed to building partial
19564      symtabs and just interested in finding include files mentioned by
19565      the line number program).  */
19566   bool record_lines_p = !decode_for_pst_p;
19567
19568   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19569
19570   line_ptr = lh->statement_program_start;
19571   line_end = lh->statement_program_end;
19572
19573   /* Read the statement sequences until there's nothing left.  */
19574   while (line_ptr < line_end)
19575     {
19576       /* The DWARF line number program state machine.  Reset the state
19577          machine at the start of each sequence.  */
19578       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
19579       bool end_sequence = false;
19580
19581       if (record_lines_p)
19582         {
19583           /* Start a subfile for the current file of the state
19584              machine.  */
19585           const file_entry *fe = state_machine.current_file ();
19586
19587           if (fe != NULL)
19588             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
19589         }
19590
19591       /* Decode the table.  */
19592       while (line_ptr < line_end && !end_sequence)
19593         {
19594           op_code = read_1_byte (abfd, line_ptr);
19595           line_ptr += 1;
19596
19597           if (op_code >= lh->opcode_base)
19598             {
19599               /* Special opcode.  */
19600               state_machine.handle_special_opcode (op_code);
19601             }
19602           else switch (op_code)
19603             {
19604             case DW_LNS_extended_op:
19605               extended_len = read_unsigned_leb128 (abfd, line_ptr,
19606                                                    &bytes_read);
19607               line_ptr += bytes_read;
19608               extended_end = line_ptr + extended_len;
19609               extended_op = read_1_byte (abfd, line_ptr);
19610               line_ptr += 1;
19611               switch (extended_op)
19612                 {
19613                 case DW_LNE_end_sequence:
19614                   state_machine.handle_end_sequence ();
19615                   end_sequence = true;
19616                   break;
19617                 case DW_LNE_set_address:
19618                   {
19619                     CORE_ADDR address
19620                       = read_address (abfd, line_ptr, cu, &bytes_read);
19621                     line_ptr += bytes_read;
19622
19623                     state_machine.check_line_address (cu, line_ptr,
19624                                                       lowpc, address);
19625                     state_machine.handle_set_address (baseaddr, address);
19626                   }
19627                   break;
19628                 case DW_LNE_define_file:
19629                   {
19630                     const char *cur_file;
19631                     unsigned int mod_time, length;
19632                     dir_index dindex;
19633
19634                     cur_file = read_direct_string (abfd, line_ptr,
19635                                                    &bytes_read);
19636                     line_ptr += bytes_read;
19637                     dindex = (dir_index)
19638                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19639                     line_ptr += bytes_read;
19640                     mod_time =
19641                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19642                     line_ptr += bytes_read;
19643                     length =
19644                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19645                     line_ptr += bytes_read;
19646                     lh->add_file_name (cur_file, dindex, mod_time, length);
19647                   }
19648                   break;
19649                 case DW_LNE_set_discriminator:
19650                   {
19651                     /* The discriminator is not interesting to the
19652                        debugger; just ignore it.  We still need to
19653                        check its value though:
19654                        if there are consecutive entries for the same
19655                        (non-prologue) line we want to coalesce them.
19656                        PR 17276.  */
19657                     unsigned int discr
19658                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19659                     line_ptr += bytes_read;
19660
19661                     state_machine.handle_set_discriminator (discr);
19662                   }
19663                   break;
19664                 default:
19665                   complaint (&symfile_complaints,
19666                              _("mangled .debug_line section"));
19667                   return;
19668                 }
19669               /* Make sure that we parsed the extended op correctly.  If e.g.
19670                  we expected a different address size than the producer used,
19671                  we may have read the wrong number of bytes.  */
19672               if (line_ptr != extended_end)
19673                 {
19674                   complaint (&symfile_complaints,
19675                              _("mangled .debug_line section"));
19676                   return;
19677                 }
19678               break;
19679             case DW_LNS_copy:
19680               state_machine.handle_copy ();
19681               break;
19682             case DW_LNS_advance_pc:
19683               {
19684                 CORE_ADDR adjust
19685                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19686                 line_ptr += bytes_read;
19687
19688                 state_machine.handle_advance_pc (adjust);
19689               }
19690               break;
19691             case DW_LNS_advance_line:
19692               {
19693                 int line_delta
19694                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19695                 line_ptr += bytes_read;
19696
19697                 state_machine.handle_advance_line (line_delta);
19698               }
19699               break;
19700             case DW_LNS_set_file:
19701               {
19702                 file_name_index file
19703                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19704                                                             &bytes_read);
19705                 line_ptr += bytes_read;
19706
19707                 state_machine.handle_set_file (file);
19708               }
19709               break;
19710             case DW_LNS_set_column:
19711               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19712               line_ptr += bytes_read;
19713               break;
19714             case DW_LNS_negate_stmt:
19715               state_machine.handle_negate_stmt ();
19716               break;
19717             case DW_LNS_set_basic_block:
19718               break;
19719             /* Add to the address register of the state machine the
19720                address increment value corresponding to special opcode
19721                255.  I.e., this value is scaled by the minimum
19722                instruction length since special opcode 255 would have
19723                scaled the increment.  */
19724             case DW_LNS_const_add_pc:
19725               state_machine.handle_const_add_pc ();
19726               break;
19727             case DW_LNS_fixed_advance_pc:
19728               {
19729                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19730                 line_ptr += 2;
19731
19732                 state_machine.handle_fixed_advance_pc (addr_adj);
19733               }
19734               break;
19735             default:
19736               {
19737                 /* Unknown standard opcode, ignore it.  */
19738                 int i;
19739
19740                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19741                   {
19742                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19743                     line_ptr += bytes_read;
19744                   }
19745               }
19746             }
19747         }
19748
19749       if (!end_sequence)
19750         dwarf2_debug_line_missing_end_sequence_complaint ();
19751
19752       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19753          in which case we still finish recording the last line).  */
19754       state_machine.record_line (true);
19755     }
19756 }
19757
19758 /* Decode the Line Number Program (LNP) for the given line_header
19759    structure and CU.  The actual information extracted and the type
19760    of structures created from the LNP depends on the value of PST.
19761
19762    1. If PST is NULL, then this procedure uses the data from the program
19763       to create all necessary symbol tables, and their linetables.
19764
19765    2. If PST is not NULL, this procedure reads the program to determine
19766       the list of files included by the unit represented by PST, and
19767       builds all the associated partial symbol tables.
19768
19769    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19770    It is used for relative paths in the line table.
19771    NOTE: When processing partial symtabs (pst != NULL),
19772    comp_dir == pst->dirname.
19773
19774    NOTE: It is important that psymtabs have the same file name (via strcmp)
19775    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19776    symtab we don't use it in the name of the psymtabs we create.
19777    E.g. expand_line_sal requires this when finding psymtabs to expand.
19778    A good testcase for this is mb-inline.exp.
19779
19780    LOWPC is the lowest address in CU (or 0 if not known).
19781
19782    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19783    for its PC<->lines mapping information.  Otherwise only the filename
19784    table is read in.  */
19785
19786 static void
19787 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19788                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19789                     CORE_ADDR lowpc, int decode_mapping)
19790 {
19791   struct objfile *objfile = cu->objfile;
19792   const int decode_for_pst_p = (pst != NULL);
19793
19794   if (decode_mapping)
19795     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19796
19797   if (decode_for_pst_p)
19798     {
19799       int file_index;
19800
19801       /* Now that we're done scanning the Line Header Program, we can
19802          create the psymtab of each included file.  */
19803       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19804         if (lh->file_names[file_index].included_p == 1)
19805           {
19806             const char *include_name =
19807               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19808             if (include_name != NULL)
19809               dwarf2_create_include_psymtab (include_name, pst, objfile);
19810           }
19811     }
19812   else
19813     {
19814       /* Make sure a symtab is created for every file, even files
19815          which contain only variables (i.e. no code with associated
19816          line numbers).  */
19817       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19818       int i;
19819
19820       for (i = 0; i < lh->file_names.size (); i++)
19821         {
19822           file_entry &fe = lh->file_names[i];
19823
19824           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19825
19826           if (current_subfile->symtab == NULL)
19827             {
19828               current_subfile->symtab
19829                 = allocate_symtab (cust, current_subfile->name);
19830             }
19831           fe.symtab = current_subfile->symtab;
19832         }
19833     }
19834 }
19835
19836 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19837    DIRNAME the name of the source directory which contains FILENAME
19838    or NULL if not known.
19839    This routine tries to keep line numbers from identical absolute and
19840    relative file names in a common subfile.
19841
19842    Using the `list' example from the GDB testsuite, which resides in
19843    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19844    of /srcdir/list0.c yields the following debugging information for list0.c:
19845
19846    DW_AT_name:          /srcdir/list0.c
19847    DW_AT_comp_dir:      /compdir
19848    files.files[0].name: list0.h
19849    files.files[0].dir:  /srcdir
19850    files.files[1].name: list0.c
19851    files.files[1].dir:  /srcdir
19852
19853    The line number information for list0.c has to end up in a single
19854    subfile, so that `break /srcdir/list0.c:1' works as expected.
19855    start_subfile will ensure that this happens provided that we pass the
19856    concatenation of files.files[1].dir and files.files[1].name as the
19857    subfile's name.  */
19858
19859 static void
19860 dwarf2_start_subfile (const char *filename, const char *dirname)
19861 {
19862   char *copy = NULL;
19863
19864   /* In order not to lose the line information directory,
19865      we concatenate it to the filename when it makes sense.
19866      Note that the Dwarf3 standard says (speaking of filenames in line
19867      information): ``The directory index is ignored for file names
19868      that represent full path names''.  Thus ignoring dirname in the
19869      `else' branch below isn't an issue.  */
19870
19871   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19872     {
19873       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19874       filename = copy;
19875     }
19876
19877   start_subfile (filename);
19878
19879   if (copy != NULL)
19880     xfree (copy);
19881 }
19882
19883 /* Start a symtab for DWARF.
19884    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19885
19886 static struct compunit_symtab *
19887 dwarf2_start_symtab (struct dwarf2_cu *cu,
19888                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19889 {
19890   struct compunit_symtab *cust
19891     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19892
19893   record_debugformat ("DWARF 2");
19894   record_producer (cu->producer);
19895
19896   /* We assume that we're processing GCC output.  */
19897   processing_gcc_compilation = 2;
19898
19899   cu->processing_has_namespace_info = 0;
19900
19901   return cust;
19902 }
19903
19904 static void
19905 var_decode_location (struct attribute *attr, struct symbol *sym,
19906                      struct dwarf2_cu *cu)
19907 {
19908   struct objfile *objfile = cu->objfile;
19909   struct comp_unit_head *cu_header = &cu->header;
19910
19911   /* NOTE drow/2003-01-30: There used to be a comment and some special
19912      code here to turn a symbol with DW_AT_external and a
19913      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19914      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19915      with some versions of binutils) where shared libraries could have
19916      relocations against symbols in their debug information - the
19917      minimal symbol would have the right address, but the debug info
19918      would not.  It's no longer necessary, because we will explicitly
19919      apply relocations when we read in the debug information now.  */
19920
19921   /* A DW_AT_location attribute with no contents indicates that a
19922      variable has been optimized away.  */
19923   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19924     {
19925       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19926       return;
19927     }
19928
19929   /* Handle one degenerate form of location expression specially, to
19930      preserve GDB's previous behavior when section offsets are
19931      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19932      then mark this symbol as LOC_STATIC.  */
19933
19934   if (attr_form_is_block (attr)
19935       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19936            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19937           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19938               && (DW_BLOCK (attr)->size
19939                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19940     {
19941       unsigned int dummy;
19942
19943       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19944         SYMBOL_VALUE_ADDRESS (sym) =
19945           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19946       else
19947         SYMBOL_VALUE_ADDRESS (sym) =
19948           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19949       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19950       fixup_symbol_section (sym, objfile);
19951       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19952                                               SYMBOL_SECTION (sym));
19953       return;
19954     }
19955
19956   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19957      expression evaluator, and use LOC_COMPUTED only when necessary
19958      (i.e. when the value of a register or memory location is
19959      referenced, or a thread-local block, etc.).  Then again, it might
19960      not be worthwhile.  I'm assuming that it isn't unless performance
19961      or memory numbers show me otherwise.  */
19962
19963   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19964
19965   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19966     cu->has_loclist = 1;
19967 }
19968
19969 /* Given a pointer to a DWARF information entry, figure out if we need
19970    to make a symbol table entry for it, and if so, create a new entry
19971    and return a pointer to it.
19972    If TYPE is NULL, determine symbol type from the die, otherwise
19973    used the passed type.
19974    If SPACE is not NULL, use it to hold the new symbol.  If it is
19975    NULL, allocate a new symbol on the objfile's obstack.  */
19976
19977 static struct symbol *
19978 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19979                  struct symbol *space)
19980 {
19981   struct objfile *objfile = cu->objfile;
19982   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19983   struct symbol *sym = NULL;
19984   const char *name;
19985   struct attribute *attr = NULL;
19986   struct attribute *attr2 = NULL;
19987   CORE_ADDR baseaddr;
19988   struct pending **list_to_add = NULL;
19989
19990   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19991
19992   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19993
19994   name = dwarf2_name (die, cu);
19995   if (name)
19996     {
19997       const char *linkagename;
19998       int suppress_add = 0;
19999
20000       if (space)
20001         sym = space;
20002       else
20003         sym = allocate_symbol (objfile);
20004       OBJSTAT (objfile, n_syms++);
20005
20006       /* Cache this symbol's name and the name's demangled form (if any).  */
20007       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
20008       linkagename = dwarf2_physname (name, die, cu);
20009       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
20010
20011       /* Fortran does not have mangling standard and the mangling does differ
20012          between gfortran, iFort etc.  */
20013       if (cu->language == language_fortran
20014           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
20015         symbol_set_demangled_name (&(sym->ginfo),
20016                                    dwarf2_full_name (name, die, cu),
20017                                    NULL);
20018
20019       /* Default assumptions.
20020          Use the passed type or decode it from the die.  */
20021       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20022       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
20023       if (type != NULL)
20024         SYMBOL_TYPE (sym) = type;
20025       else
20026         SYMBOL_TYPE (sym) = die_type (die, cu);
20027       attr = dwarf2_attr (die,
20028                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
20029                           cu);
20030       if (attr)
20031         {
20032           SYMBOL_LINE (sym) = DW_UNSND (attr);
20033         }
20034
20035       attr = dwarf2_attr (die,
20036                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
20037                           cu);
20038       if (attr)
20039         {
20040           file_name_index file_index = (file_name_index) DW_UNSND (attr);
20041           struct file_entry *fe;
20042
20043           if (cu->line_header != NULL)
20044             fe = cu->line_header->file_name_at (file_index);
20045           else
20046             fe = NULL;
20047
20048           if (fe == NULL)
20049             complaint (&symfile_complaints,
20050                        _("file index out of range"));
20051           else
20052             symbol_set_symtab (sym, fe->symtab);
20053         }
20054
20055       switch (die->tag)
20056         {
20057         case DW_TAG_label:
20058           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
20059           if (attr)
20060             {
20061               CORE_ADDR addr;
20062
20063               addr = attr_value_as_address (attr);
20064               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
20065               SYMBOL_VALUE_ADDRESS (sym) = addr;
20066             }
20067           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
20068           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
20069           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
20070           add_symbol_to_list (sym, cu->list_in_scope);
20071           break;
20072         case DW_TAG_subprogram:
20073           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20074              finish_block.  */
20075           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20076           attr2 = dwarf2_attr (die, DW_AT_external, cu);
20077           if ((attr2 && (DW_UNSND (attr2) != 0))
20078               || cu->language == language_ada)
20079             {
20080               /* Subprograms marked external are stored as a global symbol.
20081                  Ada subprograms, whether marked external or not, are always
20082                  stored as a global symbol, because we want to be able to
20083                  access them globally.  For instance, we want to be able
20084                  to break on a nested subprogram without having to
20085                  specify the context.  */
20086               list_to_add = &global_symbols;
20087             }
20088           else
20089             {
20090               list_to_add = cu->list_in_scope;
20091             }
20092           break;
20093         case DW_TAG_inlined_subroutine:
20094           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20095              finish_block.  */
20096           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20097           SYMBOL_INLINED (sym) = 1;
20098           list_to_add = cu->list_in_scope;
20099           break;
20100         case DW_TAG_template_value_param:
20101           suppress_add = 1;
20102           /* Fall through.  */
20103         case DW_TAG_constant:
20104         case DW_TAG_variable:
20105         case DW_TAG_member:
20106           /* Compilation with minimal debug info may result in
20107              variables with missing type entries.  Change the
20108              misleading `void' type to something sensible.  */
20109           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
20110             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
20111
20112           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20113           /* In the case of DW_TAG_member, we should only be called for
20114              static const members.  */
20115           if (die->tag == DW_TAG_member)
20116             {
20117               /* dwarf2_add_field uses die_is_declaration,
20118                  so we do the same.  */
20119               gdb_assert (die_is_declaration (die, cu));
20120               gdb_assert (attr);
20121             }
20122           if (attr)
20123             {
20124               dwarf2_const_value (attr, sym, cu);
20125               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20126               if (!suppress_add)
20127                 {
20128                   if (attr2 && (DW_UNSND (attr2) != 0))
20129                     list_to_add = &global_symbols;
20130                   else
20131                     list_to_add = cu->list_in_scope;
20132                 }
20133               break;
20134             }
20135           attr = dwarf2_attr (die, DW_AT_location, cu);
20136           if (attr)
20137             {
20138               var_decode_location (attr, sym, cu);
20139               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20140
20141               /* Fortran explicitly imports any global symbols to the local
20142                  scope by DW_TAG_common_block.  */
20143               if (cu->language == language_fortran && die->parent
20144                   && die->parent->tag == DW_TAG_common_block)
20145                 attr2 = NULL;
20146
20147               if (SYMBOL_CLASS (sym) == LOC_STATIC
20148                   && SYMBOL_VALUE_ADDRESS (sym) == 0
20149                   && !dwarf2_per_objfile->has_section_at_zero)
20150                 {
20151                   /* When a static variable is eliminated by the linker,
20152                      the corresponding debug information is not stripped
20153                      out, but the variable address is set to null;
20154                      do not add such variables into symbol table.  */
20155                 }
20156               else if (attr2 && (DW_UNSND (attr2) != 0))
20157                 {
20158                   /* Workaround gfortran PR debug/40040 - it uses
20159                      DW_AT_location for variables in -fPIC libraries which may
20160                      get overriden by other libraries/executable and get
20161                      a different address.  Resolve it by the minimal symbol
20162                      which may come from inferior's executable using copy
20163                      relocation.  Make this workaround only for gfortran as for
20164                      other compilers GDB cannot guess the minimal symbol
20165                      Fortran mangling kind.  */
20166                   if (cu->language == language_fortran && die->parent
20167                       && die->parent->tag == DW_TAG_module
20168                       && cu->producer
20169                       && startswith (cu->producer, "GNU Fortran"))
20170                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20171
20172                   /* A variable with DW_AT_external is never static,
20173                      but it may be block-scoped.  */
20174                   list_to_add = (cu->list_in_scope == &file_symbols
20175                                  ? &global_symbols : cu->list_in_scope);
20176                 }
20177               else
20178                 list_to_add = cu->list_in_scope;
20179             }
20180           else
20181             {
20182               /* We do not know the address of this symbol.
20183                  If it is an external symbol and we have type information
20184                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
20185                  The address of the variable will then be determined from
20186                  the minimal symbol table whenever the variable is
20187                  referenced.  */
20188               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20189
20190               /* Fortran explicitly imports any global symbols to the local
20191                  scope by DW_TAG_common_block.  */
20192               if (cu->language == language_fortran && die->parent
20193                   && die->parent->tag == DW_TAG_common_block)
20194                 {
20195                   /* SYMBOL_CLASS doesn't matter here because
20196                      read_common_block is going to reset it.  */
20197                   if (!suppress_add)
20198                     list_to_add = cu->list_in_scope;
20199                 }
20200               else if (attr2 && (DW_UNSND (attr2) != 0)
20201                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
20202                 {
20203                   /* A variable with DW_AT_external is never static, but it
20204                      may be block-scoped.  */
20205                   list_to_add = (cu->list_in_scope == &file_symbols
20206                                  ? &global_symbols : cu->list_in_scope);
20207
20208                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20209                 }
20210               else if (!die_is_declaration (die, cu))
20211                 {
20212                   /* Use the default LOC_OPTIMIZED_OUT class.  */
20213                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
20214                   if (!suppress_add)
20215                     list_to_add = cu->list_in_scope;
20216                 }
20217             }
20218           break;
20219         case DW_TAG_formal_parameter:
20220           /* If we are inside a function, mark this as an argument.  If
20221              not, we might be looking at an argument to an inlined function
20222              when we do not have enough information to show inlined frames;
20223              pretend it's a local variable in that case so that the user can
20224              still see it.  */
20225           if (context_stack_depth > 0
20226               && context_stack[context_stack_depth - 1].name != NULL)
20227             SYMBOL_IS_ARGUMENT (sym) = 1;
20228           attr = dwarf2_attr (die, DW_AT_location, cu);
20229           if (attr)
20230             {
20231               var_decode_location (attr, sym, cu);
20232             }
20233           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20234           if (attr)
20235             {
20236               dwarf2_const_value (attr, sym, cu);
20237             }
20238
20239           list_to_add = cu->list_in_scope;
20240           break;
20241         case DW_TAG_unspecified_parameters:
20242           /* From varargs functions; gdb doesn't seem to have any
20243              interest in this information, so just ignore it for now.
20244              (FIXME?) */
20245           break;
20246         case DW_TAG_template_type_param:
20247           suppress_add = 1;
20248           /* Fall through.  */
20249         case DW_TAG_class_type:
20250         case DW_TAG_interface_type:
20251         case DW_TAG_structure_type:
20252         case DW_TAG_union_type:
20253         case DW_TAG_set_type:
20254         case DW_TAG_enumeration_type:
20255           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20256           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
20257
20258           {
20259             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
20260                really ever be static objects: otherwise, if you try
20261                to, say, break of a class's method and you're in a file
20262                which doesn't mention that class, it won't work unless
20263                the check for all static symbols in lookup_symbol_aux
20264                saves you.  See the OtherFileClass tests in
20265                gdb.c++/namespace.exp.  */
20266
20267             if (!suppress_add)
20268               {
20269                 list_to_add = (cu->list_in_scope == &file_symbols
20270                                && cu->language == language_cplus
20271                                ? &global_symbols : cu->list_in_scope);
20272
20273                 /* The semantics of C++ state that "struct foo {
20274                    ... }" also defines a typedef for "foo".  */
20275                 if (cu->language == language_cplus
20276                     || cu->language == language_ada
20277                     || cu->language == language_d
20278                     || cu->language == language_rust)
20279                   {
20280                     /* The symbol's name is already allocated along
20281                        with this objfile, so we don't need to
20282                        duplicate it for the type.  */
20283                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
20284                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
20285                   }
20286               }
20287           }
20288           break;
20289         case DW_TAG_typedef:
20290           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20291           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20292           list_to_add = cu->list_in_scope;
20293           break;
20294         case DW_TAG_base_type:
20295         case DW_TAG_subrange_type:
20296           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20297           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20298           list_to_add = cu->list_in_scope;
20299           break;
20300         case DW_TAG_enumerator:
20301           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20302           if (attr)
20303             {
20304               dwarf2_const_value (attr, sym, cu);
20305             }
20306           {
20307             /* NOTE: carlton/2003-11-10: See comment above in the
20308                DW_TAG_class_type, etc. block.  */
20309
20310             list_to_add = (cu->list_in_scope == &file_symbols
20311                            && cu->language == language_cplus
20312                            ? &global_symbols : cu->list_in_scope);
20313           }
20314           break;
20315         case DW_TAG_imported_declaration:
20316         case DW_TAG_namespace:
20317           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20318           list_to_add = &global_symbols;
20319           break;
20320         case DW_TAG_module:
20321           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20322           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
20323           list_to_add = &global_symbols;
20324           break;
20325         case DW_TAG_common_block:
20326           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
20327           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
20328           add_symbol_to_list (sym, cu->list_in_scope);
20329           break;
20330         default:
20331           /* Not a tag we recognize.  Hopefully we aren't processing
20332              trash data, but since we must specifically ignore things
20333              we don't recognize, there is nothing else we should do at
20334              this point.  */
20335           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
20336                      dwarf_tag_name (die->tag));
20337           break;
20338         }
20339
20340       if (suppress_add)
20341         {
20342           sym->hash_next = objfile->template_symbols;
20343           objfile->template_symbols = sym;
20344           list_to_add = NULL;
20345         }
20346
20347       if (list_to_add != NULL)
20348         add_symbol_to_list (sym, list_to_add);
20349
20350       /* For the benefit of old versions of GCC, check for anonymous
20351          namespaces based on the demangled name.  */
20352       if (!cu->processing_has_namespace_info
20353           && cu->language == language_cplus)
20354         cp_scan_for_anonymous_namespaces (sym, objfile);
20355     }
20356   return (sym);
20357 }
20358
20359 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
20360
20361 static struct symbol *
20362 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20363 {
20364   return new_symbol_full (die, type, cu, NULL);
20365 }
20366
20367 /* Given an attr with a DW_FORM_dataN value in host byte order,
20368    zero-extend it as appropriate for the symbol's type.  The DWARF
20369    standard (v4) is not entirely clear about the meaning of using
20370    DW_FORM_dataN for a constant with a signed type, where the type is
20371    wider than the data.  The conclusion of a discussion on the DWARF
20372    list was that this is unspecified.  We choose to always zero-extend
20373    because that is the interpretation long in use by GCC.  */
20374
20375 static gdb_byte *
20376 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
20377                          struct dwarf2_cu *cu, LONGEST *value, int bits)
20378 {
20379   struct objfile *objfile = cu->objfile;
20380   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
20381                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
20382   LONGEST l = DW_UNSND (attr);
20383
20384   if (bits < sizeof (*value) * 8)
20385     {
20386       l &= ((LONGEST) 1 << bits) - 1;
20387       *value = l;
20388     }
20389   else if (bits == sizeof (*value) * 8)
20390     *value = l;
20391   else
20392     {
20393       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
20394       store_unsigned_integer (bytes, bits / 8, byte_order, l);
20395       return bytes;
20396     }
20397
20398   return NULL;
20399 }
20400
20401 /* Read a constant value from an attribute.  Either set *VALUE, or if
20402    the value does not fit in *VALUE, set *BYTES - either already
20403    allocated on the objfile obstack, or newly allocated on OBSTACK,
20404    or, set *BATON, if we translated the constant to a location
20405    expression.  */
20406
20407 static void
20408 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
20409                          const char *name, struct obstack *obstack,
20410                          struct dwarf2_cu *cu,
20411                          LONGEST *value, const gdb_byte **bytes,
20412                          struct dwarf2_locexpr_baton **baton)
20413 {
20414   struct objfile *objfile = cu->objfile;
20415   struct comp_unit_head *cu_header = &cu->header;
20416   struct dwarf_block *blk;
20417   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
20418                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20419
20420   *value = 0;
20421   *bytes = NULL;
20422   *baton = NULL;
20423
20424   switch (attr->form)
20425     {
20426     case DW_FORM_addr:
20427     case DW_FORM_GNU_addr_index:
20428       {
20429         gdb_byte *data;
20430
20431         if (TYPE_LENGTH (type) != cu_header->addr_size)
20432           dwarf2_const_value_length_mismatch_complaint (name,
20433                                                         cu_header->addr_size,
20434                                                         TYPE_LENGTH (type));
20435         /* Symbols of this form are reasonably rare, so we just
20436            piggyback on the existing location code rather than writing
20437            a new implementation of symbol_computed_ops.  */
20438         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
20439         (*baton)->per_cu = cu->per_cu;
20440         gdb_assert ((*baton)->per_cu);
20441
20442         (*baton)->size = 2 + cu_header->addr_size;
20443         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
20444         (*baton)->data = data;
20445
20446         data[0] = DW_OP_addr;
20447         store_unsigned_integer (&data[1], cu_header->addr_size,
20448                                 byte_order, DW_ADDR (attr));
20449         data[cu_header->addr_size + 1] = DW_OP_stack_value;
20450       }
20451       break;
20452     case DW_FORM_string:
20453     case DW_FORM_strp:
20454     case DW_FORM_GNU_str_index:
20455     case DW_FORM_GNU_strp_alt:
20456       /* DW_STRING is already allocated on the objfile obstack, point
20457          directly to it.  */
20458       *bytes = (const gdb_byte *) DW_STRING (attr);
20459       break;
20460     case DW_FORM_block1:
20461     case DW_FORM_block2:
20462     case DW_FORM_block4:
20463     case DW_FORM_block:
20464     case DW_FORM_exprloc:
20465     case DW_FORM_data16:
20466       blk = DW_BLOCK (attr);
20467       if (TYPE_LENGTH (type) != blk->size)
20468         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
20469                                                       TYPE_LENGTH (type));
20470       *bytes = blk->data;
20471       break;
20472
20473       /* The DW_AT_const_value attributes are supposed to carry the
20474          symbol's value "represented as it would be on the target
20475          architecture."  By the time we get here, it's already been
20476          converted to host endianness, so we just need to sign- or
20477          zero-extend it as appropriate.  */
20478     case DW_FORM_data1:
20479       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
20480       break;
20481     case DW_FORM_data2:
20482       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
20483       break;
20484     case DW_FORM_data4:
20485       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
20486       break;
20487     case DW_FORM_data8:
20488       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
20489       break;
20490
20491     case DW_FORM_sdata:
20492     case DW_FORM_implicit_const:
20493       *value = DW_SND (attr);
20494       break;
20495
20496     case DW_FORM_udata:
20497       *value = DW_UNSND (attr);
20498       break;
20499
20500     default:
20501       complaint (&symfile_complaints,
20502                  _("unsupported const value attribute form: '%s'"),
20503                  dwarf_form_name (attr->form));
20504       *value = 0;
20505       break;
20506     }
20507 }
20508
20509
20510 /* Copy constant value from an attribute to a symbol.  */
20511
20512 static void
20513 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
20514                     struct dwarf2_cu *cu)
20515 {
20516   struct objfile *objfile = cu->objfile;
20517   LONGEST value;
20518   const gdb_byte *bytes;
20519   struct dwarf2_locexpr_baton *baton;
20520
20521   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
20522                            SYMBOL_PRINT_NAME (sym),
20523                            &objfile->objfile_obstack, cu,
20524                            &value, &bytes, &baton);
20525
20526   if (baton != NULL)
20527     {
20528       SYMBOL_LOCATION_BATON (sym) = baton;
20529       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
20530     }
20531   else if (bytes != NULL)
20532      {
20533       SYMBOL_VALUE_BYTES (sym) = bytes;
20534       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
20535     }
20536   else
20537     {
20538       SYMBOL_VALUE (sym) = value;
20539       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
20540     }
20541 }
20542
20543 /* Return the type of the die in question using its DW_AT_type attribute.  */
20544
20545 static struct type *
20546 die_type (struct die_info *die, struct dwarf2_cu *cu)
20547 {
20548   struct attribute *type_attr;
20549
20550   type_attr = dwarf2_attr (die, DW_AT_type, cu);
20551   if (!type_attr)
20552     {
20553       /* A missing DW_AT_type represents a void type.  */
20554       return objfile_type (cu->objfile)->builtin_void;
20555     }
20556
20557   return lookup_die_type (die, type_attr, cu);
20558 }
20559
20560 /* True iff CU's producer generates GNAT Ada auxiliary information
20561    that allows to find parallel types through that information instead
20562    of having to do expensive parallel lookups by type name.  */
20563
20564 static int
20565 need_gnat_info (struct dwarf2_cu *cu)
20566 {
20567   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
20568      of GNAT produces this auxiliary information, without any indication
20569      that it is produced.  Part of enhancing the FSF version of GNAT
20570      to produce that information will be to put in place an indicator
20571      that we can use in order to determine whether the descriptive type
20572      info is available or not.  One suggestion that has been made is
20573      to use a new attribute, attached to the CU die.  For now, assume
20574      that the descriptive type info is not available.  */
20575   return 0;
20576 }
20577
20578 /* Return the auxiliary type of the die in question using its
20579    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
20580    attribute is not present.  */
20581
20582 static struct type *
20583 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
20584 {
20585   struct attribute *type_attr;
20586
20587   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
20588   if (!type_attr)
20589     return NULL;
20590
20591   return lookup_die_type (die, type_attr, cu);
20592 }
20593
20594 /* If DIE has a descriptive_type attribute, then set the TYPE's
20595    descriptive type accordingly.  */
20596
20597 static void
20598 set_descriptive_type (struct type *type, struct die_info *die,
20599                       struct dwarf2_cu *cu)
20600 {
20601   struct type *descriptive_type = die_descriptive_type (die, cu);
20602
20603   if (descriptive_type)
20604     {
20605       ALLOCATE_GNAT_AUX_TYPE (type);
20606       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
20607     }
20608 }
20609
20610 /* Return the containing type of the die in question using its
20611    DW_AT_containing_type attribute.  */
20612
20613 static struct type *
20614 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
20615 {
20616   struct attribute *type_attr;
20617
20618   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
20619   if (!type_attr)
20620     error (_("Dwarf Error: Problem turning containing type into gdb type "
20621              "[in module %s]"), objfile_name (cu->objfile));
20622
20623   return lookup_die_type (die, type_attr, cu);
20624 }
20625
20626 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
20627
20628 static struct type *
20629 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
20630 {
20631   struct objfile *objfile = dwarf2_per_objfile->objfile;
20632   char *message, *saved;
20633
20634   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
20635                         objfile_name (objfile),
20636                         to_underlying (cu->header.sect_off),
20637                         to_underlying (die->sect_off));
20638   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
20639                                   message, strlen (message));
20640   xfree (message);
20641
20642   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
20643 }
20644
20645 /* Look up the type of DIE in CU using its type attribute ATTR.
20646    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
20647    DW_AT_containing_type.
20648    If there is no type substitute an error marker.  */
20649
20650 static struct type *
20651 lookup_die_type (struct die_info *die, const struct attribute *attr,
20652                  struct dwarf2_cu *cu)
20653 {
20654   struct objfile *objfile = cu->objfile;
20655   struct type *this_type;
20656
20657   gdb_assert (attr->name == DW_AT_type
20658               || attr->name == DW_AT_GNAT_descriptive_type
20659               || attr->name == DW_AT_containing_type);
20660
20661   /* First see if we have it cached.  */
20662
20663   if (attr->form == DW_FORM_GNU_ref_alt)
20664     {
20665       struct dwarf2_per_cu_data *per_cu;
20666       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20667
20668       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20669       this_type = get_die_type_at_offset (sect_off, per_cu);
20670     }
20671   else if (attr_form_is_ref (attr))
20672     {
20673       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20674
20675       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20676     }
20677   else if (attr->form == DW_FORM_ref_sig8)
20678     {
20679       ULONGEST signature = DW_SIGNATURE (attr);
20680
20681       return get_signatured_type (die, signature, cu);
20682     }
20683   else
20684     {
20685       complaint (&symfile_complaints,
20686                  _("Dwarf Error: Bad type attribute %s in DIE"
20687                    " at 0x%x [in module %s]"),
20688                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20689                  objfile_name (objfile));
20690       return build_error_marker_type (cu, die);
20691     }
20692
20693   /* If not cached we need to read it in.  */
20694
20695   if (this_type == NULL)
20696     {
20697       struct die_info *type_die = NULL;
20698       struct dwarf2_cu *type_cu = cu;
20699
20700       if (attr_form_is_ref (attr))
20701         type_die = follow_die_ref (die, attr, &type_cu);
20702       if (type_die == NULL)
20703         return build_error_marker_type (cu, die);
20704       /* If we find the type now, it's probably because the type came
20705          from an inter-CU reference and the type's CU got expanded before
20706          ours.  */
20707       this_type = read_type_die (type_die, type_cu);
20708     }
20709
20710   /* If we still don't have a type use an error marker.  */
20711
20712   if (this_type == NULL)
20713     return build_error_marker_type (cu, die);
20714
20715   return this_type;
20716 }
20717
20718 /* Return the type in DIE, CU.
20719    Returns NULL for invalid types.
20720
20721    This first does a lookup in die_type_hash,
20722    and only reads the die in if necessary.
20723
20724    NOTE: This can be called when reading in partial or full symbols.  */
20725
20726 static struct type *
20727 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20728 {
20729   struct type *this_type;
20730
20731   this_type = get_die_type (die, cu);
20732   if (this_type)
20733     return this_type;
20734
20735   return read_type_die_1 (die, cu);
20736 }
20737
20738 /* Read the type in DIE, CU.
20739    Returns NULL for invalid types.  */
20740
20741 static struct type *
20742 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20743 {
20744   struct type *this_type = NULL;
20745
20746   switch (die->tag)
20747     {
20748     case DW_TAG_class_type:
20749     case DW_TAG_interface_type:
20750     case DW_TAG_structure_type:
20751     case DW_TAG_union_type:
20752       this_type = read_structure_type (die, cu);
20753       break;
20754     case DW_TAG_enumeration_type:
20755       this_type = read_enumeration_type (die, cu);
20756       break;
20757     case DW_TAG_subprogram:
20758     case DW_TAG_subroutine_type:
20759     case DW_TAG_inlined_subroutine:
20760       this_type = read_subroutine_type (die, cu);
20761       break;
20762     case DW_TAG_array_type:
20763       this_type = read_array_type (die, cu);
20764       break;
20765     case DW_TAG_set_type:
20766       this_type = read_set_type (die, cu);
20767       break;
20768     case DW_TAG_pointer_type:
20769       this_type = read_tag_pointer_type (die, cu);
20770       break;
20771     case DW_TAG_ptr_to_member_type:
20772       this_type = read_tag_ptr_to_member_type (die, cu);
20773       break;
20774     case DW_TAG_reference_type:
20775       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20776       break;
20777     case DW_TAG_rvalue_reference_type:
20778       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20779       break;
20780     case DW_TAG_const_type:
20781       this_type = read_tag_const_type (die, cu);
20782       break;
20783     case DW_TAG_volatile_type:
20784       this_type = read_tag_volatile_type (die, cu);
20785       break;
20786     case DW_TAG_restrict_type:
20787       this_type = read_tag_restrict_type (die, cu);
20788       break;
20789     case DW_TAG_string_type:
20790       this_type = read_tag_string_type (die, cu);
20791       break;
20792     case DW_TAG_typedef:
20793       this_type = read_typedef (die, cu);
20794       break;
20795     case DW_TAG_subrange_type:
20796       this_type = read_subrange_type (die, cu);
20797       break;
20798     case DW_TAG_base_type:
20799       this_type = read_base_type (die, cu);
20800       break;
20801     case DW_TAG_unspecified_type:
20802       this_type = read_unspecified_type (die, cu);
20803       break;
20804     case DW_TAG_namespace:
20805       this_type = read_namespace_type (die, cu);
20806       break;
20807     case DW_TAG_module:
20808       this_type = read_module_type (die, cu);
20809       break;
20810     case DW_TAG_atomic_type:
20811       this_type = read_tag_atomic_type (die, cu);
20812       break;
20813     default:
20814       complaint (&symfile_complaints,
20815                  _("unexpected tag in read_type_die: '%s'"),
20816                  dwarf_tag_name (die->tag));
20817       break;
20818     }
20819
20820   return this_type;
20821 }
20822
20823 /* See if we can figure out if the class lives in a namespace.  We do
20824    this by looking for a member function; its demangled name will
20825    contain namespace info, if there is any.
20826    Return the computed name or NULL.
20827    Space for the result is allocated on the objfile's obstack.
20828    This is the full-die version of guess_partial_die_structure_name.
20829    In this case we know DIE has no useful parent.  */
20830
20831 static char *
20832 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20833 {
20834   struct die_info *spec_die;
20835   struct dwarf2_cu *spec_cu;
20836   struct die_info *child;
20837
20838   spec_cu = cu;
20839   spec_die = die_specification (die, &spec_cu);
20840   if (spec_die != NULL)
20841     {
20842       die = spec_die;
20843       cu = spec_cu;
20844     }
20845
20846   for (child = die->child;
20847        child != NULL;
20848        child = child->sibling)
20849     {
20850       if (child->tag == DW_TAG_subprogram)
20851         {
20852           const char *linkage_name = dw2_linkage_name (child, cu);
20853
20854           if (linkage_name != NULL)
20855             {
20856               char *actual_name
20857                 = language_class_name_from_physname (cu->language_defn,
20858                                                      linkage_name);
20859               char *name = NULL;
20860
20861               if (actual_name != NULL)
20862                 {
20863                   const char *die_name = dwarf2_name (die, cu);
20864
20865                   if (die_name != NULL
20866                       && strcmp (die_name, actual_name) != 0)
20867                     {
20868                       /* Strip off the class name from the full name.
20869                          We want the prefix.  */
20870                       int die_name_len = strlen (die_name);
20871                       int actual_name_len = strlen (actual_name);
20872
20873                       /* Test for '::' as a sanity check.  */
20874                       if (actual_name_len > die_name_len + 2
20875                           && actual_name[actual_name_len
20876                                          - die_name_len - 1] == ':')
20877                         name = (char *) obstack_copy0 (
20878                           &cu->objfile->per_bfd->storage_obstack,
20879                           actual_name, actual_name_len - die_name_len - 2);
20880                     }
20881                 }
20882               xfree (actual_name);
20883               return name;
20884             }
20885         }
20886     }
20887
20888   return NULL;
20889 }
20890
20891 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20892    prefix part in such case.  See
20893    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20894
20895 static const char *
20896 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20897 {
20898   struct attribute *attr;
20899   const char *base;
20900
20901   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20902       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20903     return NULL;
20904
20905   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20906     return NULL;
20907
20908   attr = dw2_linkage_name_attr (die, cu);
20909   if (attr == NULL || DW_STRING (attr) == NULL)
20910     return NULL;
20911
20912   /* dwarf2_name had to be already called.  */
20913   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20914
20915   /* Strip the base name, keep any leading namespaces/classes.  */
20916   base = strrchr (DW_STRING (attr), ':');
20917   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20918     return "";
20919
20920   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20921                                  DW_STRING (attr),
20922                                  &base[-1] - DW_STRING (attr));
20923 }
20924
20925 /* Return the name of the namespace/class that DIE is defined within,
20926    or "" if we can't tell.  The caller should not xfree the result.
20927
20928    For example, if we're within the method foo() in the following
20929    code:
20930
20931    namespace N {
20932      class C {
20933        void foo () {
20934        }
20935      };
20936    }
20937
20938    then determine_prefix on foo's die will return "N::C".  */
20939
20940 static const char *
20941 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20942 {
20943   struct die_info *parent, *spec_die;
20944   struct dwarf2_cu *spec_cu;
20945   struct type *parent_type;
20946   const char *retval;
20947
20948   if (cu->language != language_cplus
20949       && cu->language != language_fortran && cu->language != language_d
20950       && cu->language != language_rust)
20951     return "";
20952
20953   retval = anonymous_struct_prefix (die, cu);
20954   if (retval)
20955     return retval;
20956
20957   /* We have to be careful in the presence of DW_AT_specification.
20958      For example, with GCC 3.4, given the code
20959
20960      namespace N {
20961        void foo() {
20962          // Definition of N::foo.
20963        }
20964      }
20965
20966      then we'll have a tree of DIEs like this:
20967
20968      1: DW_TAG_compile_unit
20969        2: DW_TAG_namespace        // N
20970          3: DW_TAG_subprogram     // declaration of N::foo
20971        4: DW_TAG_subprogram       // definition of N::foo
20972             DW_AT_specification   // refers to die #3
20973
20974      Thus, when processing die #4, we have to pretend that we're in
20975      the context of its DW_AT_specification, namely the contex of die
20976      #3.  */
20977   spec_cu = cu;
20978   spec_die = die_specification (die, &spec_cu);
20979   if (spec_die == NULL)
20980     parent = die->parent;
20981   else
20982     {
20983       parent = spec_die->parent;
20984       cu = spec_cu;
20985     }
20986
20987   if (parent == NULL)
20988     return "";
20989   else if (parent->building_fullname)
20990     {
20991       const char *name;
20992       const char *parent_name;
20993
20994       /* It has been seen on RealView 2.2 built binaries,
20995          DW_TAG_template_type_param types actually _defined_ as
20996          children of the parent class:
20997
20998          enum E {};
20999          template class <class Enum> Class{};
21000          Class<enum E> class_e;
21001
21002          1: DW_TAG_class_type (Class)
21003            2: DW_TAG_enumeration_type (E)
21004              3: DW_TAG_enumerator (enum1:0)
21005              3: DW_TAG_enumerator (enum2:1)
21006              ...
21007            2: DW_TAG_template_type_param
21008               DW_AT_type  DW_FORM_ref_udata (E)
21009
21010          Besides being broken debug info, it can put GDB into an
21011          infinite loop.  Consider:
21012
21013          When we're building the full name for Class<E>, we'll start
21014          at Class, and go look over its template type parameters,
21015          finding E.  We'll then try to build the full name of E, and
21016          reach here.  We're now trying to build the full name of E,
21017          and look over the parent DIE for containing scope.  In the
21018          broken case, if we followed the parent DIE of E, we'd again
21019          find Class, and once again go look at its template type
21020          arguments, etc., etc.  Simply don't consider such parent die
21021          as source-level parent of this die (it can't be, the language
21022          doesn't allow it), and break the loop here.  */
21023       name = dwarf2_name (die, cu);
21024       parent_name = dwarf2_name (parent, cu);
21025       complaint (&symfile_complaints,
21026                  _("template param type '%s' defined within parent '%s'"),
21027                  name ? name : "<unknown>",
21028                  parent_name ? parent_name : "<unknown>");
21029       return "";
21030     }
21031   else
21032     switch (parent->tag)
21033       {
21034       case DW_TAG_namespace:
21035         parent_type = read_type_die (parent, cu);
21036         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
21037            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
21038            Work around this problem here.  */
21039         if (cu->language == language_cplus
21040             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
21041           return "";
21042         /* We give a name to even anonymous namespaces.  */
21043         return TYPE_TAG_NAME (parent_type);
21044       case DW_TAG_class_type:
21045       case DW_TAG_interface_type:
21046       case DW_TAG_structure_type:
21047       case DW_TAG_union_type:
21048       case DW_TAG_module:
21049         parent_type = read_type_die (parent, cu);
21050         if (TYPE_TAG_NAME (parent_type) != NULL)
21051           return TYPE_TAG_NAME (parent_type);
21052         else
21053           /* An anonymous structure is only allowed non-static data
21054              members; no typedefs, no member functions, et cetera.
21055              So it does not need a prefix.  */
21056           return "";
21057       case DW_TAG_compile_unit:
21058       case DW_TAG_partial_unit:
21059         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
21060         if (cu->language == language_cplus
21061             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
21062             && die->child != NULL
21063             && (die->tag == DW_TAG_class_type
21064                 || die->tag == DW_TAG_structure_type
21065                 || die->tag == DW_TAG_union_type))
21066           {
21067             char *name = guess_full_die_structure_name (die, cu);
21068             if (name != NULL)
21069               return name;
21070           }
21071         return "";
21072       case DW_TAG_enumeration_type:
21073         parent_type = read_type_die (parent, cu);
21074         if (TYPE_DECLARED_CLASS (parent_type))
21075           {
21076             if (TYPE_TAG_NAME (parent_type) != NULL)
21077               return TYPE_TAG_NAME (parent_type);
21078             return "";
21079           }
21080         /* Fall through.  */
21081       default:
21082         return determine_prefix (parent, cu);
21083       }
21084 }
21085
21086 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
21087    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
21088    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
21089    an obconcat, otherwise allocate storage for the result.  The CU argument is
21090    used to determine the language and hence, the appropriate separator.  */
21091
21092 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
21093
21094 static char *
21095 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
21096                  int physname, struct dwarf2_cu *cu)
21097 {
21098   const char *lead = "";
21099   const char *sep;
21100
21101   if (suffix == NULL || suffix[0] == '\0'
21102       || prefix == NULL || prefix[0] == '\0')
21103     sep = "";
21104   else if (cu->language == language_d)
21105     {
21106       /* For D, the 'main' function could be defined in any module, but it
21107          should never be prefixed.  */
21108       if (strcmp (suffix, "D main") == 0)
21109         {
21110           prefix = "";
21111           sep = "";
21112         }
21113       else
21114         sep = ".";
21115     }
21116   else if (cu->language == language_fortran && physname)
21117     {
21118       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
21119          DW_AT_MIPS_linkage_name is preferred and used instead.  */
21120
21121       lead = "__";
21122       sep = "_MOD_";
21123     }
21124   else
21125     sep = "::";
21126
21127   if (prefix == NULL)
21128     prefix = "";
21129   if (suffix == NULL)
21130     suffix = "";
21131
21132   if (obs == NULL)
21133     {
21134       char *retval
21135         = ((char *)
21136            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
21137
21138       strcpy (retval, lead);
21139       strcat (retval, prefix);
21140       strcat (retval, sep);
21141       strcat (retval, suffix);
21142       return retval;
21143     }
21144   else
21145     {
21146       /* We have an obstack.  */
21147       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
21148     }
21149 }
21150
21151 /* Return sibling of die, NULL if no sibling.  */
21152
21153 static struct die_info *
21154 sibling_die (struct die_info *die)
21155 {
21156   return die->sibling;
21157 }
21158
21159 /* Get name of a die, return NULL if not found.  */
21160
21161 static const char *
21162 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
21163                           struct obstack *obstack)
21164 {
21165   if (name && cu->language == language_cplus)
21166     {
21167       std::string canon_name = cp_canonicalize_string (name);
21168
21169       if (!canon_name.empty ())
21170         {
21171           if (canon_name != name)
21172             name = (const char *) obstack_copy0 (obstack,
21173                                                  canon_name.c_str (),
21174                                                  canon_name.length ());
21175         }
21176     }
21177
21178   return name;
21179 }
21180
21181 /* Get name of a die, return NULL if not found.
21182    Anonymous namespaces are converted to their magic string.  */
21183
21184 static const char *
21185 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
21186 {
21187   struct attribute *attr;
21188
21189   attr = dwarf2_attr (die, DW_AT_name, cu);
21190   if ((!attr || !DW_STRING (attr))
21191       && die->tag != DW_TAG_namespace
21192       && die->tag != DW_TAG_class_type
21193       && die->tag != DW_TAG_interface_type
21194       && die->tag != DW_TAG_structure_type
21195       && die->tag != DW_TAG_union_type)
21196     return NULL;
21197
21198   switch (die->tag)
21199     {
21200     case DW_TAG_compile_unit:
21201     case DW_TAG_partial_unit:
21202       /* Compilation units have a DW_AT_name that is a filename, not
21203          a source language identifier.  */
21204     case DW_TAG_enumeration_type:
21205     case DW_TAG_enumerator:
21206       /* These tags always have simple identifiers already; no need
21207          to canonicalize them.  */
21208       return DW_STRING (attr);
21209
21210     case DW_TAG_namespace:
21211       if (attr != NULL && DW_STRING (attr) != NULL)
21212         return DW_STRING (attr);
21213       return CP_ANONYMOUS_NAMESPACE_STR;
21214
21215     case DW_TAG_class_type:
21216     case DW_TAG_interface_type:
21217     case DW_TAG_structure_type:
21218     case DW_TAG_union_type:
21219       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
21220          structures or unions.  These were of the form "._%d" in GCC 4.1,
21221          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
21222          and GCC 4.4.  We work around this problem by ignoring these.  */
21223       if (attr && DW_STRING (attr)
21224           && (startswith (DW_STRING (attr), "._")
21225               || startswith (DW_STRING (attr), "<anonymous")))
21226         return NULL;
21227
21228       /* GCC might emit a nameless typedef that has a linkage name.  See
21229          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
21230       if (!attr || DW_STRING (attr) == NULL)
21231         {
21232           char *demangled = NULL;
21233
21234           attr = dw2_linkage_name_attr (die, cu);
21235           if (attr == NULL || DW_STRING (attr) == NULL)
21236             return NULL;
21237
21238           /* Avoid demangling DW_STRING (attr) the second time on a second
21239              call for the same DIE.  */
21240           if (!DW_STRING_IS_CANONICAL (attr))
21241             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
21242
21243           if (demangled)
21244             {
21245               const char *base;
21246
21247               /* FIXME: we already did this for the partial symbol... */
21248               DW_STRING (attr)
21249                 = ((const char *)
21250                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
21251                                   demangled, strlen (demangled)));
21252               DW_STRING_IS_CANONICAL (attr) = 1;
21253               xfree (demangled);
21254
21255               /* Strip any leading namespaces/classes, keep only the base name.
21256                  DW_AT_name for named DIEs does not contain the prefixes.  */
21257               base = strrchr (DW_STRING (attr), ':');
21258               if (base && base > DW_STRING (attr) && base[-1] == ':')
21259                 return &base[1];
21260               else
21261                 return DW_STRING (attr);
21262             }
21263         }
21264       break;
21265
21266     default:
21267       break;
21268     }
21269
21270   if (!DW_STRING_IS_CANONICAL (attr))
21271     {
21272       DW_STRING (attr)
21273         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
21274                                     &cu->objfile->per_bfd->storage_obstack);
21275       DW_STRING_IS_CANONICAL (attr) = 1;
21276     }
21277   return DW_STRING (attr);
21278 }
21279
21280 /* Return the die that this die in an extension of, or NULL if there
21281    is none.  *EXT_CU is the CU containing DIE on input, and the CU
21282    containing the return value on output.  */
21283
21284 static struct die_info *
21285 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
21286 {
21287   struct attribute *attr;
21288
21289   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
21290   if (attr == NULL)
21291     return NULL;
21292
21293   return follow_die_ref (die, attr, ext_cu);
21294 }
21295
21296 /* Convert a DIE tag into its string name.  */
21297
21298 static const char *
21299 dwarf_tag_name (unsigned tag)
21300 {
21301   const char *name = get_DW_TAG_name (tag);
21302
21303   if (name == NULL)
21304     return "DW_TAG_<unknown>";
21305
21306   return name;
21307 }
21308
21309 /* Convert a DWARF attribute code into its string name.  */
21310
21311 static const char *
21312 dwarf_attr_name (unsigned attr)
21313 {
21314   const char *name;
21315
21316 #ifdef MIPS /* collides with DW_AT_HP_block_index */
21317   if (attr == DW_AT_MIPS_fde)
21318     return "DW_AT_MIPS_fde";
21319 #else
21320   if (attr == DW_AT_HP_block_index)
21321     return "DW_AT_HP_block_index";
21322 #endif
21323
21324   name = get_DW_AT_name (attr);
21325
21326   if (name == NULL)
21327     return "DW_AT_<unknown>";
21328
21329   return name;
21330 }
21331
21332 /* Convert a DWARF value form code into its string name.  */
21333
21334 static const char *
21335 dwarf_form_name (unsigned form)
21336 {
21337   const char *name = get_DW_FORM_name (form);
21338
21339   if (name == NULL)
21340     return "DW_FORM_<unknown>";
21341
21342   return name;
21343 }
21344
21345 static const char *
21346 dwarf_bool_name (unsigned mybool)
21347 {
21348   if (mybool)
21349     return "TRUE";
21350   else
21351     return "FALSE";
21352 }
21353
21354 /* Convert a DWARF type code into its string name.  */
21355
21356 static const char *
21357 dwarf_type_encoding_name (unsigned enc)
21358 {
21359   const char *name = get_DW_ATE_name (enc);
21360
21361   if (name == NULL)
21362     return "DW_ATE_<unknown>";
21363
21364   return name;
21365 }
21366
21367 static void
21368 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
21369 {
21370   unsigned int i;
21371
21372   print_spaces (indent, f);
21373   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
21374                       dwarf_tag_name (die->tag), die->abbrev,
21375                       to_underlying (die->sect_off));
21376
21377   if (die->parent != NULL)
21378     {
21379       print_spaces (indent, f);
21380       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
21381                           to_underlying (die->parent->sect_off));
21382     }
21383
21384   print_spaces (indent, f);
21385   fprintf_unfiltered (f, "  has children: %s\n",
21386            dwarf_bool_name (die->child != NULL));
21387
21388   print_spaces (indent, f);
21389   fprintf_unfiltered (f, "  attributes:\n");
21390
21391   for (i = 0; i < die->num_attrs; ++i)
21392     {
21393       print_spaces (indent, f);
21394       fprintf_unfiltered (f, "    %s (%s) ",
21395                dwarf_attr_name (die->attrs[i].name),
21396                dwarf_form_name (die->attrs[i].form));
21397
21398       switch (die->attrs[i].form)
21399         {
21400         case DW_FORM_addr:
21401         case DW_FORM_GNU_addr_index:
21402           fprintf_unfiltered (f, "address: ");
21403           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
21404           break;
21405         case DW_FORM_block2:
21406         case DW_FORM_block4:
21407         case DW_FORM_block:
21408         case DW_FORM_block1:
21409           fprintf_unfiltered (f, "block: size %s",
21410                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21411           break;
21412         case DW_FORM_exprloc:
21413           fprintf_unfiltered (f, "expression: size %s",
21414                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21415           break;
21416         case DW_FORM_data16:
21417           fprintf_unfiltered (f, "constant of 16 bytes");
21418           break;
21419         case DW_FORM_ref_addr:
21420           fprintf_unfiltered (f, "ref address: ");
21421           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21422           break;
21423         case DW_FORM_GNU_ref_alt:
21424           fprintf_unfiltered (f, "alt ref address: ");
21425           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21426           break;
21427         case DW_FORM_ref1:
21428         case DW_FORM_ref2:
21429         case DW_FORM_ref4:
21430         case DW_FORM_ref8:
21431         case DW_FORM_ref_udata:
21432           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
21433                               (long) (DW_UNSND (&die->attrs[i])));
21434           break;
21435         case DW_FORM_data1:
21436         case DW_FORM_data2:
21437         case DW_FORM_data4:
21438         case DW_FORM_data8:
21439         case DW_FORM_udata:
21440         case DW_FORM_sdata:
21441           fprintf_unfiltered (f, "constant: %s",
21442                               pulongest (DW_UNSND (&die->attrs[i])));
21443           break;
21444         case DW_FORM_sec_offset:
21445           fprintf_unfiltered (f, "section offset: %s",
21446                               pulongest (DW_UNSND (&die->attrs[i])));
21447           break;
21448         case DW_FORM_ref_sig8:
21449           fprintf_unfiltered (f, "signature: %s",
21450                               hex_string (DW_SIGNATURE (&die->attrs[i])));
21451           break;
21452         case DW_FORM_string:
21453         case DW_FORM_strp:
21454         case DW_FORM_line_strp:
21455         case DW_FORM_GNU_str_index:
21456         case DW_FORM_GNU_strp_alt:
21457           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
21458                    DW_STRING (&die->attrs[i])
21459                    ? DW_STRING (&die->attrs[i]) : "",
21460                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
21461           break;
21462         case DW_FORM_flag:
21463           if (DW_UNSND (&die->attrs[i]))
21464             fprintf_unfiltered (f, "flag: TRUE");
21465           else
21466             fprintf_unfiltered (f, "flag: FALSE");
21467           break;
21468         case DW_FORM_flag_present:
21469           fprintf_unfiltered (f, "flag: TRUE");
21470           break;
21471         case DW_FORM_indirect:
21472           /* The reader will have reduced the indirect form to
21473              the "base form" so this form should not occur.  */
21474           fprintf_unfiltered (f, 
21475                               "unexpected attribute form: DW_FORM_indirect");
21476           break;
21477         case DW_FORM_implicit_const:
21478           fprintf_unfiltered (f, "constant: %s",
21479                               plongest (DW_SND (&die->attrs[i])));
21480           break;
21481         default:
21482           fprintf_unfiltered (f, "unsupported attribute form: %d.",
21483                    die->attrs[i].form);
21484           break;
21485         }
21486       fprintf_unfiltered (f, "\n");
21487     }
21488 }
21489
21490 static void
21491 dump_die_for_error (struct die_info *die)
21492 {
21493   dump_die_shallow (gdb_stderr, 0, die);
21494 }
21495
21496 static void
21497 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
21498 {
21499   int indent = level * 4;
21500
21501   gdb_assert (die != NULL);
21502
21503   if (level >= max_level)
21504     return;
21505
21506   dump_die_shallow (f, indent, die);
21507
21508   if (die->child != NULL)
21509     {
21510       print_spaces (indent, f);
21511       fprintf_unfiltered (f, "  Children:");
21512       if (level + 1 < max_level)
21513         {
21514           fprintf_unfiltered (f, "\n");
21515           dump_die_1 (f, level + 1, max_level, die->child);
21516         }
21517       else
21518         {
21519           fprintf_unfiltered (f,
21520                               " [not printed, max nesting level reached]\n");
21521         }
21522     }
21523
21524   if (die->sibling != NULL && level > 0)
21525     {
21526       dump_die_1 (f, level, max_level, die->sibling);
21527     }
21528 }
21529
21530 /* This is called from the pdie macro in gdbinit.in.
21531    It's not static so gcc will keep a copy callable from gdb.  */
21532
21533 void
21534 dump_die (struct die_info *die, int max_level)
21535 {
21536   dump_die_1 (gdb_stdlog, 0, max_level, die);
21537 }
21538
21539 static void
21540 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
21541 {
21542   void **slot;
21543
21544   slot = htab_find_slot_with_hash (cu->die_hash, die,
21545                                    to_underlying (die->sect_off),
21546                                    INSERT);
21547
21548   *slot = die;
21549 }
21550
21551 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
21552    required kind.  */
21553
21554 static sect_offset
21555 dwarf2_get_ref_die_offset (const struct attribute *attr)
21556 {
21557   if (attr_form_is_ref (attr))
21558     return (sect_offset) DW_UNSND (attr);
21559
21560   complaint (&symfile_complaints,
21561              _("unsupported die ref attribute form: '%s'"),
21562              dwarf_form_name (attr->form));
21563   return {};
21564 }
21565
21566 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
21567  * the value held by the attribute is not constant.  */
21568
21569 static LONGEST
21570 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
21571 {
21572   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
21573     return DW_SND (attr);
21574   else if (attr->form == DW_FORM_udata
21575            || attr->form == DW_FORM_data1
21576            || attr->form == DW_FORM_data2
21577            || attr->form == DW_FORM_data4
21578            || attr->form == DW_FORM_data8)
21579     return DW_UNSND (attr);
21580   else
21581     {
21582       /* For DW_FORM_data16 see attr_form_is_constant.  */
21583       complaint (&symfile_complaints,
21584                  _("Attribute value is not a constant (%s)"),
21585                  dwarf_form_name (attr->form));
21586       return default_value;
21587     }
21588 }
21589
21590 /* Follow reference or signature attribute ATTR of SRC_DIE.
21591    On entry *REF_CU is the CU of SRC_DIE.
21592    On exit *REF_CU is the CU of the result.  */
21593
21594 static struct die_info *
21595 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
21596                        struct dwarf2_cu **ref_cu)
21597 {
21598   struct die_info *die;
21599
21600   if (attr_form_is_ref (attr))
21601     die = follow_die_ref (src_die, attr, ref_cu);
21602   else if (attr->form == DW_FORM_ref_sig8)
21603     die = follow_die_sig (src_die, attr, ref_cu);
21604   else
21605     {
21606       dump_die_for_error (src_die);
21607       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
21608              objfile_name ((*ref_cu)->objfile));
21609     }
21610
21611   return die;
21612 }
21613
21614 /* Follow reference OFFSET.
21615    On entry *REF_CU is the CU of the source die referencing OFFSET.
21616    On exit *REF_CU is the CU of the result.
21617    Returns NULL if OFFSET is invalid.  */
21618
21619 static struct die_info *
21620 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
21621                    struct dwarf2_cu **ref_cu)
21622 {
21623   struct die_info temp_die;
21624   struct dwarf2_cu *target_cu, *cu = *ref_cu;
21625
21626   gdb_assert (cu->per_cu != NULL);
21627
21628   target_cu = cu;
21629
21630   if (cu->per_cu->is_debug_types)
21631     {
21632       /* .debug_types CUs cannot reference anything outside their CU.
21633          If they need to, they have to reference a signatured type via
21634          DW_FORM_ref_sig8.  */
21635       if (!offset_in_cu_p (&cu->header, sect_off))
21636         return NULL;
21637     }
21638   else if (offset_in_dwz != cu->per_cu->is_dwz
21639            || !offset_in_cu_p (&cu->header, sect_off))
21640     {
21641       struct dwarf2_per_cu_data *per_cu;
21642
21643       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
21644                                                  cu->objfile);
21645
21646       /* If necessary, add it to the queue and load its DIEs.  */
21647       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
21648         load_full_comp_unit (per_cu, cu->language);
21649
21650       target_cu = per_cu->cu;
21651     }
21652   else if (cu->dies == NULL)
21653     {
21654       /* We're loading full DIEs during partial symbol reading.  */
21655       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21656       load_full_comp_unit (cu->per_cu, language_minimal);
21657     }
21658
21659   *ref_cu = target_cu;
21660   temp_die.sect_off = sect_off;
21661   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21662                                                   &temp_die,
21663                                                   to_underlying (sect_off));
21664 }
21665
21666 /* Follow reference attribute ATTR of SRC_DIE.
21667    On entry *REF_CU is the CU of SRC_DIE.
21668    On exit *REF_CU is the CU of the result.  */
21669
21670 static struct die_info *
21671 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21672                 struct dwarf2_cu **ref_cu)
21673 {
21674   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21675   struct dwarf2_cu *cu = *ref_cu;
21676   struct die_info *die;
21677
21678   die = follow_die_offset (sect_off,
21679                            (attr->form == DW_FORM_GNU_ref_alt
21680                             || cu->per_cu->is_dwz),
21681                            ref_cu);
21682   if (!die)
21683     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21684            "at 0x%x [in module %s]"),
21685            to_underlying (sect_off), to_underlying (src_die->sect_off),
21686            objfile_name (cu->objfile));
21687
21688   return die;
21689 }
21690
21691 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21692    Returned value is intended for DW_OP_call*.  Returned
21693    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21694
21695 struct dwarf2_locexpr_baton
21696 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21697                                struct dwarf2_per_cu_data *per_cu,
21698                                CORE_ADDR (*get_frame_pc) (void *baton),
21699                                void *baton)
21700 {
21701   struct dwarf2_cu *cu;
21702   struct die_info *die;
21703   struct attribute *attr;
21704   struct dwarf2_locexpr_baton retval;
21705
21706   dw2_setup (per_cu->objfile);
21707
21708   if (per_cu->cu == NULL)
21709     load_cu (per_cu);
21710   cu = per_cu->cu;
21711   if (cu == NULL)
21712     {
21713       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21714          Instead just throw an error, not much else we can do.  */
21715       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21716              to_underlying (sect_off), objfile_name (per_cu->objfile));
21717     }
21718
21719   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21720   if (!die)
21721     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21722            to_underlying (sect_off), objfile_name (per_cu->objfile));
21723
21724   attr = dwarf2_attr (die, DW_AT_location, cu);
21725   if (!attr)
21726     {
21727       /* DWARF: "If there is no such attribute, then there is no effect.".
21728          DATA is ignored if SIZE is 0.  */
21729
21730       retval.data = NULL;
21731       retval.size = 0;
21732     }
21733   else if (attr_form_is_section_offset (attr))
21734     {
21735       struct dwarf2_loclist_baton loclist_baton;
21736       CORE_ADDR pc = (*get_frame_pc) (baton);
21737       size_t size;
21738
21739       fill_in_loclist_baton (cu, &loclist_baton, attr);
21740
21741       retval.data = dwarf2_find_location_expression (&loclist_baton,
21742                                                      &size, pc);
21743       retval.size = size;
21744     }
21745   else
21746     {
21747       if (!attr_form_is_block (attr))
21748         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21749                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21750                to_underlying (sect_off), objfile_name (per_cu->objfile));
21751
21752       retval.data = DW_BLOCK (attr)->data;
21753       retval.size = DW_BLOCK (attr)->size;
21754     }
21755   retval.per_cu = cu->per_cu;
21756
21757   age_cached_comp_units ();
21758
21759   return retval;
21760 }
21761
21762 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21763    offset.  */
21764
21765 struct dwarf2_locexpr_baton
21766 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21767                              struct dwarf2_per_cu_data *per_cu,
21768                              CORE_ADDR (*get_frame_pc) (void *baton),
21769                              void *baton)
21770 {
21771   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21772
21773   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21774 }
21775
21776 /* Write a constant of a given type as target-ordered bytes into
21777    OBSTACK.  */
21778
21779 static const gdb_byte *
21780 write_constant_as_bytes (struct obstack *obstack,
21781                          enum bfd_endian byte_order,
21782                          struct type *type,
21783                          ULONGEST value,
21784                          LONGEST *len)
21785 {
21786   gdb_byte *result;
21787
21788   *len = TYPE_LENGTH (type);
21789   result = (gdb_byte *) obstack_alloc (obstack, *len);
21790   store_unsigned_integer (result, *len, byte_order, value);
21791
21792   return result;
21793 }
21794
21795 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21796    pointer to the constant bytes and set LEN to the length of the
21797    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21798    does not have a DW_AT_const_value, return NULL.  */
21799
21800 const gdb_byte *
21801 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21802                              struct dwarf2_per_cu_data *per_cu,
21803                              struct obstack *obstack,
21804                              LONGEST *len)
21805 {
21806   struct dwarf2_cu *cu;
21807   struct die_info *die;
21808   struct attribute *attr;
21809   const gdb_byte *result = NULL;
21810   struct type *type;
21811   LONGEST value;
21812   enum bfd_endian byte_order;
21813
21814   dw2_setup (per_cu->objfile);
21815
21816   if (per_cu->cu == NULL)
21817     load_cu (per_cu);
21818   cu = per_cu->cu;
21819   if (cu == NULL)
21820     {
21821       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21822          Instead just throw an error, not much else we can do.  */
21823       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21824              to_underlying (sect_off), objfile_name (per_cu->objfile));
21825     }
21826
21827   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21828   if (!die)
21829     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21830            to_underlying (sect_off), objfile_name (per_cu->objfile));
21831
21832
21833   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21834   if (attr == NULL)
21835     return NULL;
21836
21837   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21838                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21839
21840   switch (attr->form)
21841     {
21842     case DW_FORM_addr:
21843     case DW_FORM_GNU_addr_index:
21844       {
21845         gdb_byte *tem;
21846
21847         *len = cu->header.addr_size;
21848         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21849         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21850         result = tem;
21851       }
21852       break;
21853     case DW_FORM_string:
21854     case DW_FORM_strp:
21855     case DW_FORM_GNU_str_index:
21856     case DW_FORM_GNU_strp_alt:
21857       /* DW_STRING is already allocated on the objfile obstack, point
21858          directly to it.  */
21859       result = (const gdb_byte *) DW_STRING (attr);
21860       *len = strlen (DW_STRING (attr));
21861       break;
21862     case DW_FORM_block1:
21863     case DW_FORM_block2:
21864     case DW_FORM_block4:
21865     case DW_FORM_block:
21866     case DW_FORM_exprloc:
21867     case DW_FORM_data16:
21868       result = DW_BLOCK (attr)->data;
21869       *len = DW_BLOCK (attr)->size;
21870       break;
21871
21872       /* The DW_AT_const_value attributes are supposed to carry the
21873          symbol's value "represented as it would be on the target
21874          architecture."  By the time we get here, it's already been
21875          converted to host endianness, so we just need to sign- or
21876          zero-extend it as appropriate.  */
21877     case DW_FORM_data1:
21878       type = die_type (die, cu);
21879       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21880       if (result == NULL)
21881         result = write_constant_as_bytes (obstack, byte_order,
21882                                           type, value, len);
21883       break;
21884     case DW_FORM_data2:
21885       type = die_type (die, cu);
21886       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21887       if (result == NULL)
21888         result = write_constant_as_bytes (obstack, byte_order,
21889                                           type, value, len);
21890       break;
21891     case DW_FORM_data4:
21892       type = die_type (die, cu);
21893       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21894       if (result == NULL)
21895         result = write_constant_as_bytes (obstack, byte_order,
21896                                           type, value, len);
21897       break;
21898     case DW_FORM_data8:
21899       type = die_type (die, cu);
21900       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21901       if (result == NULL)
21902         result = write_constant_as_bytes (obstack, byte_order,
21903                                           type, value, len);
21904       break;
21905
21906     case DW_FORM_sdata:
21907     case DW_FORM_implicit_const:
21908       type = die_type (die, cu);
21909       result = write_constant_as_bytes (obstack, byte_order,
21910                                         type, DW_SND (attr), len);
21911       break;
21912
21913     case DW_FORM_udata:
21914       type = die_type (die, cu);
21915       result = write_constant_as_bytes (obstack, byte_order,
21916                                         type, DW_UNSND (attr), len);
21917       break;
21918
21919     default:
21920       complaint (&symfile_complaints,
21921                  _("unsupported const value attribute form: '%s'"),
21922                  dwarf_form_name (attr->form));
21923       break;
21924     }
21925
21926   return result;
21927 }
21928
21929 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21930    valid type for this die is found.  */
21931
21932 struct type *
21933 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21934                                 struct dwarf2_per_cu_data *per_cu)
21935 {
21936   struct dwarf2_cu *cu;
21937   struct die_info *die;
21938
21939   dw2_setup (per_cu->objfile);
21940
21941   if (per_cu->cu == NULL)
21942     load_cu (per_cu);
21943   cu = per_cu->cu;
21944   if (!cu)
21945     return NULL;
21946
21947   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21948   if (!die)
21949     return NULL;
21950
21951   return die_type (die, cu);
21952 }
21953
21954 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21955    PER_CU.  */
21956
21957 struct type *
21958 dwarf2_get_die_type (cu_offset die_offset,
21959                      struct dwarf2_per_cu_data *per_cu)
21960 {
21961   dw2_setup (per_cu->objfile);
21962
21963   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21964   return get_die_type_at_offset (die_offset_sect, per_cu);
21965 }
21966
21967 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21968    On entry *REF_CU is the CU of SRC_DIE.
21969    On exit *REF_CU is the CU of the result.
21970    Returns NULL if the referenced DIE isn't found.  */
21971
21972 static struct die_info *
21973 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21974                   struct dwarf2_cu **ref_cu)
21975 {
21976   struct die_info temp_die;
21977   struct dwarf2_cu *sig_cu;
21978   struct die_info *die;
21979
21980   /* While it might be nice to assert sig_type->type == NULL here,
21981      we can get here for DW_AT_imported_declaration where we need
21982      the DIE not the type.  */
21983
21984   /* If necessary, add it to the queue and load its DIEs.  */
21985
21986   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21987     read_signatured_type (sig_type);
21988
21989   sig_cu = sig_type->per_cu.cu;
21990   gdb_assert (sig_cu != NULL);
21991   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21992   temp_die.sect_off = sig_type->type_offset_in_section;
21993   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21994                                                  to_underlying (temp_die.sect_off));
21995   if (die)
21996     {
21997       /* For .gdb_index version 7 keep track of included TUs.
21998          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21999       if (dwarf2_per_objfile->index_table != NULL
22000           && dwarf2_per_objfile->index_table->version <= 7)
22001         {
22002           VEC_safe_push (dwarf2_per_cu_ptr,
22003                          (*ref_cu)->per_cu->imported_symtabs,
22004                          sig_cu->per_cu);
22005         }
22006
22007       *ref_cu = sig_cu;
22008       return die;
22009     }
22010
22011   return NULL;
22012 }
22013
22014 /* Follow signatured type referenced by ATTR in SRC_DIE.
22015    On entry *REF_CU is the CU of SRC_DIE.
22016    On exit *REF_CU is the CU of the result.
22017    The result is the DIE of the type.
22018    If the referenced type cannot be found an error is thrown.  */
22019
22020 static struct die_info *
22021 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
22022                 struct dwarf2_cu **ref_cu)
22023 {
22024   ULONGEST signature = DW_SIGNATURE (attr);
22025   struct signatured_type *sig_type;
22026   struct die_info *die;
22027
22028   gdb_assert (attr->form == DW_FORM_ref_sig8);
22029
22030   sig_type = lookup_signatured_type (*ref_cu, signature);
22031   /* sig_type will be NULL if the signatured type is missing from
22032      the debug info.  */
22033   if (sig_type == NULL)
22034     {
22035       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
22036                " from DIE at 0x%x [in module %s]"),
22037              hex_string (signature), to_underlying (src_die->sect_off),
22038              objfile_name ((*ref_cu)->objfile));
22039     }
22040
22041   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
22042   if (die == NULL)
22043     {
22044       dump_die_for_error (src_die);
22045       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
22046                " from DIE at 0x%x [in module %s]"),
22047              hex_string (signature), to_underlying (src_die->sect_off),
22048              objfile_name ((*ref_cu)->objfile));
22049     }
22050
22051   return die;
22052 }
22053
22054 /* Get the type specified by SIGNATURE referenced in DIE/CU,
22055    reading in and processing the type unit if necessary.  */
22056
22057 static struct type *
22058 get_signatured_type (struct die_info *die, ULONGEST signature,
22059                      struct dwarf2_cu *cu)
22060 {
22061   struct signatured_type *sig_type;
22062   struct dwarf2_cu *type_cu;
22063   struct die_info *type_die;
22064   struct type *type;
22065
22066   sig_type = lookup_signatured_type (cu, signature);
22067   /* sig_type will be NULL if the signatured type is missing from
22068      the debug info.  */
22069   if (sig_type == NULL)
22070     {
22071       complaint (&symfile_complaints,
22072                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
22073                    " from DIE at 0x%x [in module %s]"),
22074                  hex_string (signature), to_underlying (die->sect_off),
22075                  objfile_name (dwarf2_per_objfile->objfile));
22076       return build_error_marker_type (cu, die);
22077     }
22078
22079   /* If we already know the type we're done.  */
22080   if (sig_type->type != NULL)
22081     return sig_type->type;
22082
22083   type_cu = cu;
22084   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
22085   if (type_die != NULL)
22086     {
22087       /* N.B. We need to call get_die_type to ensure only one type for this DIE
22088          is created.  This is important, for example, because for c++ classes
22089          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
22090       type = read_type_die (type_die, type_cu);
22091       if (type == NULL)
22092         {
22093           complaint (&symfile_complaints,
22094                      _("Dwarf Error: Cannot build signatured type %s"
22095                        " referenced from DIE at 0x%x [in module %s]"),
22096                      hex_string (signature), to_underlying (die->sect_off),
22097                      objfile_name (dwarf2_per_objfile->objfile));
22098           type = build_error_marker_type (cu, die);
22099         }
22100     }
22101   else
22102     {
22103       complaint (&symfile_complaints,
22104                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
22105                    " from DIE at 0x%x [in module %s]"),
22106                  hex_string (signature), to_underlying (die->sect_off),
22107                  objfile_name (dwarf2_per_objfile->objfile));
22108       type = build_error_marker_type (cu, die);
22109     }
22110   sig_type->type = type;
22111
22112   return type;
22113 }
22114
22115 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
22116    reading in and processing the type unit if necessary.  */
22117
22118 static struct type *
22119 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
22120                           struct dwarf2_cu *cu) /* ARI: editCase function */
22121 {
22122   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
22123   if (attr_form_is_ref (attr))
22124     {
22125       struct dwarf2_cu *type_cu = cu;
22126       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
22127
22128       return read_type_die (type_die, type_cu);
22129     }
22130   else if (attr->form == DW_FORM_ref_sig8)
22131     {
22132       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
22133     }
22134   else
22135     {
22136       complaint (&symfile_complaints,
22137                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
22138                    " at 0x%x [in module %s]"),
22139                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
22140                  objfile_name (dwarf2_per_objfile->objfile));
22141       return build_error_marker_type (cu, die);
22142     }
22143 }
22144
22145 /* Load the DIEs associated with type unit PER_CU into memory.  */
22146
22147 static void
22148 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
22149 {
22150   struct signatured_type *sig_type;
22151
22152   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
22153   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
22154
22155   /* We have the per_cu, but we need the signatured_type.
22156      Fortunately this is an easy translation.  */
22157   gdb_assert (per_cu->is_debug_types);
22158   sig_type = (struct signatured_type *) per_cu;
22159
22160   gdb_assert (per_cu->cu == NULL);
22161
22162   read_signatured_type (sig_type);
22163
22164   gdb_assert (per_cu->cu != NULL);
22165 }
22166
22167 /* die_reader_func for read_signatured_type.
22168    This is identical to load_full_comp_unit_reader,
22169    but is kept separate for now.  */
22170
22171 static void
22172 read_signatured_type_reader (const struct die_reader_specs *reader,
22173                              const gdb_byte *info_ptr,
22174                              struct die_info *comp_unit_die,
22175                              int has_children,
22176                              void *data)
22177 {
22178   struct dwarf2_cu *cu = reader->cu;
22179
22180   gdb_assert (cu->die_hash == NULL);
22181   cu->die_hash =
22182     htab_create_alloc_ex (cu->header.length / 12,
22183                           die_hash,
22184                           die_eq,
22185                           NULL,
22186                           &cu->comp_unit_obstack,
22187                           hashtab_obstack_allocate,
22188                           dummy_obstack_deallocate);
22189
22190   if (has_children)
22191     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
22192                                                   &info_ptr, comp_unit_die);
22193   cu->dies = comp_unit_die;
22194   /* comp_unit_die is not stored in die_hash, no need.  */
22195
22196   /* We try not to read any attributes in this function, because not
22197      all CUs needed for references have been loaded yet, and symbol
22198      table processing isn't initialized.  But we have to set the CU language,
22199      or we won't be able to build types correctly.
22200      Similarly, if we do not read the producer, we can not apply
22201      producer-specific interpretation.  */
22202   prepare_one_comp_unit (cu, cu->dies, language_minimal);
22203 }
22204
22205 /* Read in a signatured type and build its CU and DIEs.
22206    If the type is a stub for the real type in a DWO file,
22207    read in the real type from the DWO file as well.  */
22208
22209 static void
22210 read_signatured_type (struct signatured_type *sig_type)
22211 {
22212   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
22213
22214   gdb_assert (per_cu->is_debug_types);
22215   gdb_assert (per_cu->cu == NULL);
22216
22217   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
22218                            read_signatured_type_reader, NULL);
22219   sig_type->per_cu.tu_read = 1;
22220 }
22221
22222 /* Decode simple location descriptions.
22223    Given a pointer to a dwarf block that defines a location, compute
22224    the location and return the value.
22225
22226    NOTE drow/2003-11-18: This function is called in two situations
22227    now: for the address of static or global variables (partial symbols
22228    only) and for offsets into structures which are expected to be
22229    (more or less) constant.  The partial symbol case should go away,
22230    and only the constant case should remain.  That will let this
22231    function complain more accurately.  A few special modes are allowed
22232    without complaint for global variables (for instance, global
22233    register values and thread-local values).
22234
22235    A location description containing no operations indicates that the
22236    object is optimized out.  The return value is 0 for that case.
22237    FIXME drow/2003-11-16: No callers check for this case any more; soon all
22238    callers will only want a very basic result and this can become a
22239    complaint.
22240
22241    Note that stack[0] is unused except as a default error return.  */
22242
22243 static CORE_ADDR
22244 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
22245 {
22246   struct objfile *objfile = cu->objfile;
22247   size_t i;
22248   size_t size = blk->size;
22249   const gdb_byte *data = blk->data;
22250   CORE_ADDR stack[64];
22251   int stacki;
22252   unsigned int bytes_read, unsnd;
22253   gdb_byte op;
22254
22255   i = 0;
22256   stacki = 0;
22257   stack[stacki] = 0;
22258   stack[++stacki] = 0;
22259
22260   while (i < size)
22261     {
22262       op = data[i++];
22263       switch (op)
22264         {
22265         case DW_OP_lit0:
22266         case DW_OP_lit1:
22267         case DW_OP_lit2:
22268         case DW_OP_lit3:
22269         case DW_OP_lit4:
22270         case DW_OP_lit5:
22271         case DW_OP_lit6:
22272         case DW_OP_lit7:
22273         case DW_OP_lit8:
22274         case DW_OP_lit9:
22275         case DW_OP_lit10:
22276         case DW_OP_lit11:
22277         case DW_OP_lit12:
22278         case DW_OP_lit13:
22279         case DW_OP_lit14:
22280         case DW_OP_lit15:
22281         case DW_OP_lit16:
22282         case DW_OP_lit17:
22283         case DW_OP_lit18:
22284         case DW_OP_lit19:
22285         case DW_OP_lit20:
22286         case DW_OP_lit21:
22287         case DW_OP_lit22:
22288         case DW_OP_lit23:
22289         case DW_OP_lit24:
22290         case DW_OP_lit25:
22291         case DW_OP_lit26:
22292         case DW_OP_lit27:
22293         case DW_OP_lit28:
22294         case DW_OP_lit29:
22295         case DW_OP_lit30:
22296         case DW_OP_lit31:
22297           stack[++stacki] = op - DW_OP_lit0;
22298           break;
22299
22300         case DW_OP_reg0:
22301         case DW_OP_reg1:
22302         case DW_OP_reg2:
22303         case DW_OP_reg3:
22304         case DW_OP_reg4:
22305         case DW_OP_reg5:
22306         case DW_OP_reg6:
22307         case DW_OP_reg7:
22308         case DW_OP_reg8:
22309         case DW_OP_reg9:
22310         case DW_OP_reg10:
22311         case DW_OP_reg11:
22312         case DW_OP_reg12:
22313         case DW_OP_reg13:
22314         case DW_OP_reg14:
22315         case DW_OP_reg15:
22316         case DW_OP_reg16:
22317         case DW_OP_reg17:
22318         case DW_OP_reg18:
22319         case DW_OP_reg19:
22320         case DW_OP_reg20:
22321         case DW_OP_reg21:
22322         case DW_OP_reg22:
22323         case DW_OP_reg23:
22324         case DW_OP_reg24:
22325         case DW_OP_reg25:
22326         case DW_OP_reg26:
22327         case DW_OP_reg27:
22328         case DW_OP_reg28:
22329         case DW_OP_reg29:
22330         case DW_OP_reg30:
22331         case DW_OP_reg31:
22332           stack[++stacki] = op - DW_OP_reg0;
22333           if (i < size)
22334             dwarf2_complex_location_expr_complaint ();
22335           break;
22336
22337         case DW_OP_regx:
22338           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
22339           i += bytes_read;
22340           stack[++stacki] = unsnd;
22341           if (i < size)
22342             dwarf2_complex_location_expr_complaint ();
22343           break;
22344
22345         case DW_OP_addr:
22346           stack[++stacki] = read_address (objfile->obfd, &data[i],
22347                                           cu, &bytes_read);
22348           i += bytes_read;
22349           break;
22350
22351         case DW_OP_const1u:
22352           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
22353           i += 1;
22354           break;
22355
22356         case DW_OP_const1s:
22357           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
22358           i += 1;
22359           break;
22360
22361         case DW_OP_const2u:
22362           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
22363           i += 2;
22364           break;
22365
22366         case DW_OP_const2s:
22367           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
22368           i += 2;
22369           break;
22370
22371         case DW_OP_const4u:
22372           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
22373           i += 4;
22374           break;
22375
22376         case DW_OP_const4s:
22377           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
22378           i += 4;
22379           break;
22380
22381         case DW_OP_const8u:
22382           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
22383           i += 8;
22384           break;
22385
22386         case DW_OP_constu:
22387           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
22388                                                   &bytes_read);
22389           i += bytes_read;
22390           break;
22391
22392         case DW_OP_consts:
22393           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
22394           i += bytes_read;
22395           break;
22396
22397         case DW_OP_dup:
22398           stack[stacki + 1] = stack[stacki];
22399           stacki++;
22400           break;
22401
22402         case DW_OP_plus:
22403           stack[stacki - 1] += stack[stacki];
22404           stacki--;
22405           break;
22406
22407         case DW_OP_plus_uconst:
22408           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
22409                                                  &bytes_read);
22410           i += bytes_read;
22411           break;
22412
22413         case DW_OP_minus:
22414           stack[stacki - 1] -= stack[stacki];
22415           stacki--;
22416           break;
22417
22418         case DW_OP_deref:
22419           /* If we're not the last op, then we definitely can't encode
22420              this using GDB's address_class enum.  This is valid for partial
22421              global symbols, although the variable's address will be bogus
22422              in the psymtab.  */
22423           if (i < size)
22424             dwarf2_complex_location_expr_complaint ();
22425           break;
22426
22427         case DW_OP_GNU_push_tls_address:
22428         case DW_OP_form_tls_address:
22429           /* The top of the stack has the offset from the beginning
22430              of the thread control block at which the variable is located.  */
22431           /* Nothing should follow this operator, so the top of stack would
22432              be returned.  */
22433           /* This is valid for partial global symbols, but the variable's
22434              address will be bogus in the psymtab.  Make it always at least
22435              non-zero to not look as a variable garbage collected by linker
22436              which have DW_OP_addr 0.  */
22437           if (i < size)
22438             dwarf2_complex_location_expr_complaint ();
22439           stack[stacki]++;
22440           break;
22441
22442         case DW_OP_GNU_uninit:
22443           break;
22444
22445         case DW_OP_GNU_addr_index:
22446         case DW_OP_GNU_const_index:
22447           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
22448                                                          &bytes_read);
22449           i += bytes_read;
22450           break;
22451
22452         default:
22453           {
22454             const char *name = get_DW_OP_name (op);
22455
22456             if (name)
22457               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
22458                          name);
22459             else
22460               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
22461                          op);
22462           }
22463
22464           return (stack[stacki]);
22465         }
22466
22467       /* Enforce maximum stack depth of SIZE-1 to avoid writing
22468          outside of the allocated space.  Also enforce minimum>0.  */
22469       if (stacki >= ARRAY_SIZE (stack) - 1)
22470         {
22471           complaint (&symfile_complaints,
22472                      _("location description stack overflow"));
22473           return 0;
22474         }
22475
22476       if (stacki <= 0)
22477         {
22478           complaint (&symfile_complaints,
22479                      _("location description stack underflow"));
22480           return 0;
22481         }
22482     }
22483   return (stack[stacki]);
22484 }
22485
22486 /* memory allocation interface */
22487
22488 static struct dwarf_block *
22489 dwarf_alloc_block (struct dwarf2_cu *cu)
22490 {
22491   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
22492 }
22493
22494 static struct die_info *
22495 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
22496 {
22497   struct die_info *die;
22498   size_t size = sizeof (struct die_info);
22499
22500   if (num_attrs > 1)
22501     size += (num_attrs - 1) * sizeof (struct attribute);
22502
22503   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
22504   memset (die, 0, sizeof (struct die_info));
22505   return (die);
22506 }
22507
22508 \f
22509 /* Macro support.  */
22510
22511 /* Return file name relative to the compilation directory of file number I in
22512    *LH's file name table.  The result is allocated using xmalloc; the caller is
22513    responsible for freeing it.  */
22514
22515 static char *
22516 file_file_name (int file, struct line_header *lh)
22517 {
22518   /* Is the file number a valid index into the line header's file name
22519      table?  Remember that file numbers start with one, not zero.  */
22520   if (1 <= file && file <= lh->file_names.size ())
22521     {
22522       const file_entry &fe = lh->file_names[file - 1];
22523
22524       if (!IS_ABSOLUTE_PATH (fe.name))
22525         {
22526           const char *dir = fe.include_dir (lh);
22527           if (dir != NULL)
22528             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
22529         }
22530       return xstrdup (fe.name);
22531     }
22532   else
22533     {
22534       /* The compiler produced a bogus file number.  We can at least
22535          record the macro definitions made in the file, even if we
22536          won't be able to find the file by name.  */
22537       char fake_name[80];
22538
22539       xsnprintf (fake_name, sizeof (fake_name),
22540                  "<bad macro file number %d>", file);
22541
22542       complaint (&symfile_complaints,
22543                  _("bad file number in macro information (%d)"),
22544                  file);
22545
22546       return xstrdup (fake_name);
22547     }
22548 }
22549
22550 /* Return the full name of file number I in *LH's file name table.
22551    Use COMP_DIR as the name of the current directory of the
22552    compilation.  The result is allocated using xmalloc; the caller is
22553    responsible for freeing it.  */
22554 static char *
22555 file_full_name (int file, struct line_header *lh, const char *comp_dir)
22556 {
22557   /* Is the file number a valid index into the line header's file name
22558      table?  Remember that file numbers start with one, not zero.  */
22559   if (1 <= file && file <= lh->file_names.size ())
22560     {
22561       char *relative = file_file_name (file, lh);
22562
22563       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
22564         return relative;
22565       return reconcat (relative, comp_dir, SLASH_STRING,
22566                        relative, (char *) NULL);
22567     }
22568   else
22569     return file_file_name (file, lh);
22570 }
22571
22572
22573 static struct macro_source_file *
22574 macro_start_file (int file, int line,
22575                   struct macro_source_file *current_file,
22576                   struct line_header *lh)
22577 {
22578   /* File name relative to the compilation directory of this source file.  */
22579   char *file_name = file_file_name (file, lh);
22580
22581   if (! current_file)
22582     {
22583       /* Note: We don't create a macro table for this compilation unit
22584          at all until we actually get a filename.  */
22585       struct macro_table *macro_table = get_macro_table ();
22586
22587       /* If we have no current file, then this must be the start_file
22588          directive for the compilation unit's main source file.  */
22589       current_file = macro_set_main (macro_table, file_name);
22590       macro_define_special (macro_table);
22591     }
22592   else
22593     current_file = macro_include (current_file, line, file_name);
22594
22595   xfree (file_name);
22596
22597   return current_file;
22598 }
22599
22600 static const char *
22601 consume_improper_spaces (const char *p, const char *body)
22602 {
22603   if (*p == ' ')
22604     {
22605       complaint (&symfile_complaints,
22606                  _("macro definition contains spaces "
22607                    "in formal argument list:\n`%s'"),
22608                  body);
22609
22610       while (*p == ' ')
22611         p++;
22612     }
22613
22614   return p;
22615 }
22616
22617
22618 static void
22619 parse_macro_definition (struct macro_source_file *file, int line,
22620                         const char *body)
22621 {
22622   const char *p;
22623
22624   /* The body string takes one of two forms.  For object-like macro
22625      definitions, it should be:
22626
22627         <macro name> " " <definition>
22628
22629      For function-like macro definitions, it should be:
22630
22631         <macro name> "() " <definition>
22632      or
22633         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
22634
22635      Spaces may appear only where explicitly indicated, and in the
22636      <definition>.
22637
22638      The Dwarf 2 spec says that an object-like macro's name is always
22639      followed by a space, but versions of GCC around March 2002 omit
22640      the space when the macro's definition is the empty string.
22641
22642      The Dwarf 2 spec says that there should be no spaces between the
22643      formal arguments in a function-like macro's formal argument list,
22644      but versions of GCC around March 2002 include spaces after the
22645      commas.  */
22646
22647
22648   /* Find the extent of the macro name.  The macro name is terminated
22649      by either a space or null character (for an object-like macro) or
22650      an opening paren (for a function-like macro).  */
22651   for (p = body; *p; p++)
22652     if (*p == ' ' || *p == '(')
22653       break;
22654
22655   if (*p == ' ' || *p == '\0')
22656     {
22657       /* It's an object-like macro.  */
22658       int name_len = p - body;
22659       char *name = savestring (body, name_len);
22660       const char *replacement;
22661
22662       if (*p == ' ')
22663         replacement = body + name_len + 1;
22664       else
22665         {
22666           dwarf2_macro_malformed_definition_complaint (body);
22667           replacement = body + name_len;
22668         }
22669
22670       macro_define_object (file, line, name, replacement);
22671
22672       xfree (name);
22673     }
22674   else if (*p == '(')
22675     {
22676       /* It's a function-like macro.  */
22677       char *name = savestring (body, p - body);
22678       int argc = 0;
22679       int argv_size = 1;
22680       char **argv = XNEWVEC (char *, argv_size);
22681
22682       p++;
22683
22684       p = consume_improper_spaces (p, body);
22685
22686       /* Parse the formal argument list.  */
22687       while (*p && *p != ')')
22688         {
22689           /* Find the extent of the current argument name.  */
22690           const char *arg_start = p;
22691
22692           while (*p && *p != ',' && *p != ')' && *p != ' ')
22693             p++;
22694
22695           if (! *p || p == arg_start)
22696             dwarf2_macro_malformed_definition_complaint (body);
22697           else
22698             {
22699               /* Make sure argv has room for the new argument.  */
22700               if (argc >= argv_size)
22701                 {
22702                   argv_size *= 2;
22703                   argv = XRESIZEVEC (char *, argv, argv_size);
22704                 }
22705
22706               argv[argc++] = savestring (arg_start, p - arg_start);
22707             }
22708
22709           p = consume_improper_spaces (p, body);
22710
22711           /* Consume the comma, if present.  */
22712           if (*p == ',')
22713             {
22714               p++;
22715
22716               p = consume_improper_spaces (p, body);
22717             }
22718         }
22719
22720       if (*p == ')')
22721         {
22722           p++;
22723
22724           if (*p == ' ')
22725             /* Perfectly formed definition, no complaints.  */
22726             macro_define_function (file, line, name,
22727                                    argc, (const char **) argv,
22728                                    p + 1);
22729           else if (*p == '\0')
22730             {
22731               /* Complain, but do define it.  */
22732               dwarf2_macro_malformed_definition_complaint (body);
22733               macro_define_function (file, line, name,
22734                                      argc, (const char **) argv,
22735                                      p);
22736             }
22737           else
22738             /* Just complain.  */
22739             dwarf2_macro_malformed_definition_complaint (body);
22740         }
22741       else
22742         /* Just complain.  */
22743         dwarf2_macro_malformed_definition_complaint (body);
22744
22745       xfree (name);
22746       {
22747         int i;
22748
22749         for (i = 0; i < argc; i++)
22750           xfree (argv[i]);
22751       }
22752       xfree (argv);
22753     }
22754   else
22755     dwarf2_macro_malformed_definition_complaint (body);
22756 }
22757
22758 /* Skip some bytes from BYTES according to the form given in FORM.
22759    Returns the new pointer.  */
22760
22761 static const gdb_byte *
22762 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22763                  enum dwarf_form form,
22764                  unsigned int offset_size,
22765                  struct dwarf2_section_info *section)
22766 {
22767   unsigned int bytes_read;
22768
22769   switch (form)
22770     {
22771     case DW_FORM_data1:
22772     case DW_FORM_flag:
22773       ++bytes;
22774       break;
22775
22776     case DW_FORM_data2:
22777       bytes += 2;
22778       break;
22779
22780     case DW_FORM_data4:
22781       bytes += 4;
22782       break;
22783
22784     case DW_FORM_data8:
22785       bytes += 8;
22786       break;
22787
22788     case DW_FORM_data16:
22789       bytes += 16;
22790       break;
22791
22792     case DW_FORM_string:
22793       read_direct_string (abfd, bytes, &bytes_read);
22794       bytes += bytes_read;
22795       break;
22796
22797     case DW_FORM_sec_offset:
22798     case DW_FORM_strp:
22799     case DW_FORM_GNU_strp_alt:
22800       bytes += offset_size;
22801       break;
22802
22803     case DW_FORM_block:
22804       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22805       bytes += bytes_read;
22806       break;
22807
22808     case DW_FORM_block1:
22809       bytes += 1 + read_1_byte (abfd, bytes);
22810       break;
22811     case DW_FORM_block2:
22812       bytes += 2 + read_2_bytes (abfd, bytes);
22813       break;
22814     case DW_FORM_block4:
22815       bytes += 4 + read_4_bytes (abfd, bytes);
22816       break;
22817
22818     case DW_FORM_sdata:
22819     case DW_FORM_udata:
22820     case DW_FORM_GNU_addr_index:
22821     case DW_FORM_GNU_str_index:
22822       bytes = gdb_skip_leb128 (bytes, buffer_end);
22823       if (bytes == NULL)
22824         {
22825           dwarf2_section_buffer_overflow_complaint (section);
22826           return NULL;
22827         }
22828       break;
22829
22830     case DW_FORM_implicit_const:
22831       break;
22832
22833     default:
22834       {
22835         complaint (&symfile_complaints,
22836                    _("invalid form 0x%x in `%s'"),
22837                    form, get_section_name (section));
22838         return NULL;
22839       }
22840     }
22841
22842   return bytes;
22843 }
22844
22845 /* A helper for dwarf_decode_macros that handles skipping an unknown
22846    opcode.  Returns an updated pointer to the macro data buffer; or,
22847    on error, issues a complaint and returns NULL.  */
22848
22849 static const gdb_byte *
22850 skip_unknown_opcode (unsigned int opcode,
22851                      const gdb_byte **opcode_definitions,
22852                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22853                      bfd *abfd,
22854                      unsigned int offset_size,
22855                      struct dwarf2_section_info *section)
22856 {
22857   unsigned int bytes_read, i;
22858   unsigned long arg;
22859   const gdb_byte *defn;
22860
22861   if (opcode_definitions[opcode] == NULL)
22862     {
22863       complaint (&symfile_complaints,
22864                  _("unrecognized DW_MACFINO opcode 0x%x"),
22865                  opcode);
22866       return NULL;
22867     }
22868
22869   defn = opcode_definitions[opcode];
22870   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22871   defn += bytes_read;
22872
22873   for (i = 0; i < arg; ++i)
22874     {
22875       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22876                                  (enum dwarf_form) defn[i], offset_size,
22877                                  section);
22878       if (mac_ptr == NULL)
22879         {
22880           /* skip_form_bytes already issued the complaint.  */
22881           return NULL;
22882         }
22883     }
22884
22885   return mac_ptr;
22886 }
22887
22888 /* A helper function which parses the header of a macro section.
22889    If the macro section is the extended (for now called "GNU") type,
22890    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22891    the header, or issues a complaint and returns NULL on error.  */
22892
22893 static const gdb_byte *
22894 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22895                           bfd *abfd,
22896                           const gdb_byte *mac_ptr,
22897                           unsigned int *offset_size,
22898                           int section_is_gnu)
22899 {
22900   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22901
22902   if (section_is_gnu)
22903     {
22904       unsigned int version, flags;
22905
22906       version = read_2_bytes (abfd, mac_ptr);
22907       if (version != 4 && version != 5)
22908         {
22909           complaint (&symfile_complaints,
22910                      _("unrecognized version `%d' in .debug_macro section"),
22911                      version);
22912           return NULL;
22913         }
22914       mac_ptr += 2;
22915
22916       flags = read_1_byte (abfd, mac_ptr);
22917       ++mac_ptr;
22918       *offset_size = (flags & 1) ? 8 : 4;
22919
22920       if ((flags & 2) != 0)
22921         /* We don't need the line table offset.  */
22922         mac_ptr += *offset_size;
22923
22924       /* Vendor opcode descriptions.  */
22925       if ((flags & 4) != 0)
22926         {
22927           unsigned int i, count;
22928
22929           count = read_1_byte (abfd, mac_ptr);
22930           ++mac_ptr;
22931           for (i = 0; i < count; ++i)
22932             {
22933               unsigned int opcode, bytes_read;
22934               unsigned long arg;
22935
22936               opcode = read_1_byte (abfd, mac_ptr);
22937               ++mac_ptr;
22938               opcode_definitions[opcode] = mac_ptr;
22939               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22940               mac_ptr += bytes_read;
22941               mac_ptr += arg;
22942             }
22943         }
22944     }
22945
22946   return mac_ptr;
22947 }
22948
22949 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22950    including DW_MACRO_import.  */
22951
22952 static void
22953 dwarf_decode_macro_bytes (bfd *abfd,
22954                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22955                           struct macro_source_file *current_file,
22956                           struct line_header *lh,
22957                           struct dwarf2_section_info *section,
22958                           int section_is_gnu, int section_is_dwz,
22959                           unsigned int offset_size,
22960                           htab_t include_hash)
22961 {
22962   struct objfile *objfile = dwarf2_per_objfile->objfile;
22963   enum dwarf_macro_record_type macinfo_type;
22964   int at_commandline;
22965   const gdb_byte *opcode_definitions[256];
22966
22967   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22968                                       &offset_size, section_is_gnu);
22969   if (mac_ptr == NULL)
22970     {
22971       /* We already issued a complaint.  */
22972       return;
22973     }
22974
22975   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22976      GDB is still reading the definitions from command line.  First
22977      DW_MACINFO_start_file will need to be ignored as it was already executed
22978      to create CURRENT_FILE for the main source holding also the command line
22979      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22980      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22981
22982   at_commandline = 1;
22983
22984   do
22985     {
22986       /* Do we at least have room for a macinfo type byte?  */
22987       if (mac_ptr >= mac_end)
22988         {
22989           dwarf2_section_buffer_overflow_complaint (section);
22990           break;
22991         }
22992
22993       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22994       mac_ptr++;
22995
22996       /* Note that we rely on the fact that the corresponding GNU and
22997          DWARF constants are the same.  */
22998       switch (macinfo_type)
22999         {
23000           /* A zero macinfo type indicates the end of the macro
23001              information.  */
23002         case 0:
23003           break;
23004
23005         case DW_MACRO_define:
23006         case DW_MACRO_undef:
23007         case DW_MACRO_define_strp:
23008         case DW_MACRO_undef_strp:
23009         case DW_MACRO_define_sup:
23010         case DW_MACRO_undef_sup:
23011           {
23012             unsigned int bytes_read;
23013             int line;
23014             const char *body;
23015             int is_define;
23016
23017             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23018             mac_ptr += bytes_read;
23019
23020             if (macinfo_type == DW_MACRO_define
23021                 || macinfo_type == DW_MACRO_undef)
23022               {
23023                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
23024                 mac_ptr += bytes_read;
23025               }
23026             else
23027               {
23028                 LONGEST str_offset;
23029
23030                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
23031                 mac_ptr += offset_size;
23032
23033                 if (macinfo_type == DW_MACRO_define_sup
23034                     || macinfo_type == DW_MACRO_undef_sup
23035                     || section_is_dwz)
23036                   {
23037                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
23038
23039                     body = read_indirect_string_from_dwz (dwz, str_offset);
23040                   }
23041                 else
23042                   body = read_indirect_string_at_offset (abfd, str_offset);
23043               }
23044
23045             is_define = (macinfo_type == DW_MACRO_define
23046                          || macinfo_type == DW_MACRO_define_strp
23047                          || macinfo_type == DW_MACRO_define_sup);
23048             if (! current_file)
23049               {
23050                 /* DWARF violation as no main source is present.  */
23051                 complaint (&symfile_complaints,
23052                            _("debug info with no main source gives macro %s "
23053                              "on line %d: %s"),
23054                            is_define ? _("definition") : _("undefinition"),
23055                            line, body);
23056                 break;
23057               }
23058             if ((line == 0 && !at_commandline)
23059                 || (line != 0 && at_commandline))
23060               complaint (&symfile_complaints,
23061                          _("debug info gives %s macro %s with %s line %d: %s"),
23062                          at_commandline ? _("command-line") : _("in-file"),
23063                          is_define ? _("definition") : _("undefinition"),
23064                          line == 0 ? _("zero") : _("non-zero"), line, body);
23065
23066             if (is_define)
23067               parse_macro_definition (current_file, line, body);
23068             else
23069               {
23070                 gdb_assert (macinfo_type == DW_MACRO_undef
23071                             || macinfo_type == DW_MACRO_undef_strp
23072                             || macinfo_type == DW_MACRO_undef_sup);
23073                 macro_undef (current_file, line, body);
23074               }
23075           }
23076           break;
23077
23078         case DW_MACRO_start_file:
23079           {
23080             unsigned int bytes_read;
23081             int line, file;
23082
23083             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23084             mac_ptr += bytes_read;
23085             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23086             mac_ptr += bytes_read;
23087
23088             if ((line == 0 && !at_commandline)
23089                 || (line != 0 && at_commandline))
23090               complaint (&symfile_complaints,
23091                          _("debug info gives source %d included "
23092                            "from %s at %s line %d"),
23093                          file, at_commandline ? _("command-line") : _("file"),
23094                          line == 0 ? _("zero") : _("non-zero"), line);
23095
23096             if (at_commandline)
23097               {
23098                 /* This DW_MACRO_start_file was executed in the
23099                    pass one.  */
23100                 at_commandline = 0;
23101               }
23102             else
23103               current_file = macro_start_file (file, line, current_file, lh);
23104           }
23105           break;
23106
23107         case DW_MACRO_end_file:
23108           if (! current_file)
23109             complaint (&symfile_complaints,
23110                        _("macro debug info has an unmatched "
23111                          "`close_file' directive"));
23112           else
23113             {
23114               current_file = current_file->included_by;
23115               if (! current_file)
23116                 {
23117                   enum dwarf_macro_record_type next_type;
23118
23119                   /* GCC circa March 2002 doesn't produce the zero
23120                      type byte marking the end of the compilation
23121                      unit.  Complain if it's not there, but exit no
23122                      matter what.  */
23123
23124                   /* Do we at least have room for a macinfo type byte?  */
23125                   if (mac_ptr >= mac_end)
23126                     {
23127                       dwarf2_section_buffer_overflow_complaint (section);
23128                       return;
23129                     }
23130
23131                   /* We don't increment mac_ptr here, so this is just
23132                      a look-ahead.  */
23133                   next_type
23134                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
23135                                                                   mac_ptr);
23136                   if (next_type != 0)
23137                     complaint (&symfile_complaints,
23138                                _("no terminating 0-type entry for "
23139                                  "macros in `.debug_macinfo' section"));
23140
23141                   return;
23142                 }
23143             }
23144           break;
23145
23146         case DW_MACRO_import:
23147         case DW_MACRO_import_sup:
23148           {
23149             LONGEST offset;
23150             void **slot;
23151             bfd *include_bfd = abfd;
23152             struct dwarf2_section_info *include_section = section;
23153             const gdb_byte *include_mac_end = mac_end;
23154             int is_dwz = section_is_dwz;
23155             const gdb_byte *new_mac_ptr;
23156
23157             offset = read_offset_1 (abfd, mac_ptr, offset_size);
23158             mac_ptr += offset_size;
23159
23160             if (macinfo_type == DW_MACRO_import_sup)
23161               {
23162                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
23163
23164                 dwarf2_read_section (objfile, &dwz->macro);
23165
23166                 include_section = &dwz->macro;
23167                 include_bfd = get_section_bfd_owner (include_section);
23168                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
23169                 is_dwz = 1;
23170               }
23171
23172             new_mac_ptr = include_section->buffer + offset;
23173             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
23174
23175             if (*slot != NULL)
23176               {
23177                 /* This has actually happened; see
23178                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
23179                 complaint (&symfile_complaints,
23180                            _("recursive DW_MACRO_import in "
23181                              ".debug_macro section"));
23182               }
23183             else
23184               {
23185                 *slot = (void *) new_mac_ptr;
23186
23187                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
23188                                           include_mac_end, current_file, lh,
23189                                           section, section_is_gnu, is_dwz,
23190                                           offset_size, include_hash);
23191
23192                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
23193               }
23194           }
23195           break;
23196
23197         case DW_MACINFO_vendor_ext:
23198           if (!section_is_gnu)
23199             {
23200               unsigned int bytes_read;
23201
23202               /* This reads the constant, but since we don't recognize
23203                  any vendor extensions, we ignore it.  */
23204               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23205               mac_ptr += bytes_read;
23206               read_direct_string (abfd, mac_ptr, &bytes_read);
23207               mac_ptr += bytes_read;
23208
23209               /* We don't recognize any vendor extensions.  */
23210               break;
23211             }
23212           /* FALLTHROUGH */
23213
23214         default:
23215           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23216                                          mac_ptr, mac_end, abfd, offset_size,
23217                                          section);
23218           if (mac_ptr == NULL)
23219             return;
23220           break;
23221         }
23222     } while (macinfo_type != 0);
23223 }
23224
23225 static void
23226 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
23227                      int section_is_gnu)
23228 {
23229   struct objfile *objfile = dwarf2_per_objfile->objfile;
23230   struct line_header *lh = cu->line_header;
23231   bfd *abfd;
23232   const gdb_byte *mac_ptr, *mac_end;
23233   struct macro_source_file *current_file = 0;
23234   enum dwarf_macro_record_type macinfo_type;
23235   unsigned int offset_size = cu->header.offset_size;
23236   const gdb_byte *opcode_definitions[256];
23237   void **slot;
23238   struct dwarf2_section_info *section;
23239   const char *section_name;
23240
23241   if (cu->dwo_unit != NULL)
23242     {
23243       if (section_is_gnu)
23244         {
23245           section = &cu->dwo_unit->dwo_file->sections.macro;
23246           section_name = ".debug_macro.dwo";
23247         }
23248       else
23249         {
23250           section = &cu->dwo_unit->dwo_file->sections.macinfo;
23251           section_name = ".debug_macinfo.dwo";
23252         }
23253     }
23254   else
23255     {
23256       if (section_is_gnu)
23257         {
23258           section = &dwarf2_per_objfile->macro;
23259           section_name = ".debug_macro";
23260         }
23261       else
23262         {
23263           section = &dwarf2_per_objfile->macinfo;
23264           section_name = ".debug_macinfo";
23265         }
23266     }
23267
23268   dwarf2_read_section (objfile, section);
23269   if (section->buffer == NULL)
23270     {
23271       complaint (&symfile_complaints, _("missing %s section"), section_name);
23272       return;
23273     }
23274   abfd = get_section_bfd_owner (section);
23275
23276   /* First pass: Find the name of the base filename.
23277      This filename is needed in order to process all macros whose definition
23278      (or undefinition) comes from the command line.  These macros are defined
23279      before the first DW_MACINFO_start_file entry, and yet still need to be
23280      associated to the base file.
23281
23282      To determine the base file name, we scan the macro definitions until we
23283      reach the first DW_MACINFO_start_file entry.  We then initialize
23284      CURRENT_FILE accordingly so that any macro definition found before the
23285      first DW_MACINFO_start_file can still be associated to the base file.  */
23286
23287   mac_ptr = section->buffer + offset;
23288   mac_end = section->buffer + section->size;
23289
23290   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23291                                       &offset_size, section_is_gnu);
23292   if (mac_ptr == NULL)
23293     {
23294       /* We already issued a complaint.  */
23295       return;
23296     }
23297
23298   do
23299     {
23300       /* Do we at least have room for a macinfo type byte?  */
23301       if (mac_ptr >= mac_end)
23302         {
23303           /* Complaint is printed during the second pass as GDB will probably
23304              stop the first pass earlier upon finding
23305              DW_MACINFO_start_file.  */
23306           break;
23307         }
23308
23309       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23310       mac_ptr++;
23311
23312       /* Note that we rely on the fact that the corresponding GNU and
23313          DWARF constants are the same.  */
23314       switch (macinfo_type)
23315         {
23316           /* A zero macinfo type indicates the end of the macro
23317              information.  */
23318         case 0:
23319           break;
23320
23321         case DW_MACRO_define:
23322         case DW_MACRO_undef:
23323           /* Only skip the data by MAC_PTR.  */
23324           {
23325             unsigned int bytes_read;
23326
23327             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23328             mac_ptr += bytes_read;
23329             read_direct_string (abfd, mac_ptr, &bytes_read);
23330             mac_ptr += bytes_read;
23331           }
23332           break;
23333
23334         case DW_MACRO_start_file:
23335           {
23336             unsigned int bytes_read;
23337             int line, file;
23338
23339             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23340             mac_ptr += bytes_read;
23341             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23342             mac_ptr += bytes_read;
23343
23344             current_file = macro_start_file (file, line, current_file, lh);
23345           }
23346           break;
23347
23348         case DW_MACRO_end_file:
23349           /* No data to skip by MAC_PTR.  */
23350           break;
23351
23352         case DW_MACRO_define_strp:
23353         case DW_MACRO_undef_strp:
23354         case DW_MACRO_define_sup:
23355         case DW_MACRO_undef_sup:
23356           {
23357             unsigned int bytes_read;
23358
23359             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23360             mac_ptr += bytes_read;
23361             mac_ptr += offset_size;
23362           }
23363           break;
23364
23365         case DW_MACRO_import:
23366         case DW_MACRO_import_sup:
23367           /* Note that, according to the spec, a transparent include
23368              chain cannot call DW_MACRO_start_file.  So, we can just
23369              skip this opcode.  */
23370           mac_ptr += offset_size;
23371           break;
23372
23373         case DW_MACINFO_vendor_ext:
23374           /* Only skip the data by MAC_PTR.  */
23375           if (!section_is_gnu)
23376             {
23377               unsigned int bytes_read;
23378
23379               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23380               mac_ptr += bytes_read;
23381               read_direct_string (abfd, mac_ptr, &bytes_read);
23382               mac_ptr += bytes_read;
23383             }
23384           /* FALLTHROUGH */
23385
23386         default:
23387           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23388                                          mac_ptr, mac_end, abfd, offset_size,
23389                                          section);
23390           if (mac_ptr == NULL)
23391             return;
23392           break;
23393         }
23394     } while (macinfo_type != 0 && current_file == NULL);
23395
23396   /* Second pass: Process all entries.
23397
23398      Use the AT_COMMAND_LINE flag to determine whether we are still processing
23399      command-line macro definitions/undefinitions.  This flag is unset when we
23400      reach the first DW_MACINFO_start_file entry.  */
23401
23402   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
23403                                            htab_eq_pointer,
23404                                            NULL, xcalloc, xfree));
23405   mac_ptr = section->buffer + offset;
23406   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
23407   *slot = (void *) mac_ptr;
23408   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
23409                             current_file, lh, section,
23410                             section_is_gnu, 0, offset_size,
23411                             include_hash.get ());
23412 }
23413
23414 /* Check if the attribute's form is a DW_FORM_block*
23415    if so return true else false.  */
23416
23417 static int
23418 attr_form_is_block (const struct attribute *attr)
23419 {
23420   return (attr == NULL ? 0 :
23421       attr->form == DW_FORM_block1
23422       || attr->form == DW_FORM_block2
23423       || attr->form == DW_FORM_block4
23424       || attr->form == DW_FORM_block
23425       || attr->form == DW_FORM_exprloc);
23426 }
23427
23428 /* Return non-zero if ATTR's value is a section offset --- classes
23429    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
23430    You may use DW_UNSND (attr) to retrieve such offsets.
23431
23432    Section 7.5.4, "Attribute Encodings", explains that no attribute
23433    may have a value that belongs to more than one of these classes; it
23434    would be ambiguous if we did, because we use the same forms for all
23435    of them.  */
23436
23437 static int
23438 attr_form_is_section_offset (const struct attribute *attr)
23439 {
23440   return (attr->form == DW_FORM_data4
23441           || attr->form == DW_FORM_data8
23442           || attr->form == DW_FORM_sec_offset);
23443 }
23444
23445 /* Return non-zero if ATTR's value falls in the 'constant' class, or
23446    zero otherwise.  When this function returns true, you can apply
23447    dwarf2_get_attr_constant_value to it.
23448
23449    However, note that for some attributes you must check
23450    attr_form_is_section_offset before using this test.  DW_FORM_data4
23451    and DW_FORM_data8 are members of both the constant class, and of
23452    the classes that contain offsets into other debug sections
23453    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
23454    that, if an attribute's can be either a constant or one of the
23455    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
23456    taken as section offsets, not constants.
23457
23458    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
23459    cannot handle that.  */
23460
23461 static int
23462 attr_form_is_constant (const struct attribute *attr)
23463 {
23464   switch (attr->form)
23465     {
23466     case DW_FORM_sdata:
23467     case DW_FORM_udata:
23468     case DW_FORM_data1:
23469     case DW_FORM_data2:
23470     case DW_FORM_data4:
23471     case DW_FORM_data8:
23472     case DW_FORM_implicit_const:
23473       return 1;
23474     default:
23475       return 0;
23476     }
23477 }
23478
23479
23480 /* DW_ADDR is always stored already as sect_offset; despite for the forms
23481    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
23482
23483 static int
23484 attr_form_is_ref (const struct attribute *attr)
23485 {
23486   switch (attr->form)
23487     {
23488     case DW_FORM_ref_addr:
23489     case DW_FORM_ref1:
23490     case DW_FORM_ref2:
23491     case DW_FORM_ref4:
23492     case DW_FORM_ref8:
23493     case DW_FORM_ref_udata:
23494     case DW_FORM_GNU_ref_alt:
23495       return 1;
23496     default:
23497       return 0;
23498     }
23499 }
23500
23501 /* Return the .debug_loc section to use for CU.
23502    For DWO files use .debug_loc.dwo.  */
23503
23504 static struct dwarf2_section_info *
23505 cu_debug_loc_section (struct dwarf2_cu *cu)
23506 {
23507   if (cu->dwo_unit)
23508     {
23509       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
23510       
23511       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
23512     }
23513   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
23514                                   : &dwarf2_per_objfile->loc);
23515 }
23516
23517 /* A helper function that fills in a dwarf2_loclist_baton.  */
23518
23519 static void
23520 fill_in_loclist_baton (struct dwarf2_cu *cu,
23521                        struct dwarf2_loclist_baton *baton,
23522                        const struct attribute *attr)
23523 {
23524   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23525
23526   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
23527
23528   baton->per_cu = cu->per_cu;
23529   gdb_assert (baton->per_cu);
23530   /* We don't know how long the location list is, but make sure we
23531      don't run off the edge of the section.  */
23532   baton->size = section->size - DW_UNSND (attr);
23533   baton->data = section->buffer + DW_UNSND (attr);
23534   baton->base_address = cu->base_address;
23535   baton->from_dwo = cu->dwo_unit != NULL;
23536 }
23537
23538 static void
23539 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
23540                              struct dwarf2_cu *cu, int is_block)
23541 {
23542   struct objfile *objfile = dwarf2_per_objfile->objfile;
23543   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23544
23545   if (attr_form_is_section_offset (attr)
23546       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
23547          the section.  If so, fall through to the complaint in the
23548          other branch.  */
23549       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
23550     {
23551       struct dwarf2_loclist_baton *baton;
23552
23553       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
23554
23555       fill_in_loclist_baton (cu, baton, attr);
23556
23557       if (cu->base_known == 0)
23558         complaint (&symfile_complaints,
23559                    _("Location list used without "
23560                      "specifying the CU base address."));
23561
23562       SYMBOL_ACLASS_INDEX (sym) = (is_block
23563                                    ? dwarf2_loclist_block_index
23564                                    : dwarf2_loclist_index);
23565       SYMBOL_LOCATION_BATON (sym) = baton;
23566     }
23567   else
23568     {
23569       struct dwarf2_locexpr_baton *baton;
23570
23571       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
23572       baton->per_cu = cu->per_cu;
23573       gdb_assert (baton->per_cu);
23574
23575       if (attr_form_is_block (attr))
23576         {
23577           /* Note that we're just copying the block's data pointer
23578              here, not the actual data.  We're still pointing into the
23579              info_buffer for SYM's objfile; right now we never release
23580              that buffer, but when we do clean up properly this may
23581              need to change.  */
23582           baton->size = DW_BLOCK (attr)->size;
23583           baton->data = DW_BLOCK (attr)->data;
23584         }
23585       else
23586         {
23587           dwarf2_invalid_attrib_class_complaint ("location description",
23588                                                  SYMBOL_NATURAL_NAME (sym));
23589           baton->size = 0;
23590         }
23591
23592       SYMBOL_ACLASS_INDEX (sym) = (is_block
23593                                    ? dwarf2_locexpr_block_index
23594                                    : dwarf2_locexpr_index);
23595       SYMBOL_LOCATION_BATON (sym) = baton;
23596     }
23597 }
23598
23599 /* Return the OBJFILE associated with the compilation unit CU.  If CU
23600    came from a separate debuginfo file, then the master objfile is
23601    returned.  */
23602
23603 struct objfile *
23604 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
23605 {
23606   struct objfile *objfile = per_cu->objfile;
23607
23608   /* Return the master objfile, so that we can report and look up the
23609      correct file containing this variable.  */
23610   if (objfile->separate_debug_objfile_backlink)
23611     objfile = objfile->separate_debug_objfile_backlink;
23612
23613   return objfile;
23614 }
23615
23616 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
23617    (CU_HEADERP is unused in such case) or prepare a temporary copy at
23618    CU_HEADERP first.  */
23619
23620 static const struct comp_unit_head *
23621 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
23622                        struct dwarf2_per_cu_data *per_cu)
23623 {
23624   const gdb_byte *info_ptr;
23625
23626   if (per_cu->cu)
23627     return &per_cu->cu->header;
23628
23629   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
23630
23631   memset (cu_headerp, 0, sizeof (*cu_headerp));
23632   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
23633                        rcuh_kind::COMPILE);
23634
23635   return cu_headerp;
23636 }
23637
23638 /* Return the address size given in the compilation unit header for CU.  */
23639
23640 int
23641 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
23642 {
23643   struct comp_unit_head cu_header_local;
23644   const struct comp_unit_head *cu_headerp;
23645
23646   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23647
23648   return cu_headerp->addr_size;
23649 }
23650
23651 /* Return the offset size given in the compilation unit header for CU.  */
23652
23653 int
23654 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23655 {
23656   struct comp_unit_head cu_header_local;
23657   const struct comp_unit_head *cu_headerp;
23658
23659   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23660
23661   return cu_headerp->offset_size;
23662 }
23663
23664 /* See its dwarf2loc.h declaration.  */
23665
23666 int
23667 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23668 {
23669   struct comp_unit_head cu_header_local;
23670   const struct comp_unit_head *cu_headerp;
23671
23672   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23673
23674   if (cu_headerp->version == 2)
23675     return cu_headerp->addr_size;
23676   else
23677     return cu_headerp->offset_size;
23678 }
23679
23680 /* Return the text offset of the CU.  The returned offset comes from
23681    this CU's objfile.  If this objfile came from a separate debuginfo
23682    file, then the offset may be different from the corresponding
23683    offset in the parent objfile.  */
23684
23685 CORE_ADDR
23686 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23687 {
23688   struct objfile *objfile = per_cu->objfile;
23689
23690   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23691 }
23692
23693 /* Return DWARF version number of PER_CU.  */
23694
23695 short
23696 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23697 {
23698   return per_cu->dwarf_version;
23699 }
23700
23701 /* Locate the .debug_info compilation unit from CU's objfile which contains
23702    the DIE at OFFSET.  Raises an error on failure.  */
23703
23704 static struct dwarf2_per_cu_data *
23705 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23706                                   unsigned int offset_in_dwz,
23707                                   struct objfile *objfile)
23708 {
23709   struct dwarf2_per_cu_data *this_cu;
23710   int low, high;
23711   const sect_offset *cu_off;
23712
23713   low = 0;
23714   high = dwarf2_per_objfile->n_comp_units - 1;
23715   while (high > low)
23716     {
23717       struct dwarf2_per_cu_data *mid_cu;
23718       int mid = low + (high - low) / 2;
23719
23720       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23721       cu_off = &mid_cu->sect_off;
23722       if (mid_cu->is_dwz > offset_in_dwz
23723           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23724         high = mid;
23725       else
23726         low = mid + 1;
23727     }
23728   gdb_assert (low == high);
23729   this_cu = dwarf2_per_objfile->all_comp_units[low];
23730   cu_off = &this_cu->sect_off;
23731   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23732     {
23733       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23734         error (_("Dwarf Error: could not find partial DIE containing "
23735                "offset 0x%x [in module %s]"),
23736                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23737
23738       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23739                   <= sect_off);
23740       return dwarf2_per_objfile->all_comp_units[low-1];
23741     }
23742   else
23743     {
23744       this_cu = dwarf2_per_objfile->all_comp_units[low];
23745       if (low == dwarf2_per_objfile->n_comp_units - 1
23746           && sect_off >= this_cu->sect_off + this_cu->length)
23747         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23748       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23749       return this_cu;
23750     }
23751 }
23752
23753 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23754
23755 static void
23756 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23757 {
23758   memset (cu, 0, sizeof (*cu));
23759   per_cu->cu = cu;
23760   cu->per_cu = per_cu;
23761   cu->objfile = per_cu->objfile;
23762   obstack_init (&cu->comp_unit_obstack);
23763 }
23764
23765 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23766
23767 static void
23768 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23769                        enum language pretend_language)
23770 {
23771   struct attribute *attr;
23772
23773   /* Set the language we're debugging.  */
23774   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23775   if (attr)
23776     set_cu_language (DW_UNSND (attr), cu);
23777   else
23778     {
23779       cu->language = pretend_language;
23780       cu->language_defn = language_def (cu->language);
23781     }
23782
23783   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23784 }
23785
23786 /* Release one cached compilation unit, CU.  We unlink it from the tree
23787    of compilation units, but we don't remove it from the read_in_chain;
23788    the caller is responsible for that.
23789    NOTE: DATA is a void * because this function is also used as a
23790    cleanup routine.  */
23791
23792 static void
23793 free_heap_comp_unit (void *data)
23794 {
23795   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23796
23797   gdb_assert (cu->per_cu != NULL);
23798   cu->per_cu->cu = NULL;
23799   cu->per_cu = NULL;
23800
23801   obstack_free (&cu->comp_unit_obstack, NULL);
23802
23803   xfree (cu);
23804 }
23805
23806 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23807    when we're finished with it.  We can't free the pointer itself, but be
23808    sure to unlink it from the cache.  Also release any associated storage.  */
23809
23810 static void
23811 free_stack_comp_unit (void *data)
23812 {
23813   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23814
23815   gdb_assert (cu->per_cu != NULL);
23816   cu->per_cu->cu = NULL;
23817   cu->per_cu = NULL;
23818
23819   obstack_free (&cu->comp_unit_obstack, NULL);
23820   cu->partial_dies = NULL;
23821 }
23822
23823 /* Free all cached compilation units.  */
23824
23825 static void
23826 free_cached_comp_units (void *data)
23827 {
23828   dwarf2_per_objfile->free_cached_comp_units ();
23829 }
23830
23831 /* Increase the age counter on each cached compilation unit, and free
23832    any that are too old.  */
23833
23834 static void
23835 age_cached_comp_units (void)
23836 {
23837   struct dwarf2_per_cu_data *per_cu, **last_chain;
23838
23839   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23840   per_cu = dwarf2_per_objfile->read_in_chain;
23841   while (per_cu != NULL)
23842     {
23843       per_cu->cu->last_used ++;
23844       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23845         dwarf2_mark (per_cu->cu);
23846       per_cu = per_cu->cu->read_in_chain;
23847     }
23848
23849   per_cu = dwarf2_per_objfile->read_in_chain;
23850   last_chain = &dwarf2_per_objfile->read_in_chain;
23851   while (per_cu != NULL)
23852     {
23853       struct dwarf2_per_cu_data *next_cu;
23854
23855       next_cu = per_cu->cu->read_in_chain;
23856
23857       if (!per_cu->cu->mark)
23858         {
23859           free_heap_comp_unit (per_cu->cu);
23860           *last_chain = next_cu;
23861         }
23862       else
23863         last_chain = &per_cu->cu->read_in_chain;
23864
23865       per_cu = next_cu;
23866     }
23867 }
23868
23869 /* Remove a single compilation unit from the cache.  */
23870
23871 static void
23872 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23873 {
23874   struct dwarf2_per_cu_data *per_cu, **last_chain;
23875
23876   per_cu = dwarf2_per_objfile->read_in_chain;
23877   last_chain = &dwarf2_per_objfile->read_in_chain;
23878   while (per_cu != NULL)
23879     {
23880       struct dwarf2_per_cu_data *next_cu;
23881
23882       next_cu = per_cu->cu->read_in_chain;
23883
23884       if (per_cu == target_per_cu)
23885         {
23886           free_heap_comp_unit (per_cu->cu);
23887           per_cu->cu = NULL;
23888           *last_chain = next_cu;
23889           break;
23890         }
23891       else
23892         last_chain = &per_cu->cu->read_in_chain;
23893
23894       per_cu = next_cu;
23895     }
23896 }
23897
23898 /* Release all extra memory associated with OBJFILE.  */
23899
23900 void
23901 dwarf2_free_objfile (struct objfile *objfile)
23902 {
23903   dwarf2_per_objfile
23904     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23905                                                   dwarf2_objfile_data_key);
23906
23907   if (dwarf2_per_objfile == NULL)
23908     return;
23909
23910   dwarf2_per_objfile->~dwarf2_per_objfile ();
23911 }
23912
23913 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23914    We store these in a hash table separate from the DIEs, and preserve them
23915    when the DIEs are flushed out of cache.
23916
23917    The CU "per_cu" pointer is needed because offset alone is not enough to
23918    uniquely identify the type.  A file may have multiple .debug_types sections,
23919    or the type may come from a DWO file.  Furthermore, while it's more logical
23920    to use per_cu->section+offset, with Fission the section with the data is in
23921    the DWO file but we don't know that section at the point we need it.
23922    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23923    because we can enter the lookup routine, get_die_type_at_offset, from
23924    outside this file, and thus won't necessarily have PER_CU->cu.
23925    Fortunately, PER_CU is stable for the life of the objfile.  */
23926
23927 struct dwarf2_per_cu_offset_and_type
23928 {
23929   const struct dwarf2_per_cu_data *per_cu;
23930   sect_offset sect_off;
23931   struct type *type;
23932 };
23933
23934 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23935
23936 static hashval_t
23937 per_cu_offset_and_type_hash (const void *item)
23938 {
23939   const struct dwarf2_per_cu_offset_and_type *ofs
23940     = (const struct dwarf2_per_cu_offset_and_type *) item;
23941
23942   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23943 }
23944
23945 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23946
23947 static int
23948 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23949 {
23950   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23951     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23952   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23953     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23954
23955   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23956           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23957 }
23958
23959 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23960    table if necessary.  For convenience, return TYPE.
23961
23962    The DIEs reading must have careful ordering to:
23963     * Not cause infite loops trying to read in DIEs as a prerequisite for
23964       reading current DIE.
23965     * Not trying to dereference contents of still incompletely read in types
23966       while reading in other DIEs.
23967     * Enable referencing still incompletely read in types just by a pointer to
23968       the type without accessing its fields.
23969
23970    Therefore caller should follow these rules:
23971      * Try to fetch any prerequisite types we may need to build this DIE type
23972        before building the type and calling set_die_type.
23973      * After building type call set_die_type for current DIE as soon as
23974        possible before fetching more types to complete the current type.
23975      * Make the type as complete as possible before fetching more types.  */
23976
23977 static struct type *
23978 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23979 {
23980   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23981   struct objfile *objfile = cu->objfile;
23982   struct attribute *attr;
23983   struct dynamic_prop prop;
23984
23985   /* For Ada types, make sure that the gnat-specific data is always
23986      initialized (if not already set).  There are a few types where
23987      we should not be doing so, because the type-specific area is
23988      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23989      where the type-specific area is used to store the floatformat).
23990      But this is not a problem, because the gnat-specific information
23991      is actually not needed for these types.  */
23992   if (need_gnat_info (cu)
23993       && TYPE_CODE (type) != TYPE_CODE_FUNC
23994       && TYPE_CODE (type) != TYPE_CODE_FLT
23995       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23996       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23997       && TYPE_CODE (type) != TYPE_CODE_METHOD
23998       && !HAVE_GNAT_AUX_INFO (type))
23999     INIT_GNAT_SPECIFIC (type);
24000
24001   /* Read DW_AT_allocated and set in type.  */
24002   attr = dwarf2_attr (die, DW_AT_allocated, cu);
24003   if (attr_form_is_block (attr))
24004     {
24005       if (attr_to_dynamic_prop (attr, die, cu, &prop))
24006         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
24007     }
24008   else if (attr != NULL)
24009     {
24010       complaint (&symfile_complaints,
24011                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
24012                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24013                  to_underlying (die->sect_off));
24014     }
24015
24016   /* Read DW_AT_associated and set in type.  */
24017   attr = dwarf2_attr (die, DW_AT_associated, cu);
24018   if (attr_form_is_block (attr))
24019     {
24020       if (attr_to_dynamic_prop (attr, die, cu, &prop))
24021         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
24022     }
24023   else if (attr != NULL)
24024     {
24025       complaint (&symfile_complaints,
24026                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
24027                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24028                  to_underlying (die->sect_off));
24029     }
24030
24031   /* Read DW_AT_data_location and set in type.  */
24032   attr = dwarf2_attr (die, DW_AT_data_location, cu);
24033   if (attr_to_dynamic_prop (attr, die, cu, &prop))
24034     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
24035
24036   if (dwarf2_per_objfile->die_type_hash == NULL)
24037     {
24038       dwarf2_per_objfile->die_type_hash =
24039         htab_create_alloc_ex (127,
24040                               per_cu_offset_and_type_hash,
24041                               per_cu_offset_and_type_eq,
24042                               NULL,
24043                               &objfile->objfile_obstack,
24044                               hashtab_obstack_allocate,
24045                               dummy_obstack_deallocate);
24046     }
24047
24048   ofs.per_cu = cu->per_cu;
24049   ofs.sect_off = die->sect_off;
24050   ofs.type = type;
24051   slot = (struct dwarf2_per_cu_offset_and_type **)
24052     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
24053   if (*slot)
24054     complaint (&symfile_complaints,
24055                _("A problem internal to GDB: DIE 0x%x has type already set"),
24056                to_underlying (die->sect_off));
24057   *slot = XOBNEW (&objfile->objfile_obstack,
24058                   struct dwarf2_per_cu_offset_and_type);
24059   **slot = ofs;
24060   return type;
24061 }
24062
24063 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24064    or return NULL if the die does not have a saved type.  */
24065
24066 static struct type *
24067 get_die_type_at_offset (sect_offset sect_off,
24068                         struct dwarf2_per_cu_data *per_cu)
24069 {
24070   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24071
24072   if (dwarf2_per_objfile->die_type_hash == NULL)
24073     return NULL;
24074
24075   ofs.per_cu = per_cu;
24076   ofs.sect_off = sect_off;
24077   slot = ((struct dwarf2_per_cu_offset_and_type *)
24078           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
24079   if (slot)
24080     return slot->type;
24081   else
24082     return NULL;
24083 }
24084
24085 /* Look up the type for DIE in CU in die_type_hash,
24086    or return NULL if DIE does not have a saved type.  */
24087
24088 static struct type *
24089 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24090 {
24091   return get_die_type_at_offset (die->sect_off, cu->per_cu);
24092 }
24093
24094 /* Add a dependence relationship from CU to REF_PER_CU.  */
24095
24096 static void
24097 dwarf2_add_dependence (struct dwarf2_cu *cu,
24098                        struct dwarf2_per_cu_data *ref_per_cu)
24099 {
24100   void **slot;
24101
24102   if (cu->dependencies == NULL)
24103     cu->dependencies
24104       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
24105                               NULL, &cu->comp_unit_obstack,
24106                               hashtab_obstack_allocate,
24107                               dummy_obstack_deallocate);
24108
24109   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
24110   if (*slot == NULL)
24111     *slot = ref_per_cu;
24112 }
24113
24114 /* Subroutine of dwarf2_mark to pass to htab_traverse.
24115    Set the mark field in every compilation unit in the
24116    cache that we must keep because we are keeping CU.  */
24117
24118 static int
24119 dwarf2_mark_helper (void **slot, void *data)
24120 {
24121   struct dwarf2_per_cu_data *per_cu;
24122
24123   per_cu = (struct dwarf2_per_cu_data *) *slot;
24124
24125   /* cu->dependencies references may not yet have been ever read if QUIT aborts
24126      reading of the chain.  As such dependencies remain valid it is not much
24127      useful to track and undo them during QUIT cleanups.  */
24128   if (per_cu->cu == NULL)
24129     return 1;
24130
24131   if (per_cu->cu->mark)
24132     return 1;
24133   per_cu->cu->mark = 1;
24134
24135   if (per_cu->cu->dependencies != NULL)
24136     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
24137
24138   return 1;
24139 }
24140
24141 /* Set the mark field in CU and in every other compilation unit in the
24142    cache that we must keep because we are keeping CU.  */
24143
24144 static void
24145 dwarf2_mark (struct dwarf2_cu *cu)
24146 {
24147   if (cu->mark)
24148     return;
24149   cu->mark = 1;
24150   if (cu->dependencies != NULL)
24151     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
24152 }
24153
24154 static void
24155 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
24156 {
24157   while (per_cu)
24158     {
24159       per_cu->cu->mark = 0;
24160       per_cu = per_cu->cu->read_in_chain;
24161     }
24162 }
24163
24164 /* Trivial hash function for partial_die_info: the hash value of a DIE
24165    is its offset in .debug_info for this objfile.  */
24166
24167 static hashval_t
24168 partial_die_hash (const void *item)
24169 {
24170   const struct partial_die_info *part_die
24171     = (const struct partial_die_info *) item;
24172
24173   return to_underlying (part_die->sect_off);
24174 }
24175
24176 /* Trivial comparison function for partial_die_info structures: two DIEs
24177    are equal if they have the same offset.  */
24178
24179 static int
24180 partial_die_eq (const void *item_lhs, const void *item_rhs)
24181 {
24182   const struct partial_die_info *part_die_lhs
24183     = (const struct partial_die_info *) item_lhs;
24184   const struct partial_die_info *part_die_rhs
24185     = (const struct partial_die_info *) item_rhs;
24186
24187   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24188 }
24189
24190 static struct cmd_list_element *set_dwarf_cmdlist;
24191 static struct cmd_list_element *show_dwarf_cmdlist;
24192
24193 static void
24194 set_dwarf_cmd (const char *args, int from_tty)
24195 {
24196   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
24197              gdb_stdout);
24198 }
24199
24200 static void
24201 show_dwarf_cmd (const char *args, int from_tty)
24202 {
24203   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
24204 }
24205
24206 /* Free data associated with OBJFILE, if necessary.  */
24207
24208 static void
24209 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
24210 {
24211   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
24212   int ix;
24213
24214   /* Make sure we don't accidentally use dwarf2_per_objfile while
24215      cleaning up.  */
24216   dwarf2_per_objfile = NULL;
24217
24218   for (ix = 0; ix < data->n_comp_units; ++ix)
24219    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
24220
24221   for (ix = 0; ix < data->n_type_units; ++ix)
24222     VEC_free (dwarf2_per_cu_ptr,
24223               data->all_type_units[ix]->per_cu.imported_symtabs);
24224   xfree (data->all_type_units);
24225
24226   VEC_free (dwarf2_section_info_def, data->types);
24227
24228   if (data->dwo_files)
24229     free_dwo_files (data->dwo_files, objfile);
24230   if (data->dwp_file)
24231     gdb_bfd_unref (data->dwp_file->dbfd);
24232
24233   if (data->dwz_file && data->dwz_file->dwz_bfd)
24234     gdb_bfd_unref (data->dwz_file->dwz_bfd);
24235
24236   if (data->index_table != NULL)
24237     data->index_table->~mapped_index ();
24238 }
24239
24240 \f
24241 /* The "save gdb-index" command.  */
24242
24243 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
24244    error checking.  */
24245
24246 static void
24247 file_write (FILE *file, const void *data, size_t size)
24248 {
24249   if (fwrite (data, 1, size, file) != size)
24250     error (_("couldn't data write to file"));
24251 }
24252
24253 /* Write the contents of VEC to FILE, with error checking.  */
24254
24255 template<typename Elem, typename Alloc>
24256 static void
24257 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
24258 {
24259   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
24260 }
24261
24262 /* In-memory buffer to prepare data to be written later to a file.  */
24263 class data_buf
24264 {
24265 public:
24266   /* Copy DATA to the end of the buffer.  */
24267   template<typename T>
24268   void append_data (const T &data)
24269   {
24270     std::copy (reinterpret_cast<const gdb_byte *> (&data),
24271                reinterpret_cast<const gdb_byte *> (&data + 1),
24272                grow (sizeof (data)));
24273   }
24274
24275   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
24276      terminating zero is appended too.  */
24277   void append_cstr0 (const char *cstr)
24278   {
24279     const size_t size = strlen (cstr) + 1;
24280     std::copy (cstr, cstr + size, grow (size));
24281   }
24282
24283   /* Store INPUT as ULEB128 to the end of buffer.  */
24284   void append_unsigned_leb128 (ULONGEST input)
24285   {
24286     for (;;)
24287       {
24288         gdb_byte output = input & 0x7f;
24289         input >>= 7;
24290         if (input)
24291           output |= 0x80;
24292         append_data (output);
24293         if (input == 0)
24294           break;
24295       }
24296   }
24297
24298   /* Accept a host-format integer in VAL and append it to the buffer
24299      as a target-format integer which is LEN bytes long.  */
24300   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
24301   {
24302     ::store_unsigned_integer (grow (len), len, byte_order, val);
24303   }
24304
24305   /* Return the size of the buffer.  */
24306   size_t size () const
24307   {
24308     return m_vec.size ();
24309   }
24310
24311   /* Return true iff the buffer is empty.  */
24312   bool empty () const
24313   {
24314     return m_vec.empty ();
24315   }
24316
24317   /* Write the buffer to FILE.  */
24318   void file_write (FILE *file) const
24319   {
24320     ::file_write (file, m_vec);
24321   }
24322
24323 private:
24324   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
24325      the start of the new block.  */
24326   gdb_byte *grow (size_t size)
24327   {
24328     m_vec.resize (m_vec.size () + size);
24329     return &*m_vec.end () - size;
24330   }
24331
24332   gdb::byte_vector m_vec;
24333 };
24334
24335 /* An entry in the symbol table.  */
24336 struct symtab_index_entry
24337 {
24338   /* The name of the symbol.  */
24339   const char *name;
24340   /* The offset of the name in the constant pool.  */
24341   offset_type index_offset;
24342   /* A sorted vector of the indices of all the CUs that hold an object
24343      of this name.  */
24344   std::vector<offset_type> cu_indices;
24345 };
24346
24347 /* The symbol table.  This is a power-of-2-sized hash table.  */
24348 struct mapped_symtab
24349 {
24350   mapped_symtab ()
24351   {
24352     data.resize (1024);
24353   }
24354
24355   offset_type n_elements = 0;
24356   std::vector<symtab_index_entry> data;
24357 };
24358
24359 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
24360    the slot.
24361    
24362    Function is used only during write_hash_table so no index format backward
24363    compatibility is needed.  */
24364
24365 static symtab_index_entry &
24366 find_slot (struct mapped_symtab *symtab, const char *name)
24367 {
24368   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
24369
24370   index = hash & (symtab->data.size () - 1);
24371   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
24372
24373   for (;;)
24374     {
24375       if (symtab->data[index].name == NULL
24376           || strcmp (name, symtab->data[index].name) == 0)
24377         return symtab->data[index];
24378       index = (index + step) & (symtab->data.size () - 1);
24379     }
24380 }
24381
24382 /* Expand SYMTAB's hash table.  */
24383
24384 static void
24385 hash_expand (struct mapped_symtab *symtab)
24386 {
24387   auto old_entries = std::move (symtab->data);
24388
24389   symtab->data.clear ();
24390   symtab->data.resize (old_entries.size () * 2);
24391
24392   for (auto &it : old_entries)
24393     if (it.name != NULL)
24394       {
24395         auto &ref = find_slot (symtab, it.name);
24396         ref = std::move (it);
24397       }
24398 }
24399
24400 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
24401    CU_INDEX is the index of the CU in which the symbol appears.
24402    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
24403
24404 static void
24405 add_index_entry (struct mapped_symtab *symtab, const char *name,
24406                  int is_static, gdb_index_symbol_kind kind,
24407                  offset_type cu_index)
24408 {
24409   offset_type cu_index_and_attrs;
24410
24411   ++symtab->n_elements;
24412   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
24413     hash_expand (symtab);
24414
24415   symtab_index_entry &slot = find_slot (symtab, name);
24416   if (slot.name == NULL)
24417     {
24418       slot.name = name;
24419       /* index_offset is set later.  */
24420     }
24421
24422   cu_index_and_attrs = 0;
24423   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
24424   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
24425   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
24426
24427   /* We don't want to record an index value twice as we want to avoid the
24428      duplication.
24429      We process all global symbols and then all static symbols
24430      (which would allow us to avoid the duplication by only having to check
24431      the last entry pushed), but a symbol could have multiple kinds in one CU.
24432      To keep things simple we don't worry about the duplication here and
24433      sort and uniqufy the list after we've processed all symbols.  */
24434   slot.cu_indices.push_back (cu_index_and_attrs);
24435 }
24436
24437 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
24438
24439 static void
24440 uniquify_cu_indices (struct mapped_symtab *symtab)
24441 {
24442   for (auto &entry : symtab->data)
24443     {
24444       if (entry.name != NULL && !entry.cu_indices.empty ())
24445         {
24446           auto &cu_indices = entry.cu_indices;
24447           std::sort (cu_indices.begin (), cu_indices.end ());
24448           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
24449           cu_indices.erase (from, cu_indices.end ());
24450         }
24451     }
24452 }
24453
24454 /* A form of 'const char *' suitable for container keys.  Only the
24455    pointer is stored.  The strings themselves are compared, not the
24456    pointers.  */
24457 class c_str_view
24458 {
24459 public:
24460   c_str_view (const char *cstr)
24461     : m_cstr (cstr)
24462   {}
24463
24464   bool operator== (const c_str_view &other) const
24465   {
24466     return strcmp (m_cstr, other.m_cstr) == 0;
24467   }
24468
24469   /* Return the underlying C string.  Note, the returned string is
24470      only a reference with lifetime of this object.  */
24471   const char *c_str () const
24472   {
24473     return m_cstr;
24474   }
24475
24476 private:
24477   friend class c_str_view_hasher;
24478   const char *const m_cstr;
24479 };
24480
24481 /* A std::unordered_map::hasher for c_str_view that uses the right
24482    hash function for strings in a mapped index.  */
24483 class c_str_view_hasher
24484 {
24485 public:
24486   size_t operator () (const c_str_view &x) const
24487   {
24488     return mapped_index_string_hash (INT_MAX, x.m_cstr);
24489   }
24490 };
24491
24492 /* A std::unordered_map::hasher for std::vector<>.  */
24493 template<typename T>
24494 class vector_hasher
24495 {
24496 public:
24497   size_t operator () (const std::vector<T> &key) const
24498   {
24499     return iterative_hash (key.data (),
24500                            sizeof (key.front ()) * key.size (), 0);
24501   }
24502 };
24503
24504 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
24505    constant pool entries going into the data buffer CPOOL.  */
24506
24507 static void
24508 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
24509 {
24510   {
24511     /* Elements are sorted vectors of the indices of all the CUs that
24512        hold an object of this name.  */
24513     std::unordered_map<std::vector<offset_type>, offset_type,
24514                        vector_hasher<offset_type>>
24515       symbol_hash_table;
24516
24517     /* We add all the index vectors to the constant pool first, to
24518        ensure alignment is ok.  */
24519     for (symtab_index_entry &entry : symtab->data)
24520       {
24521         if (entry.name == NULL)
24522           continue;
24523         gdb_assert (entry.index_offset == 0);
24524
24525         /* Finding before inserting is faster than always trying to
24526            insert, because inserting always allocates a node, does the
24527            lookup, and then destroys the new node if another node
24528            already had the same key.  C++17 try_emplace will avoid
24529            this.  */
24530         const auto found
24531           = symbol_hash_table.find (entry.cu_indices);
24532         if (found != symbol_hash_table.end ())
24533           {
24534             entry.index_offset = found->second;
24535             continue;
24536           }
24537
24538         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
24539         entry.index_offset = cpool.size ();
24540         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
24541         for (const auto index : entry.cu_indices)
24542           cpool.append_data (MAYBE_SWAP (index));
24543       }
24544   }
24545
24546   /* Now write out the hash table.  */
24547   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
24548   for (const auto &entry : symtab->data)
24549     {
24550       offset_type str_off, vec_off;
24551
24552       if (entry.name != NULL)
24553         {
24554           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
24555           if (insertpair.second)
24556             cpool.append_cstr0 (entry.name);
24557           str_off = insertpair.first->second;
24558           vec_off = entry.index_offset;
24559         }
24560       else
24561         {
24562           /* While 0 is a valid constant pool index, it is not valid
24563              to have 0 for both offsets.  */
24564           str_off = 0;
24565           vec_off = 0;
24566         }
24567
24568       output.append_data (MAYBE_SWAP (str_off));
24569       output.append_data (MAYBE_SWAP (vec_off));
24570     }
24571 }
24572
24573 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
24574
24575 /* Helper struct for building the address table.  */
24576 struct addrmap_index_data
24577 {
24578   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
24579     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
24580   {}
24581
24582   struct objfile *objfile;
24583   data_buf &addr_vec;
24584   psym_index_map &cu_index_htab;
24585
24586   /* Non-zero if the previous_* fields are valid.
24587      We can't write an entry until we see the next entry (since it is only then
24588      that we know the end of the entry).  */
24589   int previous_valid;
24590   /* Index of the CU in the table of all CUs in the index file.  */
24591   unsigned int previous_cu_index;
24592   /* Start address of the CU.  */
24593   CORE_ADDR previous_cu_start;
24594 };
24595
24596 /* Write an address entry to ADDR_VEC.  */
24597
24598 static void
24599 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
24600                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
24601 {
24602   CORE_ADDR baseaddr;
24603
24604   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24605
24606   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
24607   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
24608   addr_vec.append_data (MAYBE_SWAP (cu_index));
24609 }
24610
24611 /* Worker function for traversing an addrmap to build the address table.  */
24612
24613 static int
24614 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
24615 {
24616   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
24617   struct partial_symtab *pst = (struct partial_symtab *) obj;
24618
24619   if (data->previous_valid)
24620     add_address_entry (data->objfile, data->addr_vec,
24621                        data->previous_cu_start, start_addr,
24622                        data->previous_cu_index);
24623
24624   data->previous_cu_start = start_addr;
24625   if (pst != NULL)
24626     {
24627       const auto it = data->cu_index_htab.find (pst);
24628       gdb_assert (it != data->cu_index_htab.cend ());
24629       data->previous_cu_index = it->second;
24630       data->previous_valid = 1;
24631     }
24632   else
24633     data->previous_valid = 0;
24634
24635   return 0;
24636 }
24637
24638 /* Write OBJFILE's address map to ADDR_VEC.
24639    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
24640    in the index file.  */
24641
24642 static void
24643 write_address_map (struct objfile *objfile, data_buf &addr_vec,
24644                    psym_index_map &cu_index_htab)
24645 {
24646   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
24647
24648   /* When writing the address table, we have to cope with the fact that
24649      the addrmap iterator only provides the start of a region; we have to
24650      wait until the next invocation to get the start of the next region.  */
24651
24652   addrmap_index_data.objfile = objfile;
24653   addrmap_index_data.previous_valid = 0;
24654
24655   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
24656                    &addrmap_index_data);
24657
24658   /* It's highly unlikely the last entry (end address = 0xff...ff)
24659      is valid, but we should still handle it.
24660      The end address is recorded as the start of the next region, but that
24661      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
24662      anyway.  */
24663   if (addrmap_index_data.previous_valid)
24664     add_address_entry (objfile, addr_vec,
24665                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
24666                        addrmap_index_data.previous_cu_index);
24667 }
24668
24669 /* Return the symbol kind of PSYM.  */
24670
24671 static gdb_index_symbol_kind
24672 symbol_kind (struct partial_symbol *psym)
24673 {
24674   domain_enum domain = PSYMBOL_DOMAIN (psym);
24675   enum address_class aclass = PSYMBOL_CLASS (psym);
24676
24677   switch (domain)
24678     {
24679     case VAR_DOMAIN:
24680       switch (aclass)
24681         {
24682         case LOC_BLOCK:
24683           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
24684         case LOC_TYPEDEF:
24685           return GDB_INDEX_SYMBOL_KIND_TYPE;
24686         case LOC_COMPUTED:
24687         case LOC_CONST_BYTES:
24688         case LOC_OPTIMIZED_OUT:
24689         case LOC_STATIC:
24690           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24691         case LOC_CONST:
24692           /* Note: It's currently impossible to recognize psyms as enum values
24693              short of reading the type info.  For now punt.  */
24694           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24695         default:
24696           /* There are other LOC_FOO values that one might want to classify
24697              as variables, but dwarf2read.c doesn't currently use them.  */
24698           return GDB_INDEX_SYMBOL_KIND_OTHER;
24699         }
24700     case STRUCT_DOMAIN:
24701       return GDB_INDEX_SYMBOL_KIND_TYPE;
24702     default:
24703       return GDB_INDEX_SYMBOL_KIND_OTHER;
24704     }
24705 }
24706
24707 /* Add a list of partial symbols to SYMTAB.  */
24708
24709 static void
24710 write_psymbols (struct mapped_symtab *symtab,
24711                 std::unordered_set<partial_symbol *> &psyms_seen,
24712                 struct partial_symbol **psymp,
24713                 int count,
24714                 offset_type cu_index,
24715                 int is_static)
24716 {
24717   for (; count-- > 0; ++psymp)
24718     {
24719       struct partial_symbol *psym = *psymp;
24720
24721       if (SYMBOL_LANGUAGE (psym) == language_ada)
24722         error (_("Ada is not currently supported by the index"));
24723
24724       /* Only add a given psymbol once.  */
24725       if (psyms_seen.insert (psym).second)
24726         {
24727           gdb_index_symbol_kind kind = symbol_kind (psym);
24728
24729           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24730                            is_static, kind, cu_index);
24731         }
24732     }
24733 }
24734
24735 /* A helper struct used when iterating over debug_types.  */
24736 struct signatured_type_index_data
24737 {
24738   signatured_type_index_data (data_buf &types_list_,
24739                               std::unordered_set<partial_symbol *> &psyms_seen_)
24740     : types_list (types_list_), psyms_seen (psyms_seen_)
24741   {}
24742
24743   struct objfile *objfile;
24744   struct mapped_symtab *symtab;
24745   data_buf &types_list;
24746   std::unordered_set<partial_symbol *> &psyms_seen;
24747   int cu_index;
24748 };
24749
24750 /* A helper function that writes a single signatured_type to an
24751    obstack.  */
24752
24753 static int
24754 write_one_signatured_type (void **slot, void *d)
24755 {
24756   struct signatured_type_index_data *info
24757     = (struct signatured_type_index_data *) d;
24758   struct signatured_type *entry = (struct signatured_type *) *slot;
24759   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24760
24761   write_psymbols (info->symtab,
24762                   info->psyms_seen,
24763                   &info->objfile->global_psymbols[psymtab->globals_offset],
24764                   psymtab->n_global_syms, info->cu_index,
24765                   0);
24766   write_psymbols (info->symtab,
24767                   info->psyms_seen,
24768                   &info->objfile->static_psymbols[psymtab->statics_offset],
24769                   psymtab->n_static_syms, info->cu_index,
24770                   1);
24771
24772   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24773                                 to_underlying (entry->per_cu.sect_off));
24774   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24775                                 to_underlying (entry->type_offset_in_tu));
24776   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24777
24778   ++info->cu_index;
24779
24780   return 1;
24781 }
24782
24783 /* Recurse into all "included" dependencies and count their symbols as
24784    if they appeared in this psymtab.  */
24785
24786 static void
24787 recursively_count_psymbols (struct partial_symtab *psymtab,
24788                             size_t &psyms_seen)
24789 {
24790   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24791     if (psymtab->dependencies[i]->user != NULL)
24792       recursively_count_psymbols (psymtab->dependencies[i],
24793                                   psyms_seen);
24794
24795   psyms_seen += psymtab->n_global_syms;
24796   psyms_seen += psymtab->n_static_syms;
24797 }
24798
24799 /* Recurse into all "included" dependencies and write their symbols as
24800    if they appeared in this psymtab.  */
24801
24802 static void
24803 recursively_write_psymbols (struct objfile *objfile,
24804                             struct partial_symtab *psymtab,
24805                             struct mapped_symtab *symtab,
24806                             std::unordered_set<partial_symbol *> &psyms_seen,
24807                             offset_type cu_index)
24808 {
24809   int i;
24810
24811   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24812     if (psymtab->dependencies[i]->user != NULL)
24813       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24814                                   symtab, psyms_seen, cu_index);
24815
24816   write_psymbols (symtab,
24817                   psyms_seen,
24818                   &objfile->global_psymbols[psymtab->globals_offset],
24819                   psymtab->n_global_syms, cu_index,
24820                   0);
24821   write_psymbols (symtab,
24822                   psyms_seen,
24823                   &objfile->static_psymbols[psymtab->statics_offset],
24824                   psymtab->n_static_syms, cu_index,
24825                   1);
24826 }
24827
24828 /* Symbol name hashing function as specified by DWARF-5.  */
24829
24830 static uint32_t
24831 dwarf5_djb_hash (const char *str_)
24832 {
24833   const unsigned char *str = (const unsigned char *) str_;
24834
24835   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
24836      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
24837
24838   uint32_t hash = 5381;
24839   while (int c = *str++)
24840     hash = hash * 33 + tolower (c);
24841   return hash;
24842 }
24843
24844 /* DWARF-5 .debug_names builder.  */
24845 class debug_names
24846 {
24847 public:
24848   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
24849     : m_dwarf5_byte_order (dwarf5_byte_order),
24850       m_dwarf32 (dwarf5_byte_order),
24851       m_dwarf64 (dwarf5_byte_order),
24852       m_dwarf (is_dwarf64
24853                ? static_cast<dwarf &> (m_dwarf64)
24854                : static_cast<dwarf &> (m_dwarf32)),
24855       m_name_table_string_offs (m_dwarf.name_table_string_offs),
24856       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
24857   {}
24858
24859   /* Insert one symbol.  */
24860   void insert (const partial_symbol *psym, int cu_index, bool is_static)
24861   {
24862     const int dwarf_tag = psymbol_tag (psym);
24863     if (dwarf_tag == 0)
24864       return;
24865     const char *const name = SYMBOL_SEARCH_NAME (psym);
24866     const auto insertpair
24867       = m_name_to_value_set.emplace (c_str_view (name),
24868                                      std::set<symbol_value> ());
24869     std::set<symbol_value> &value_set = insertpair.first->second;
24870     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static));
24871   }
24872
24873   /* Build all the tables.  All symbols must be already inserted.
24874      This function does not call file_write, caller has to do it
24875      afterwards.  */
24876   void build ()
24877   {
24878     /* Verify the build method has not be called twice.  */
24879     gdb_assert (m_abbrev_table.empty ());
24880     const size_t name_count = m_name_to_value_set.size ();
24881     m_bucket_table.resize
24882       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
24883     m_hash_table.reserve (name_count);
24884     m_name_table_string_offs.reserve (name_count);
24885     m_name_table_entry_offs.reserve (name_count);
24886
24887     /* Map each hash of symbol to its name and value.  */
24888     struct hash_it_pair
24889     {
24890       uint32_t hash;
24891       decltype (m_name_to_value_set)::const_iterator it;
24892     };
24893     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
24894     bucket_hash.resize (m_bucket_table.size ());
24895     for (decltype (m_name_to_value_set)::const_iterator it
24896            = m_name_to_value_set.cbegin ();
24897          it != m_name_to_value_set.cend ();
24898          ++it)
24899       {
24900         const char *const name = it->first.c_str ();
24901         const uint32_t hash = dwarf5_djb_hash (name);
24902         hash_it_pair hashitpair;
24903         hashitpair.hash = hash;
24904         hashitpair.it = it;
24905         auto &slot = bucket_hash[hash % bucket_hash.size()];
24906         slot.push_front (std::move (hashitpair));
24907       }
24908     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
24909       {
24910         const std::forward_list<hash_it_pair> &hashitlist
24911           = bucket_hash[bucket_ix];
24912         if (hashitlist.empty ())
24913           continue;
24914         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
24915         /* The hashes array is indexed starting at 1.  */
24916         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
24917                                 sizeof (bucket_slot), m_dwarf5_byte_order,
24918                                 m_hash_table.size () + 1);
24919         for (const hash_it_pair &hashitpair : hashitlist)
24920           {
24921             m_hash_table.push_back (0);
24922             store_unsigned_integer (reinterpret_cast<gdb_byte *>
24923                                                         (&m_hash_table.back ()),
24924                                     sizeof (m_hash_table.back ()),
24925                                     m_dwarf5_byte_order, hashitpair.hash);
24926             const c_str_view &name = hashitpair.it->first;
24927             const std::set<symbol_value> &value_set = hashitpair.it->second;
24928             m_name_table_string_offs.push_back_reorder
24929               (m_debugstrlookup.lookup (name.c_str ()));
24930             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
24931             gdb_assert (!value_set.empty ());
24932             for (const symbol_value &value : value_set)
24933               {
24934                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
24935                                                         value.is_static)];
24936                 if (idx == 0)
24937                   {
24938                     idx = m_idx_next++;
24939                     m_abbrev_table.append_unsigned_leb128 (idx);
24940                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
24941                     m_abbrev_table.append_unsigned_leb128 (DW_IDX_compile_unit);
24942                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
24943                     m_abbrev_table.append_unsigned_leb128 (value.is_static
24944                                                            ? DW_IDX_GNU_internal
24945                                                            : DW_IDX_GNU_external);
24946                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
24947
24948                     /* Terminate attributes list.  */
24949                     m_abbrev_table.append_unsigned_leb128 (0);
24950                     m_abbrev_table.append_unsigned_leb128 (0);
24951                   }
24952
24953                 m_entry_pool.append_unsigned_leb128 (idx);
24954                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
24955               }
24956
24957             /* Terminate the list of CUs.  */
24958             m_entry_pool.append_unsigned_leb128 (0);
24959           }
24960       }
24961     gdb_assert (m_hash_table.size () == name_count);
24962
24963     /* Terminate tags list.  */
24964     m_abbrev_table.append_unsigned_leb128 (0);
24965   }
24966
24967   /* Return .debug_names bucket count.  This must be called only after
24968      calling the build method.  */
24969   uint32_t bucket_count () const
24970   {
24971     /* Verify the build method has been already called.  */
24972     gdb_assert (!m_abbrev_table.empty ());
24973     const uint32_t retval = m_bucket_table.size ();
24974
24975     /* Check for overflow.  */
24976     gdb_assert (retval == m_bucket_table.size ());
24977     return retval;
24978   }
24979
24980   /* Return .debug_names names count.  This must be called only after
24981      calling the build method.  */
24982   uint32_t name_count () const
24983   {
24984     /* Verify the build method has been already called.  */
24985     gdb_assert (!m_abbrev_table.empty ());
24986     const uint32_t retval = m_hash_table.size ();
24987
24988     /* Check for overflow.  */
24989     gdb_assert (retval == m_hash_table.size ());
24990     return retval;
24991   }
24992
24993   /* Return number of bytes of .debug_names abbreviation table.  This
24994      must be called only after calling the build method.  */
24995   uint32_t abbrev_table_bytes () const
24996   {
24997     gdb_assert (!m_abbrev_table.empty ());
24998     return m_abbrev_table.size ();
24999   }
25000
25001   /* Recurse into all "included" dependencies and store their symbols
25002      as if they appeared in this psymtab.  */
25003   void recursively_write_psymbols
25004     (struct objfile *objfile,
25005      struct partial_symtab *psymtab,
25006      std::unordered_set<partial_symbol *> &psyms_seen,
25007      int cu_index)
25008   {
25009     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
25010       if (psymtab->dependencies[i]->user != NULL)
25011         recursively_write_psymbols (objfile, psymtab->dependencies[i],
25012                                     psyms_seen, cu_index);
25013
25014     write_psymbols (psyms_seen,
25015                     &objfile->global_psymbols[psymtab->globals_offset],
25016                     psymtab->n_global_syms, cu_index, false);
25017     write_psymbols (psyms_seen,
25018                     &objfile->static_psymbols[psymtab->statics_offset],
25019                     psymtab->n_static_syms, cu_index, true);
25020   }
25021
25022   /* Return number of bytes the .debug_names section will have.  This
25023      must be called only after calling the build method.  */
25024   size_t bytes () const
25025   {
25026     /* Verify the build method has been already called.  */
25027     gdb_assert (!m_abbrev_table.empty ());
25028     size_t expected_bytes = 0;
25029     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
25030     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
25031     expected_bytes += m_name_table_string_offs.bytes ();
25032     expected_bytes += m_name_table_entry_offs.bytes ();
25033     expected_bytes += m_abbrev_table.size ();
25034     expected_bytes += m_entry_pool.size ();
25035     return expected_bytes;
25036   }
25037
25038   /* Write .debug_names to FILE_NAMES and .debug_str addition to
25039      FILE_STR.  This must be called only after calling the build
25040      method.  */
25041   void file_write (FILE *file_names, FILE *file_str) const
25042   {
25043     /* Verify the build method has been already called.  */
25044     gdb_assert (!m_abbrev_table.empty ());
25045     ::file_write (file_names, m_bucket_table);
25046     ::file_write (file_names, m_hash_table);
25047     m_name_table_string_offs.file_write (file_names);
25048     m_name_table_entry_offs.file_write (file_names);
25049     m_abbrev_table.file_write (file_names);
25050     m_entry_pool.file_write (file_names);
25051     m_debugstrlookup.file_write (file_str);
25052   }
25053
25054 private:
25055
25056   /* Storage for symbol names mapping them to their .debug_str section
25057      offsets.  */
25058   class debug_str_lookup
25059   {
25060   public:
25061
25062     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
25063        All .debug_str section strings are automatically stored.  */
25064     debug_str_lookup ()
25065       : m_abfd (dwarf2_per_objfile->objfile->obfd)
25066     {
25067       dwarf2_read_section (dwarf2_per_objfile->objfile,
25068                            &dwarf2_per_objfile->str);
25069       if (dwarf2_per_objfile->str.buffer == NULL)
25070         return;
25071       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
25072            data < (dwarf2_per_objfile->str.buffer
25073                    + dwarf2_per_objfile->str.size);)
25074         {
25075           const char *const s = reinterpret_cast<const char *> (data);
25076           const auto insertpair
25077             = m_str_table.emplace (c_str_view (s),
25078                                    data - dwarf2_per_objfile->str.buffer);
25079           if (!insertpair.second)
25080             complaint (&symfile_complaints,
25081                        _("Duplicate string \"%s\" in "
25082                          ".debug_str section [in module %s]"),
25083                        s, bfd_get_filename (m_abfd));
25084           data += strlen (s) + 1;
25085         }
25086     }
25087
25088     /* Return offset of symbol name S in the .debug_str section.  Add
25089        such symbol to the section's end if it does not exist there
25090        yet.  */
25091     size_t lookup (const char *s)
25092     {
25093       const auto it = m_str_table.find (c_str_view (s));
25094       if (it != m_str_table.end ())
25095         return it->second;
25096       const size_t offset = (dwarf2_per_objfile->str.size
25097                              + m_str_add_buf.size ());
25098       m_str_table.emplace (c_str_view (s), offset);
25099       m_str_add_buf.append_cstr0 (s);
25100       return offset;
25101     }
25102
25103     /* Append the end of the .debug_str section to FILE.  */
25104     void file_write (FILE *file) const
25105     {
25106       m_str_add_buf.file_write (file);
25107     }
25108
25109   private:
25110     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
25111     bfd *const m_abfd;
25112
25113     /* Data to add at the end of .debug_str for new needed symbol names.  */
25114     data_buf m_str_add_buf;
25115   };
25116
25117   /* Container to map used DWARF tags to their .debug_names abbreviation
25118      tags.  */
25119   class index_key
25120   {
25121   public:
25122     index_key (int dwarf_tag_, bool is_static_)
25123       : dwarf_tag (dwarf_tag_), is_static (is_static_)
25124     {
25125     }
25126
25127     bool
25128     operator== (const index_key &other) const
25129     {
25130       return dwarf_tag == other.dwarf_tag && is_static == other.is_static;
25131     }
25132
25133     const int dwarf_tag;
25134     const bool is_static;
25135   };
25136
25137   /* Provide std::unordered_map::hasher for index_key.  */
25138   class index_key_hasher
25139   {
25140   public:
25141     size_t
25142     operator () (const index_key &key) const
25143     {
25144       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
25145     }
25146   };
25147
25148   /* Parameters of one symbol entry.  */
25149   class symbol_value
25150   {
25151   public:
25152     const int dwarf_tag, cu_index;
25153     const bool is_static;
25154
25155     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_)
25156       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_)
25157     {}
25158
25159     bool
25160     operator< (const symbol_value &other) const
25161     {
25162 #define X(n) \
25163   do \
25164     { \
25165       if (n < other.n) \
25166         return true; \
25167       if (n > other.n) \
25168         return false; \
25169     } \
25170   while (0)
25171       X (dwarf_tag);
25172       X (is_static);
25173       X (cu_index);
25174 #undef X
25175       return false;
25176     }
25177   };
25178
25179   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
25180      output.  */
25181   class offset_vec
25182   {
25183   protected:
25184     const bfd_endian dwarf5_byte_order;
25185   public:
25186     explicit offset_vec (bfd_endian dwarf5_byte_order_)
25187       : dwarf5_byte_order (dwarf5_byte_order_)
25188     {}
25189
25190     /* Call std::vector::reserve for NELEM elements.  */
25191     virtual void reserve (size_t nelem) = 0;
25192
25193     /* Call std::vector::push_back with store_unsigned_integer byte
25194        reordering for ELEM.  */
25195     virtual void push_back_reorder (size_t elem) = 0;
25196
25197     /* Return expected output size in bytes.  */
25198     virtual size_t bytes () const = 0;
25199
25200     /* Write name table to FILE.  */
25201     virtual void file_write (FILE *file) const = 0;
25202   };
25203
25204   /* Template to unify DWARF-32 and DWARF-64 output.  */
25205   template<typename OffsetSize>
25206   class offset_vec_tmpl : public offset_vec
25207   {
25208   public:
25209     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
25210       : offset_vec (dwarf5_byte_order_)
25211     {}
25212
25213     /* Implement offset_vec::reserve.  */
25214     void reserve (size_t nelem) override
25215     {
25216       m_vec.reserve (nelem);
25217     }
25218
25219     /* Implement offset_vec::push_back_reorder.  */
25220     void push_back_reorder (size_t elem) override
25221     {
25222       m_vec.push_back (elem);
25223       /* Check for overflow.  */
25224       gdb_assert (m_vec.back () == elem);
25225       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
25226                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
25227     }
25228
25229     /* Implement offset_vec::bytes.  */
25230     size_t bytes () const override
25231     {
25232       return m_vec.size () * sizeof (m_vec[0]);
25233     }
25234
25235     /* Implement offset_vec::file_write.  */
25236     void file_write (FILE *file) const override
25237     {
25238       ::file_write (file, m_vec);
25239     }
25240
25241   private:
25242     std::vector<OffsetSize> m_vec;
25243   };
25244
25245   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
25246      respecting name table width.  */
25247   class dwarf
25248   {
25249   public:
25250     offset_vec &name_table_string_offs, &name_table_entry_offs;
25251
25252     dwarf (offset_vec &name_table_string_offs_,
25253            offset_vec &name_table_entry_offs_)
25254       : name_table_string_offs (name_table_string_offs_),
25255         name_table_entry_offs (name_table_entry_offs_)
25256     {
25257     }
25258   };
25259
25260   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
25261      respecting name table width.  */
25262   template<typename OffsetSize>
25263   class dwarf_tmpl : public dwarf
25264   {
25265   public:
25266     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
25267       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
25268         m_name_table_string_offs (dwarf5_byte_order_),
25269         m_name_table_entry_offs (dwarf5_byte_order_)
25270     {}
25271
25272   private:
25273     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
25274     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
25275   };
25276
25277   /* Try to reconstruct original DWARF tag for given partial_symbol.
25278      This function is not DWARF-5 compliant but it is sufficient for
25279      GDB as a DWARF-5 index consumer.  */
25280   static int psymbol_tag (const struct partial_symbol *psym)
25281   {
25282     domain_enum domain = PSYMBOL_DOMAIN (psym);
25283     enum address_class aclass = PSYMBOL_CLASS (psym);
25284
25285     switch (domain)
25286       {
25287       case VAR_DOMAIN:
25288         switch (aclass)
25289           {
25290           case LOC_BLOCK:
25291             return DW_TAG_subprogram;
25292           case LOC_TYPEDEF:
25293             return DW_TAG_typedef;
25294           case LOC_COMPUTED:
25295           case LOC_CONST_BYTES:
25296           case LOC_OPTIMIZED_OUT:
25297           case LOC_STATIC:
25298             return DW_TAG_variable;
25299           case LOC_CONST:
25300             /* Note: It's currently impossible to recognize psyms as enum values
25301                short of reading the type info.  For now punt.  */
25302             return DW_TAG_variable;
25303           default:
25304             /* There are other LOC_FOO values that one might want to classify
25305                as variables, but dwarf2read.c doesn't currently use them.  */
25306             return DW_TAG_variable;
25307           }
25308       case STRUCT_DOMAIN:
25309         return DW_TAG_structure_type;
25310       default:
25311         return 0;
25312       }
25313   }
25314
25315   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
25316   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
25317                        struct partial_symbol **psymp, int count, int cu_index,
25318                        bool is_static)
25319   {
25320     for (; count-- > 0; ++psymp)
25321       {
25322         struct partial_symbol *psym = *psymp;
25323
25324         if (SYMBOL_LANGUAGE (psym) == language_ada)
25325           error (_("Ada is not currently supported by the index"));
25326
25327         /* Only add a given psymbol once.  */
25328         if (psyms_seen.insert (psym).second)
25329           insert (psym, cu_index, is_static);
25330       }
25331   }
25332
25333   /* Store value of each symbol.  */
25334   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
25335     m_name_to_value_set;
25336
25337   /* Tables of DWARF-5 .debug_names.  They are in object file byte
25338      order.  */
25339   std::vector<uint32_t> m_bucket_table;
25340   std::vector<uint32_t> m_hash_table;
25341
25342   const bfd_endian m_dwarf5_byte_order;
25343   dwarf_tmpl<uint32_t> m_dwarf32;
25344   dwarf_tmpl<uint64_t> m_dwarf64;
25345   dwarf &m_dwarf;
25346   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
25347   debug_str_lookup m_debugstrlookup;
25348
25349   /* Map each used .debug_names abbreviation tag parameter to its
25350      index value.  */
25351   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
25352
25353   /* Next unused .debug_names abbreviation tag for
25354      m_indexkey_to_idx.  */
25355   int m_idx_next = 1;
25356
25357   /* .debug_names abbreviation table.  */
25358   data_buf m_abbrev_table;
25359
25360   /* .debug_names entry pool.  */
25361   data_buf m_entry_pool;
25362 };
25363
25364 /* Return iff any of the needed offsets does not fit into 32-bit
25365    .debug_names section.  */
25366
25367 static bool
25368 check_dwarf64_offsets ()
25369 {
25370   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25371     {
25372       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
25373
25374       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
25375         return true;
25376     }
25377   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
25378     {
25379       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
25380       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
25381
25382       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
25383         return true;
25384     }
25385   return false;
25386 }
25387
25388 /* The psyms_seen set is potentially going to be largish (~40k
25389    elements when indexing a -g3 build of GDB itself).  Estimate the
25390    number of elements in order to avoid too many rehashes, which
25391    require rebuilding buckets and thus many trips to
25392    malloc/free.  */
25393
25394 static size_t
25395 psyms_seen_size ()
25396 {
25397   size_t psyms_count = 0;
25398   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25399     {
25400       struct dwarf2_per_cu_data *per_cu
25401         = dwarf2_per_objfile->all_comp_units[i];
25402       struct partial_symtab *psymtab = per_cu->v.psymtab;
25403
25404       if (psymtab != NULL && psymtab->user == NULL)
25405         recursively_count_psymbols (psymtab, psyms_count);
25406     }
25407   /* Generating an index for gdb itself shows a ratio of
25408      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
25409   return psyms_count / 4;
25410 }
25411
25412 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
25413    Return how many bytes were expected to be written into OUT_FILE.  */
25414
25415 static size_t
25416 write_gdbindex (struct objfile *objfile, FILE *out_file)
25417 {
25418   mapped_symtab symtab;
25419   data_buf cu_list;
25420
25421   /* While we're scanning CU's create a table that maps a psymtab pointer
25422      (which is what addrmap records) to its index (which is what is recorded
25423      in the index file).  This will later be needed to write the address
25424      table.  */
25425   psym_index_map cu_index_htab;
25426   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
25427
25428   /* The CU list is already sorted, so we don't need to do additional
25429      work here.  Also, the debug_types entries do not appear in
25430      all_comp_units, but only in their own hash table.  */
25431
25432   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
25433   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25434     {
25435       struct dwarf2_per_cu_data *per_cu
25436         = dwarf2_per_objfile->all_comp_units[i];
25437       struct partial_symtab *psymtab = per_cu->v.psymtab;
25438
25439       /* CU of a shared file from 'dwz -m' may be unused by this main file.
25440          It may be referenced from a local scope but in such case it does not
25441          need to be present in .gdb_index.  */
25442       if (psymtab == NULL)
25443         continue;
25444
25445       if (psymtab->user == NULL)
25446         recursively_write_psymbols (objfile, psymtab, &symtab,
25447                                     psyms_seen, i);
25448
25449       const auto insertpair = cu_index_htab.emplace (psymtab, i);
25450       gdb_assert (insertpair.second);
25451
25452       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
25453                            to_underlying (per_cu->sect_off));
25454       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
25455     }
25456
25457   /* Dump the address map.  */
25458   data_buf addr_vec;
25459   write_address_map (objfile, addr_vec, cu_index_htab);
25460
25461   /* Write out the .debug_type entries, if any.  */
25462   data_buf types_cu_list;
25463   if (dwarf2_per_objfile->signatured_types)
25464     {
25465       signatured_type_index_data sig_data (types_cu_list,
25466                                            psyms_seen);
25467
25468       sig_data.objfile = objfile;
25469       sig_data.symtab = &symtab;
25470       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
25471       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
25472                               write_one_signatured_type, &sig_data);
25473     }
25474
25475   /* Now that we've processed all symbols we can shrink their cu_indices
25476      lists.  */
25477   uniquify_cu_indices (&symtab);
25478
25479   data_buf symtab_vec, constant_pool;
25480   write_hash_table (&symtab, symtab_vec, constant_pool);
25481
25482   data_buf contents;
25483   const offset_type size_of_contents = 6 * sizeof (offset_type);
25484   offset_type total_len = size_of_contents;
25485
25486   /* The version number.  */
25487   contents.append_data (MAYBE_SWAP (8));
25488
25489   /* The offset of the CU list from the start of the file.  */
25490   contents.append_data (MAYBE_SWAP (total_len));
25491   total_len += cu_list.size ();
25492
25493   /* The offset of the types CU list from the start of the file.  */
25494   contents.append_data (MAYBE_SWAP (total_len));
25495   total_len += types_cu_list.size ();
25496
25497   /* The offset of the address table from the start of the file.  */
25498   contents.append_data (MAYBE_SWAP (total_len));
25499   total_len += addr_vec.size ();
25500
25501   /* The offset of the symbol table from the start of the file.  */
25502   contents.append_data (MAYBE_SWAP (total_len));
25503   total_len += symtab_vec.size ();
25504
25505   /* The offset of the constant pool from the start of the file.  */
25506   contents.append_data (MAYBE_SWAP (total_len));
25507   total_len += constant_pool.size ();
25508
25509   gdb_assert (contents.size () == size_of_contents);
25510
25511   contents.file_write (out_file);
25512   cu_list.file_write (out_file);
25513   types_cu_list.file_write (out_file);
25514   addr_vec.file_write (out_file);
25515   symtab_vec.file_write (out_file);
25516   constant_pool.file_write (out_file);
25517
25518   return total_len;
25519 }
25520
25521 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
25522 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
25523
25524 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
25525    needed addition to .debug_str section to OUT_FILE_STR.  Return how
25526    many bytes were expected to be written into OUT_FILE.  */
25527
25528 static size_t
25529 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
25530 {
25531   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
25532   const int dwarf5_offset_size = dwarf5_is_dwarf64 ? 8 : 4;
25533   const enum bfd_endian dwarf5_byte_order
25534     = gdbarch_byte_order (get_objfile_arch (objfile));
25535
25536   /* The CU list is already sorted, so we don't need to do additional
25537      work here.  Also, the debug_types entries do not appear in
25538      all_comp_units, but only in their own hash table.  */
25539   data_buf cu_list;
25540   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
25541   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
25542   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25543     {
25544       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
25545       partial_symtab *psymtab = per_cu->v.psymtab;
25546
25547       /* CU of a shared file from 'dwz -m' may be unused by this main
25548          file.  It may be referenced from a local scope but in such
25549          case it does not need to be present in .debug_names.  */
25550       if (psymtab == NULL)
25551         continue;
25552
25553       if (psymtab->user == NULL)
25554         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
25555
25556       cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
25557                            to_underlying (per_cu->sect_off));
25558     }
25559   nametable.build ();
25560
25561   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
25562
25563   data_buf types_cu_list;
25564   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
25565     {
25566       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
25567       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
25568
25569       types_cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
25570                                  to_underlying (per_cu.sect_off));
25571     }
25572
25573   const offset_type bytes_of_header
25574     = ((dwarf5_is_dwarf64 ? 12 : 4)
25575        + 2 + 2 + 7 * 4
25576        + sizeof (dwarf5_gdb_augmentation));
25577   size_t expected_bytes = 0;
25578   expected_bytes += bytes_of_header;
25579   expected_bytes += cu_list.size ();
25580   expected_bytes += types_cu_list.size ();
25581   expected_bytes += nametable.bytes ();
25582   data_buf header;
25583
25584   if (!dwarf5_is_dwarf64)
25585     {
25586       const uint64_t size64 = expected_bytes - 4;
25587       gdb_assert (size64 < 0xfffffff0);
25588       header.append_uint (4, dwarf5_byte_order, size64);
25589     }
25590   else
25591     {
25592       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
25593       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
25594     }
25595
25596   /* The version number.  */
25597   header.append_uint (2, dwarf5_byte_order, 5);
25598
25599   /* Padding.  */
25600   header.append_uint (2, dwarf5_byte_order, 0);
25601
25602   /* comp_unit_count - The number of CUs in the CU list.  */
25603   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
25604
25605   /* local_type_unit_count - The number of TUs in the local TU
25606      list.  */
25607   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
25608
25609   /* foreign_type_unit_count - The number of TUs in the foreign TU
25610      list.  */
25611   header.append_uint (4, dwarf5_byte_order, 0);
25612
25613   /* bucket_count - The number of hash buckets in the hash lookup
25614      table.  */
25615   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
25616
25617   /* name_count - The number of unique names in the index.  */
25618   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
25619
25620   /* abbrev_table_size - The size in bytes of the abbreviations
25621      table.  */
25622   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
25623
25624   /* augmentation_string_size - The size in bytes of the augmentation
25625      string.  This value is rounded up to a multiple of 4.  */
25626   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
25627   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
25628   header.append_data (dwarf5_gdb_augmentation);
25629
25630   gdb_assert (header.size () == bytes_of_header);
25631
25632   header.file_write (out_file);
25633   cu_list.file_write (out_file);
25634   types_cu_list.file_write (out_file);
25635   nametable.file_write (out_file, out_file_str);
25636
25637   return expected_bytes;
25638 }
25639
25640 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
25641    position is at the end of the file.  */
25642
25643 static void
25644 assert_file_size (FILE *file, const char *filename, size_t expected_size)
25645 {
25646   const auto file_size = ftell (file);
25647   if (file_size == -1)
25648     error (_("Can't get `%s' size"), filename);
25649   gdb_assert (file_size == expected_size);
25650 }
25651
25652 /* An index variant.  */
25653 enum dw_index_kind
25654 {
25655   /* GDB's own .gdb_index format.   */
25656   GDB_INDEX,
25657
25658   /* DWARF5 .debug_names.  */
25659   DEBUG_NAMES,
25660 };
25661
25662 /* Create an index file for OBJFILE in the directory DIR.  */
25663
25664 static void
25665 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
25666                          dw_index_kind index_kind)
25667 {
25668   if (dwarf2_per_objfile->using_index)
25669     error (_("Cannot use an index to create the index"));
25670
25671   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
25672     error (_("Cannot make an index when the file has multiple .debug_types sections"));
25673
25674   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
25675     return;
25676
25677   struct stat st;
25678   if (stat (objfile_name (objfile), &st) < 0)
25679     perror_with_name (objfile_name (objfile));
25680
25681   std::string filename (std::string (dir) + SLASH_STRING
25682                         + lbasename (objfile_name (objfile))
25683                         + (index_kind == dw_index_kind::DEBUG_NAMES
25684                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
25685
25686   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
25687   if (!out_file)
25688     error (_("Can't open `%s' for writing"), filename.c_str ());
25689
25690   /* Order matters here; we want FILE to be closed before FILENAME is
25691      unlinked, because on MS-Windows one cannot delete a file that is
25692      still open.  (Don't call anything here that might throw until
25693      file_closer is created.)  */
25694   gdb::unlinker unlink_file (filename.c_str ());
25695   gdb_file_up close_out_file (out_file);
25696
25697   if (index_kind == dw_index_kind::DEBUG_NAMES)
25698     {
25699       std::string filename_str (std::string (dir) + SLASH_STRING
25700                                 + lbasename (objfile_name (objfile))
25701                                 + DEBUG_STR_SUFFIX);
25702       FILE *out_file_str
25703         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
25704       if (!out_file_str)
25705         error (_("Can't open `%s' for writing"), filename_str.c_str ());
25706       gdb::unlinker unlink_file_str (filename_str.c_str ());
25707       gdb_file_up close_out_file_str (out_file_str);
25708
25709       const size_t total_len
25710         = write_debug_names (objfile, out_file, out_file_str);
25711       assert_file_size (out_file, filename.c_str (), total_len);
25712
25713       /* We want to keep the file .debug_str file too.  */
25714       unlink_file_str.keep ();
25715     }
25716   else
25717     {
25718       const size_t total_len
25719         = write_gdbindex (objfile, out_file);
25720       assert_file_size (out_file, filename.c_str (), total_len);
25721     }
25722
25723   /* We want to keep the file.  */
25724   unlink_file.keep ();
25725 }
25726
25727 /* Implementation of the `save gdb-index' command.
25728    
25729    Note that the .gdb_index file format used by this command is
25730    documented in the GDB manual.  Any changes here must be documented
25731    there.  */
25732
25733 static void
25734 save_gdb_index_command (const char *arg, int from_tty)
25735 {
25736   struct objfile *objfile;
25737   const char dwarf5space[] = "-dwarf-5 ";
25738   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
25739
25740   if (!arg)
25741     arg = "";
25742
25743   arg = skip_spaces (arg);
25744   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
25745     {
25746       index_kind = dw_index_kind::DEBUG_NAMES;
25747       arg += strlen (dwarf5space);
25748       arg = skip_spaces (arg);
25749     }
25750
25751   if (!*arg)
25752     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
25753
25754   ALL_OBJFILES (objfile)
25755   {
25756     struct stat st;
25757
25758     /* If the objfile does not correspond to an actual file, skip it.  */
25759     if (stat (objfile_name (objfile), &st) < 0)
25760       continue;
25761
25762     dwarf2_per_objfile
25763       = (struct dwarf2_per_objfile *) objfile_data (objfile,
25764                                                     dwarf2_objfile_data_key);
25765     if (dwarf2_per_objfile)
25766       {
25767
25768         TRY
25769           {
25770             write_psymtabs_to_index (objfile, arg, index_kind);
25771           }
25772         CATCH (except, RETURN_MASK_ERROR)
25773           {
25774             exception_fprintf (gdb_stderr, except,
25775                                _("Error while writing index for `%s': "),
25776                                objfile_name (objfile));
25777           }
25778         END_CATCH
25779       }
25780   }
25781 }
25782
25783 \f
25784
25785 int dwarf_always_disassemble;
25786
25787 static void
25788 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25789                                struct cmd_list_element *c, const char *value)
25790 {
25791   fprintf_filtered (file,
25792                     _("Whether to always disassemble "
25793                       "DWARF expressions is %s.\n"),
25794                     value);
25795 }
25796
25797 static void
25798 show_check_physname (struct ui_file *file, int from_tty,
25799                      struct cmd_list_element *c, const char *value)
25800 {
25801   fprintf_filtered (file,
25802                     _("Whether to check \"physname\" is %s.\n"),
25803                     value);
25804 }
25805
25806 void
25807 _initialize_dwarf2_read (void)
25808 {
25809   struct cmd_list_element *c;
25810
25811   dwarf2_objfile_data_key
25812     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
25813
25814   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25815 Set DWARF specific variables.\n\
25816 Configure DWARF variables such as the cache size"),
25817                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25818                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25819
25820   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25821 Show DWARF specific variables\n\
25822 Show DWARF variables such as the cache size"),
25823                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25824                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25825
25826   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25827                             &dwarf_max_cache_age, _("\
25828 Set the upper bound on the age of cached DWARF compilation units."), _("\
25829 Show the upper bound on the age of cached DWARF compilation units."), _("\
25830 A higher limit means that cached compilation units will be stored\n\
25831 in memory longer, and more total memory will be used.  Zero disables\n\
25832 caching, which can slow down startup."),
25833                             NULL,
25834                             show_dwarf_max_cache_age,
25835                             &set_dwarf_cmdlist,
25836                             &show_dwarf_cmdlist);
25837
25838   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25839                            &dwarf_always_disassemble, _("\
25840 Set whether `info address' always disassembles DWARF expressions."), _("\
25841 Show whether `info address' always disassembles DWARF expressions."), _("\
25842 When enabled, DWARF expressions are always printed in an assembly-like\n\
25843 syntax.  When disabled, expressions will be printed in a more\n\
25844 conversational style, when possible."),
25845                            NULL,
25846                            show_dwarf_always_disassemble,
25847                            &set_dwarf_cmdlist,
25848                            &show_dwarf_cmdlist);
25849
25850   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25851 Set debugging of the DWARF reader."), _("\
25852 Show debugging of the DWARF reader."), _("\
25853 When enabled (non-zero), debugging messages are printed during DWARF\n\
25854 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25855 information.  A value greater than 1 provides more verbose information."),
25856                             NULL,
25857                             NULL,
25858                             &setdebuglist, &showdebuglist);
25859
25860   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25861 Set debugging of the DWARF DIE reader."), _("\
25862 Show debugging of the DWARF DIE reader."), _("\
25863 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25864 The value is the maximum depth to print."),
25865                              NULL,
25866                              NULL,
25867                              &setdebuglist, &showdebuglist);
25868
25869   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25870 Set debugging of the dwarf line reader."), _("\
25871 Show debugging of the dwarf line reader."), _("\
25872 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25873 A value of 1 (one) provides basic information.\n\
25874 A value greater than 1 provides more verbose information."),
25875                              NULL,
25876                              NULL,
25877                              &setdebuglist, &showdebuglist);
25878
25879   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25880 Set cross-checking of \"physname\" code against demangler."), _("\
25881 Show cross-checking of \"physname\" code against demangler."), _("\
25882 When enabled, GDB's internal \"physname\" code is checked against\n\
25883 the demangler."),
25884                            NULL, show_check_physname,
25885                            &setdebuglist, &showdebuglist);
25886
25887   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25888                            no_class, &use_deprecated_index_sections, _("\
25889 Set whether to use deprecated gdb_index sections."), _("\
25890 Show whether to use deprecated gdb_index sections."), _("\
25891 When enabled, deprecated .gdb_index sections are used anyway.\n\
25892 Normally they are ignored either because of a missing feature or\n\
25893 performance issue.\n\
25894 Warning: This option must be enabled before gdb reads the file."),
25895                            NULL,
25896                            NULL,
25897                            &setlist, &showlist);
25898
25899   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
25900                _("\
25901 Save a gdb-index file.\n\
25902 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
25903 \n\
25904 No options create one file with .gdb-index extension for pre-DWARF-5\n\
25905 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
25906 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
25907                &save_cmdlist);
25908   set_cmd_completer (c, filename_completer);
25909
25910   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25911                                                         &dwarf2_locexpr_funcs);
25912   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25913                                                         &dwarf2_loclist_funcs);
25914
25915   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25916                                         &dwarf2_block_frame_base_locexpr_funcs);
25917   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25918                                         &dwarf2_block_frame_base_loclist_funcs);
25919
25920 #if GDB_SELF_TEST
25921   selftests::register_test ("dw2_expand_symtabs_matching",
25922                             selftests::dw2_expand_symtabs_matching::run_test);
25923 #endif
25924 }