Refactor: Move some generic code out of .gdb_index code
[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 /* Return a new dwarf2_per_cu_data allocated on OBJFILE's
3065    objfile_obstack, and constructed with the specified field
3066    values.  */
3067
3068 static dwarf2_per_cu_data *
3069 create_cu_from_index_list (struct objfile *objfile,
3070                           struct dwarf2_section_info *section,
3071                           int is_dwz,
3072                           sect_offset sect_off, ULONGEST length)
3073 {
3074   dwarf2_per_cu_data *the_cu
3075     = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3076                      struct dwarf2_per_cu_data);
3077   the_cu->sect_off = sect_off;
3078   the_cu->length = length;
3079   the_cu->objfile = objfile;
3080   the_cu->section = section;
3081   the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3082                                    struct dwarf2_per_cu_quick_data);
3083   the_cu->is_dwz = is_dwz;
3084   return the_cu;
3085 }
3086
3087 /* A helper for create_cus_from_index that handles a given list of
3088    CUs.  */
3089
3090 static void
3091 create_cus_from_index_list (struct objfile *objfile,
3092                             const gdb_byte *cu_list, offset_type n_elements,
3093                             struct dwarf2_section_info *section,
3094                             int is_dwz,
3095                             int base_offset)
3096 {
3097   offset_type i;
3098
3099   for (i = 0; i < n_elements; i += 2)
3100     {
3101       gdb_static_assert (sizeof (ULONGEST) >= 8);
3102
3103       sect_offset sect_off
3104         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3105       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3106       cu_list += 2 * 8;
3107
3108       dwarf2_per_objfile->all_comp_units[base_offset + i / 2]
3109         = create_cu_from_index_list (objfile, section, is_dwz, sect_off, length);
3110     }
3111 }
3112
3113 /* Read the CU list from the mapped index, and use it to create all
3114    the CU objects for this objfile.  */
3115
3116 static void
3117 create_cus_from_index (struct objfile *objfile,
3118                        const gdb_byte *cu_list, offset_type cu_list_elements,
3119                        const gdb_byte *dwz_list, offset_type dwz_elements)
3120 {
3121   struct dwz_file *dwz;
3122
3123   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3124   dwarf2_per_objfile->all_comp_units =
3125     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3126                dwarf2_per_objfile->n_comp_units);
3127
3128   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3129                               &dwarf2_per_objfile->info, 0, 0);
3130
3131   if (dwz_elements == 0)
3132     return;
3133
3134   dwz = dwarf2_get_dwz_file ();
3135   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3136                               cu_list_elements / 2);
3137 }
3138
3139 /* Create the signatured type hash table from the index.  */
3140
3141 static void
3142 create_signatured_type_table_from_index (struct objfile *objfile,
3143                                          struct dwarf2_section_info *section,
3144                                          const gdb_byte *bytes,
3145                                          offset_type elements)
3146 {
3147   offset_type i;
3148   htab_t sig_types_hash;
3149
3150   dwarf2_per_objfile->n_type_units
3151     = dwarf2_per_objfile->n_allocated_type_units
3152     = elements / 3;
3153   dwarf2_per_objfile->all_type_units =
3154     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3155
3156   sig_types_hash = allocate_signatured_type_table (objfile);
3157
3158   for (i = 0; i < elements; i += 3)
3159     {
3160       struct signatured_type *sig_type;
3161       ULONGEST signature;
3162       void **slot;
3163       cu_offset type_offset_in_tu;
3164
3165       gdb_static_assert (sizeof (ULONGEST) >= 8);
3166       sect_offset sect_off
3167         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3168       type_offset_in_tu
3169         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3170                                                 BFD_ENDIAN_LITTLE);
3171       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3172       bytes += 3 * 8;
3173
3174       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3175                                  struct signatured_type);
3176       sig_type->signature = signature;
3177       sig_type->type_offset_in_tu = type_offset_in_tu;
3178       sig_type->per_cu.is_debug_types = 1;
3179       sig_type->per_cu.section = section;
3180       sig_type->per_cu.sect_off = sect_off;
3181       sig_type->per_cu.objfile = objfile;
3182       sig_type->per_cu.v.quick
3183         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3184                           struct dwarf2_per_cu_quick_data);
3185
3186       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3187       *slot = sig_type;
3188
3189       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3190     }
3191
3192   dwarf2_per_objfile->signatured_types = sig_types_hash;
3193 }
3194
3195 /* Read the address map data from the mapped index, and use it to
3196    populate the objfile's psymtabs_addrmap.  */
3197
3198 static void
3199 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3200 {
3201   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3202   const gdb_byte *iter, *end;
3203   struct addrmap *mutable_map;
3204   CORE_ADDR baseaddr;
3205
3206   auto_obstack temp_obstack;
3207
3208   mutable_map = addrmap_create_mutable (&temp_obstack);
3209
3210   iter = index->address_table;
3211   end = iter + index->address_table_size;
3212
3213   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3214
3215   while (iter < end)
3216     {
3217       ULONGEST hi, lo, cu_index;
3218       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3219       iter += 8;
3220       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3221       iter += 8;
3222       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3223       iter += 4;
3224
3225       if (lo > hi)
3226         {
3227           complaint (&symfile_complaints,
3228                      _(".gdb_index address table has invalid range (%s - %s)"),
3229                      hex_string (lo), hex_string (hi));
3230           continue;
3231         }
3232
3233       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3234         {
3235           complaint (&symfile_complaints,
3236                      _(".gdb_index address table has invalid CU number %u"),
3237                      (unsigned) cu_index);
3238           continue;
3239         }
3240
3241       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3242       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3243       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3244     }
3245
3246   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3247                                                     &objfile->objfile_obstack);
3248 }
3249
3250 /* The hash function for strings in the mapped index.  This is the same as
3251    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3252    implementation.  This is necessary because the hash function is tied to the
3253    format of the mapped index file.  The hash values do not have to match with
3254    SYMBOL_HASH_NEXT.
3255    
3256    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3257
3258 static hashval_t
3259 mapped_index_string_hash (int index_version, const void *p)
3260 {
3261   const unsigned char *str = (const unsigned char *) p;
3262   hashval_t r = 0;
3263   unsigned char c;
3264
3265   while ((c = *str++) != 0)
3266     {
3267       if (index_version >= 5)
3268         c = tolower (c);
3269       r = r * 67 + c - 113;
3270     }
3271
3272   return r;
3273 }
3274
3275 /* Find a slot in the mapped index INDEX for the object named NAME.
3276    If NAME is found, set *VEC_OUT to point to the CU vector in the
3277    constant pool and return true.  If NAME cannot be found, return
3278    false.  */
3279
3280 static bool
3281 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3282                           offset_type **vec_out)
3283 {
3284   offset_type hash;
3285   offset_type slot, step;
3286   int (*cmp) (const char *, const char *);
3287
3288   gdb::unique_xmalloc_ptr<char> without_params;
3289   if (current_language->la_language == language_cplus
3290       || current_language->la_language == language_fortran
3291       || current_language->la_language == language_d)
3292     {
3293       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3294          not contain any.  */
3295
3296       if (strchr (name, '(') != NULL)
3297         {
3298           without_params = cp_remove_params (name);
3299
3300           if (without_params != NULL)
3301             name = without_params.get ();
3302         }
3303     }
3304
3305   /* Index version 4 did not support case insensitive searches.  But the
3306      indices for case insensitive languages are built in lowercase, therefore
3307      simulate our NAME being searched is also lowercased.  */
3308   hash = mapped_index_string_hash ((index->version == 4
3309                                     && case_sensitivity == case_sensitive_off
3310                                     ? 5 : index->version),
3311                                    name);
3312
3313   slot = hash & (index->symbol_table_slots - 1);
3314   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3315   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3316
3317   for (;;)
3318     {
3319       /* Convert a slot number to an offset into the table.  */
3320       offset_type i = 2 * slot;
3321       const char *str;
3322       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3323         return false;
3324
3325       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3326       if (!cmp (name, str))
3327         {
3328           *vec_out = (offset_type *) (index->constant_pool
3329                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3330           return true;
3331         }
3332
3333       slot = (slot + step) & (index->symbol_table_slots - 1);
3334     }
3335 }
3336
3337 /* A helper function that reads the .gdb_index from SECTION and fills
3338    in MAP.  FILENAME is the name of the file containing the section;
3339    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3340    ok to use deprecated sections.
3341
3342    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3343    out parameters that are filled in with information about the CU and
3344    TU lists in the section.
3345
3346    Returns 1 if all went well, 0 otherwise.  */
3347
3348 static int
3349 read_index_from_section (struct objfile *objfile,
3350                          const char *filename,
3351                          int deprecated_ok,
3352                          struct dwarf2_section_info *section,
3353                          struct mapped_index *map,
3354                          const gdb_byte **cu_list,
3355                          offset_type *cu_list_elements,
3356                          const gdb_byte **types_list,
3357                          offset_type *types_list_elements)
3358 {
3359   const gdb_byte *addr;
3360   offset_type version;
3361   offset_type *metadata;
3362   int i;
3363
3364   if (dwarf2_section_empty_p (section))
3365     return 0;
3366
3367   /* Older elfutils strip versions could keep the section in the main
3368      executable while splitting it for the separate debug info file.  */
3369   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3370     return 0;
3371
3372   dwarf2_read_section (objfile, section);
3373
3374   addr = section->buffer;
3375   /* Version check.  */
3376   version = MAYBE_SWAP (*(offset_type *) addr);
3377   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3378      causes the index to behave very poorly for certain requests.  Version 3
3379      contained incomplete addrmap.  So, it seems better to just ignore such
3380      indices.  */
3381   if (version < 4)
3382     {
3383       static int warning_printed = 0;
3384       if (!warning_printed)
3385         {
3386           warning (_("Skipping obsolete .gdb_index section in %s."),
3387                    filename);
3388           warning_printed = 1;
3389         }
3390       return 0;
3391     }
3392   /* Index version 4 uses a different hash function than index version
3393      5 and later.
3394
3395      Versions earlier than 6 did not emit psymbols for inlined
3396      functions.  Using these files will cause GDB not to be able to
3397      set breakpoints on inlined functions by name, so we ignore these
3398      indices unless the user has done
3399      "set use-deprecated-index-sections on".  */
3400   if (version < 6 && !deprecated_ok)
3401     {
3402       static int warning_printed = 0;
3403       if (!warning_printed)
3404         {
3405           warning (_("\
3406 Skipping deprecated .gdb_index section in %s.\n\
3407 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3408 to use the section anyway."),
3409                    filename);
3410           warning_printed = 1;
3411         }
3412       return 0;
3413     }
3414   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3415      of the TU (for symbols coming from TUs),
3416      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3417      Plus gold-generated indices can have duplicate entries for global symbols,
3418      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3419      These are just performance bugs, and we can't distinguish gdb-generated
3420      indices from gold-generated ones, so issue no warning here.  */
3421
3422   /* Indexes with higher version than the one supported by GDB may be no
3423      longer backward compatible.  */
3424   if (version > 8)
3425     return 0;
3426
3427   map->version = version;
3428   map->total_size = section->size;
3429
3430   metadata = (offset_type *) (addr + sizeof (offset_type));
3431
3432   i = 0;
3433   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3434   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3435                        / 8);
3436   ++i;
3437
3438   *types_list = addr + MAYBE_SWAP (metadata[i]);
3439   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3440                            - MAYBE_SWAP (metadata[i]))
3441                           / 8);
3442   ++i;
3443
3444   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3445   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3446                              - MAYBE_SWAP (metadata[i]));
3447   ++i;
3448
3449   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3450   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3451                               - MAYBE_SWAP (metadata[i]))
3452                              / (2 * sizeof (offset_type)));
3453   ++i;
3454
3455   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3456
3457   return 1;
3458 }
3459
3460
3461 /* Read the index file.  If everything went ok, initialize the "quick"
3462    elements of all the CUs and return 1.  Otherwise, return 0.  */
3463
3464 static int
3465 dwarf2_read_index (struct objfile *objfile)
3466 {
3467   struct mapped_index local_map, *map;
3468   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3469   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3470   struct dwz_file *dwz;
3471
3472   if (!read_index_from_section (objfile, objfile_name (objfile),
3473                                 use_deprecated_index_sections,
3474                                 &dwarf2_per_objfile->gdb_index, &local_map,
3475                                 &cu_list, &cu_list_elements,
3476                                 &types_list, &types_list_elements))
3477     return 0;
3478
3479   /* Don't use the index if it's empty.  */
3480   if (local_map.symbol_table_slots == 0)
3481     return 0;
3482
3483   /* If there is a .dwz file, read it so we can get its CU list as
3484      well.  */
3485   dwz = dwarf2_get_dwz_file ();
3486   if (dwz != NULL)
3487     {
3488       struct mapped_index dwz_map;
3489       const gdb_byte *dwz_types_ignore;
3490       offset_type dwz_types_elements_ignore;
3491
3492       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3493                                     1,
3494                                     &dwz->gdb_index, &dwz_map,
3495                                     &dwz_list, &dwz_list_elements,
3496                                     &dwz_types_ignore,
3497                                     &dwz_types_elements_ignore))
3498         {
3499           warning (_("could not read '.gdb_index' section from %s; skipping"),
3500                    bfd_get_filename (dwz->dwz_bfd));
3501           return 0;
3502         }
3503     }
3504
3505   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3506                          dwz_list_elements);
3507
3508   if (types_list_elements)
3509     {
3510       struct dwarf2_section_info *section;
3511
3512       /* We can only handle a single .debug_types when we have an
3513          index.  */
3514       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3515         return 0;
3516
3517       section = VEC_index (dwarf2_section_info_def,
3518                            dwarf2_per_objfile->types, 0);
3519
3520       create_signatured_type_table_from_index (objfile, section, types_list,
3521                                                types_list_elements);
3522     }
3523
3524   create_addrmap_from_index (objfile, &local_map);
3525
3526   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3527   map = new (map) mapped_index ();
3528   *map = local_map;
3529
3530   dwarf2_per_objfile->index_table = map;
3531   dwarf2_per_objfile->using_index = 1;
3532   dwarf2_per_objfile->quick_file_names_table =
3533     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3534
3535   return 1;
3536 }
3537
3538 /* A helper for the "quick" functions which sets the global
3539    dwarf2_per_objfile according to OBJFILE.  */
3540
3541 static void
3542 dw2_setup (struct objfile *objfile)
3543 {
3544   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3545                         objfile_data (objfile, dwarf2_objfile_data_key));
3546   gdb_assert (dwarf2_per_objfile);
3547 }
3548
3549 /* die_reader_func for dw2_get_file_names.  */
3550
3551 static void
3552 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3553                            const gdb_byte *info_ptr,
3554                            struct die_info *comp_unit_die,
3555                            int has_children,
3556                            void *data)
3557 {
3558   struct dwarf2_cu *cu = reader->cu;
3559   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3560   struct objfile *objfile = dwarf2_per_objfile->objfile;
3561   struct dwarf2_per_cu_data *lh_cu;
3562   struct attribute *attr;
3563   int i;
3564   void **slot;
3565   struct quick_file_names *qfn;
3566
3567   gdb_assert (! this_cu->is_debug_types);
3568
3569   /* Our callers never want to match partial units -- instead they
3570      will match the enclosing full CU.  */
3571   if (comp_unit_die->tag == DW_TAG_partial_unit)
3572     {
3573       this_cu->v.quick->no_file_data = 1;
3574       return;
3575     }
3576
3577   lh_cu = this_cu;
3578   slot = NULL;
3579
3580   line_header_up lh;
3581   sect_offset line_offset {};
3582
3583   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3584   if (attr)
3585     {
3586       struct quick_file_names find_entry;
3587
3588       line_offset = (sect_offset) DW_UNSND (attr);
3589
3590       /* We may have already read in this line header (TU line header sharing).
3591          If we have we're done.  */
3592       find_entry.hash.dwo_unit = cu->dwo_unit;
3593       find_entry.hash.line_sect_off = line_offset;
3594       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3595                              &find_entry, INSERT);
3596       if (*slot != NULL)
3597         {
3598           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3599           return;
3600         }
3601
3602       lh = dwarf_decode_line_header (line_offset, cu);
3603     }
3604   if (lh == NULL)
3605     {
3606       lh_cu->v.quick->no_file_data = 1;
3607       return;
3608     }
3609
3610   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3611   qfn->hash.dwo_unit = cu->dwo_unit;
3612   qfn->hash.line_sect_off = line_offset;
3613   gdb_assert (slot != NULL);
3614   *slot = qfn;
3615
3616   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3617
3618   qfn->num_file_names = lh->file_names.size ();
3619   qfn->file_names =
3620     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3621   for (i = 0; i < lh->file_names.size (); ++i)
3622     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3623   qfn->real_names = NULL;
3624
3625   lh_cu->v.quick->file_names = qfn;
3626 }
3627
3628 /* A helper for the "quick" functions which attempts to read the line
3629    table for THIS_CU.  */
3630
3631 static struct quick_file_names *
3632 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3633 {
3634   /* This should never be called for TUs.  */
3635   gdb_assert (! this_cu->is_debug_types);
3636   /* Nor type unit groups.  */
3637   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3638
3639   if (this_cu->v.quick->file_names != NULL)
3640     return this_cu->v.quick->file_names;
3641   /* If we know there is no line data, no point in looking again.  */
3642   if (this_cu->v.quick->no_file_data)
3643     return NULL;
3644
3645   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3646
3647   if (this_cu->v.quick->no_file_data)
3648     return NULL;
3649   return this_cu->v.quick->file_names;
3650 }
3651
3652 /* A helper for the "quick" functions which computes and caches the
3653    real path for a given file name from the line table.  */
3654
3655 static const char *
3656 dw2_get_real_path (struct objfile *objfile,
3657                    struct quick_file_names *qfn, int index)
3658 {
3659   if (qfn->real_names == NULL)
3660     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3661                                       qfn->num_file_names, const char *);
3662
3663   if (qfn->real_names[index] == NULL)
3664     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3665
3666   return qfn->real_names[index];
3667 }
3668
3669 static struct symtab *
3670 dw2_find_last_source_symtab (struct objfile *objfile)
3671 {
3672   struct compunit_symtab *cust;
3673   int index;
3674
3675   dw2_setup (objfile);
3676   index = dwarf2_per_objfile->n_comp_units - 1;
3677   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3678   if (cust == NULL)
3679     return NULL;
3680   return compunit_primary_filetab (cust);
3681 }
3682
3683 /* Traversal function for dw2_forget_cached_source_info.  */
3684
3685 static int
3686 dw2_free_cached_file_names (void **slot, void *info)
3687 {
3688   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3689
3690   if (file_data->real_names)
3691     {
3692       int i;
3693
3694       for (i = 0; i < file_data->num_file_names; ++i)
3695         {
3696           xfree ((void*) file_data->real_names[i]);
3697           file_data->real_names[i] = NULL;
3698         }
3699     }
3700
3701   return 1;
3702 }
3703
3704 static void
3705 dw2_forget_cached_source_info (struct objfile *objfile)
3706 {
3707   dw2_setup (objfile);
3708
3709   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3710                           dw2_free_cached_file_names, NULL);
3711 }
3712
3713 /* Helper function for dw2_map_symtabs_matching_filename that expands
3714    the symtabs and calls the iterator.  */
3715
3716 static int
3717 dw2_map_expand_apply (struct objfile *objfile,
3718                       struct dwarf2_per_cu_data *per_cu,
3719                       const char *name, const char *real_path,
3720                       gdb::function_view<bool (symtab *)> callback)
3721 {
3722   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3723
3724   /* Don't visit already-expanded CUs.  */
3725   if (per_cu->v.quick->compunit_symtab)
3726     return 0;
3727
3728   /* This may expand more than one symtab, and we want to iterate over
3729      all of them.  */
3730   dw2_instantiate_symtab (per_cu);
3731
3732   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3733                                     last_made, callback);
3734 }
3735
3736 /* Implementation of the map_symtabs_matching_filename method.  */
3737
3738 static bool
3739 dw2_map_symtabs_matching_filename
3740   (struct objfile *objfile, const char *name, const char *real_path,
3741    gdb::function_view<bool (symtab *)> callback)
3742 {
3743   int i;
3744   const char *name_basename = lbasename (name);
3745
3746   dw2_setup (objfile);
3747
3748   /* The rule is CUs specify all the files, including those used by
3749      any TU, so there's no need to scan TUs here.  */
3750
3751   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3752     {
3753       int j;
3754       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3755       struct quick_file_names *file_data;
3756
3757       /* We only need to look at symtabs not already expanded.  */
3758       if (per_cu->v.quick->compunit_symtab)
3759         continue;
3760
3761       file_data = dw2_get_file_names (per_cu);
3762       if (file_data == NULL)
3763         continue;
3764
3765       for (j = 0; j < file_data->num_file_names; ++j)
3766         {
3767           const char *this_name = file_data->file_names[j];
3768           const char *this_real_name;
3769
3770           if (compare_filenames_for_search (this_name, name))
3771             {
3772               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3773                                         callback))
3774                 return true;
3775               continue;
3776             }
3777
3778           /* Before we invoke realpath, which can get expensive when many
3779              files are involved, do a quick comparison of the basenames.  */
3780           if (! basenames_may_differ
3781               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3782             continue;
3783
3784           this_real_name = dw2_get_real_path (objfile, file_data, j);
3785           if (compare_filenames_for_search (this_real_name, name))
3786             {
3787               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3788                                         callback))
3789                 return true;
3790               continue;
3791             }
3792
3793           if (real_path != NULL)
3794             {
3795               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3796               gdb_assert (IS_ABSOLUTE_PATH (name));
3797               if (this_real_name != NULL
3798                   && FILENAME_CMP (real_path, this_real_name) == 0)
3799                 {
3800                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3801                                             callback))
3802                     return true;
3803                   continue;
3804                 }
3805             }
3806         }
3807     }
3808
3809   return false;
3810 }
3811
3812 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3813
3814 struct dw2_symtab_iterator
3815 {
3816   /* The internalized form of .gdb_index.  */
3817   struct mapped_index *index;
3818   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3819   int want_specific_block;
3820   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3821      Unused if !WANT_SPECIFIC_BLOCK.  */
3822   int block_index;
3823   /* The kind of symbol we're looking for.  */
3824   domain_enum domain;
3825   /* The list of CUs from the index entry of the symbol,
3826      or NULL if not found.  */
3827   offset_type *vec;
3828   /* The next element in VEC to look at.  */
3829   int next;
3830   /* The number of elements in VEC, or zero if there is no match.  */
3831   int length;
3832   /* Have we seen a global version of the symbol?
3833      If so we can ignore all further global instances.
3834      This is to work around gold/15646, inefficient gold-generated
3835      indices.  */
3836   int global_seen;
3837 };
3838
3839 /* Initialize the index symtab iterator ITER.
3840    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3841    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3842
3843 static void
3844 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3845                       struct mapped_index *index,
3846                       int want_specific_block,
3847                       int block_index,
3848                       domain_enum domain,
3849                       const char *name)
3850 {
3851   iter->index = index;
3852   iter->want_specific_block = want_specific_block;
3853   iter->block_index = block_index;
3854   iter->domain = domain;
3855   iter->next = 0;
3856   iter->global_seen = 0;
3857
3858   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3859     iter->length = MAYBE_SWAP (*iter->vec);
3860   else
3861     {
3862       iter->vec = NULL;
3863       iter->length = 0;
3864     }
3865 }
3866
3867 /* Return the next matching CU or NULL if there are no more.  */
3868
3869 static struct dwarf2_per_cu_data *
3870 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3871 {
3872   for ( ; iter->next < iter->length; ++iter->next)
3873     {
3874       offset_type cu_index_and_attrs =
3875         MAYBE_SWAP (iter->vec[iter->next + 1]);
3876       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3877       struct dwarf2_per_cu_data *per_cu;
3878       int want_static = iter->block_index != GLOBAL_BLOCK;
3879       /* This value is only valid for index versions >= 7.  */
3880       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3881       gdb_index_symbol_kind symbol_kind =
3882         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3883       /* Only check the symbol attributes if they're present.
3884          Indices prior to version 7 don't record them,
3885          and indices >= 7 may elide them for certain symbols
3886          (gold does this).  */
3887       int attrs_valid =
3888         (iter->index->version >= 7
3889          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3890
3891       /* Don't crash on bad data.  */
3892       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3893                        + dwarf2_per_objfile->n_type_units))
3894         {
3895           complaint (&symfile_complaints,
3896                      _(".gdb_index entry has bad CU index"
3897                        " [in module %s]"),
3898                      objfile_name (dwarf2_per_objfile->objfile));
3899           continue;
3900         }
3901
3902       per_cu = dw2_get_cutu (cu_index);
3903
3904       /* Skip if already read in.  */
3905       if (per_cu->v.quick->compunit_symtab)
3906         continue;
3907
3908       /* Check static vs global.  */
3909       if (attrs_valid)
3910         {
3911           if (iter->want_specific_block
3912               && want_static != is_static)
3913             continue;
3914           /* Work around gold/15646.  */
3915           if (!is_static && iter->global_seen)
3916             continue;
3917           if (!is_static)
3918             iter->global_seen = 1;
3919         }
3920
3921       /* Only check the symbol's kind if it has one.  */
3922       if (attrs_valid)
3923         {
3924           switch (iter->domain)
3925             {
3926             case VAR_DOMAIN:
3927               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3928                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3929                   /* Some types are also in VAR_DOMAIN.  */
3930                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3931                 continue;
3932               break;
3933             case STRUCT_DOMAIN:
3934               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3935                 continue;
3936               break;
3937             case LABEL_DOMAIN:
3938               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3939                 continue;
3940               break;
3941             default:
3942               break;
3943             }
3944         }
3945
3946       ++iter->next;
3947       return per_cu;
3948     }
3949
3950   return NULL;
3951 }
3952
3953 static struct compunit_symtab *
3954 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3955                    const char *name, domain_enum domain)
3956 {
3957   struct compunit_symtab *stab_best = NULL;
3958   struct mapped_index *index;
3959
3960   dw2_setup (objfile);
3961
3962   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3963
3964   index = dwarf2_per_objfile->index_table;
3965
3966   /* index is NULL if OBJF_READNOW.  */
3967   if (index)
3968     {
3969       struct dw2_symtab_iterator iter;
3970       struct dwarf2_per_cu_data *per_cu;
3971
3972       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3973
3974       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3975         {
3976           struct symbol *sym, *with_opaque = NULL;
3977           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3978           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3979           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3980
3981           sym = block_find_symbol (block, name, domain,
3982                                    block_find_non_opaque_type_preferred,
3983                                    &with_opaque);
3984
3985           /* Some caution must be observed with overloaded functions
3986              and methods, since the index will not contain any overload
3987              information (but NAME might contain it).  */
3988
3989           if (sym != NULL
3990               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3991             return stab;
3992           if (with_opaque != NULL
3993               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3994             stab_best = stab;
3995
3996           /* Keep looking through other CUs.  */
3997         }
3998     }
3999
4000   return stab_best;
4001 }
4002
4003 static void
4004 dw2_print_stats (struct objfile *objfile)
4005 {
4006   int i, total, count;
4007
4008   dw2_setup (objfile);
4009   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
4010   count = 0;
4011   for (i = 0; i < total; ++i)
4012     {
4013       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4014
4015       if (!per_cu->v.quick->compunit_symtab)
4016         ++count;
4017     }
4018   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
4019   printf_filtered (_("  Number of unread CUs: %d\n"), count);
4020 }
4021
4022 /* This dumps minimal information about the index.
4023    It is called via "mt print objfiles".
4024    One use is to verify .gdb_index has been loaded by the
4025    gdb.dwarf2/gdb-index.exp testcase.  */
4026
4027 static void
4028 dw2_dump (struct objfile *objfile)
4029 {
4030   dw2_setup (objfile);
4031   gdb_assert (dwarf2_per_objfile->using_index);
4032   printf_filtered (".gdb_index:");
4033   if (dwarf2_per_objfile->index_table != NULL)
4034     {
4035       printf_filtered (" version %d\n",
4036                        dwarf2_per_objfile->index_table->version);
4037     }
4038   else
4039     printf_filtered (" faked for \"readnow\"\n");
4040   printf_filtered ("\n");
4041 }
4042
4043 static void
4044 dw2_relocate (struct objfile *objfile,
4045               const struct section_offsets *new_offsets,
4046               const struct section_offsets *delta)
4047 {
4048   /* There's nothing to relocate here.  */
4049 }
4050
4051 static void
4052 dw2_expand_symtabs_for_function (struct objfile *objfile,
4053                                  const char *func_name)
4054 {
4055   struct mapped_index *index;
4056
4057   dw2_setup (objfile);
4058
4059   index = dwarf2_per_objfile->index_table;
4060
4061   /* index is NULL if OBJF_READNOW.  */
4062   if (index)
4063     {
4064       struct dw2_symtab_iterator iter;
4065       struct dwarf2_per_cu_data *per_cu;
4066
4067       /* Note: It doesn't matter what we pass for block_index here.  */
4068       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4069                             func_name);
4070
4071       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4072         dw2_instantiate_symtab (per_cu);
4073     }
4074 }
4075
4076 static void
4077 dw2_expand_all_symtabs (struct objfile *objfile)
4078 {
4079   int i;
4080
4081   dw2_setup (objfile);
4082
4083   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4084                    + dwarf2_per_objfile->n_type_units); ++i)
4085     {
4086       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4087
4088       dw2_instantiate_symtab (per_cu);
4089     }
4090 }
4091
4092 static void
4093 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4094                                   const char *fullname)
4095 {
4096   int i;
4097
4098   dw2_setup (objfile);
4099
4100   /* We don't need to consider type units here.
4101      This is only called for examining code, e.g. expand_line_sal.
4102      There can be an order of magnitude (or more) more type units
4103      than comp units, and we avoid them if we can.  */
4104
4105   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4106     {
4107       int j;
4108       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4109       struct quick_file_names *file_data;
4110
4111       /* We only need to look at symtabs not already expanded.  */
4112       if (per_cu->v.quick->compunit_symtab)
4113         continue;
4114
4115       file_data = dw2_get_file_names (per_cu);
4116       if (file_data == NULL)
4117         continue;
4118
4119       for (j = 0; j < file_data->num_file_names; ++j)
4120         {
4121           const char *this_fullname = file_data->file_names[j];
4122
4123           if (filename_cmp (this_fullname, fullname) == 0)
4124             {
4125               dw2_instantiate_symtab (per_cu);
4126               break;
4127             }
4128         }
4129     }
4130 }
4131
4132 static void
4133 dw2_map_matching_symbols (struct objfile *objfile,
4134                           const char * name, domain_enum domain,
4135                           int global,
4136                           int (*callback) (struct block *,
4137                                            struct symbol *, void *),
4138                           void *data, symbol_name_match_type match,
4139                           symbol_compare_ftype *ordered_compare)
4140 {
4141   /* Currently unimplemented; used for Ada.  The function can be called if the
4142      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4143      does not look for non-Ada symbols this function should just return.  */
4144 }
4145
4146 /* Symbol name matcher for .gdb_index names.
4147
4148    Symbol names in .gdb_index have a few particularities:
4149
4150    - There's no indication of which is the language of each symbol.
4151
4152      Since each language has its own symbol name matching algorithm,
4153      and we don't know which language is the right one, we must match
4154      each symbol against all languages.  This would be a potential
4155      performance problem if it were not mitigated by the
4156      mapped_index::name_components lookup table, which significantly
4157      reduces the number of times we need to call into this matcher,
4158      making it a non-issue.
4159
4160    - Symbol names in the index have no overload (parameter)
4161      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4162      appear as "foo" in the index, for example.
4163
4164      This means that the lookup names passed to the symbol name
4165      matcher functions must have no parameter information either
4166      because (e.g.) symbol search name "foo" does not match
4167      lookup-name "foo(int)" [while swapping search name for lookup
4168      name would match].
4169 */
4170 class gdb_index_symbol_name_matcher
4171 {
4172 public:
4173   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4174   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4175
4176   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4177      Returns true if any matcher matches.  */
4178   bool matches (const char *symbol_name);
4179
4180 private:
4181   /* A reference to the lookup name we're matching against.  */
4182   const lookup_name_info &m_lookup_name;
4183
4184   /* A vector holding all the different symbol name matchers, for all
4185      languages.  */
4186   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4187 };
4188
4189 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4190   (const lookup_name_info &lookup_name)
4191     : m_lookup_name (lookup_name)
4192 {
4193   /* Prepare the vector of comparison functions upfront, to avoid
4194      doing the same work for each symbol.  Care is taken to avoid
4195      matching with the same matcher more than once if/when multiple
4196      languages use the same matcher function.  */
4197   auto &matchers = m_symbol_name_matcher_funcs;
4198   matchers.reserve (nr_languages);
4199
4200   matchers.push_back (default_symbol_name_matcher);
4201
4202   for (int i = 0; i < nr_languages; i++)
4203     {
4204       const language_defn *lang = language_def ((enum language) i);
4205       if (lang->la_get_symbol_name_matcher != NULL)
4206         {
4207           symbol_name_matcher_ftype *name_matcher
4208             = lang->la_get_symbol_name_matcher (m_lookup_name);
4209
4210           /* Don't insert the same comparison routine more than once.
4211              Note that we do this linear walk instead of a cheaper
4212              sorted insert, or use a std::set or something like that,
4213              because relative order of function addresses is not
4214              stable.  This is not a problem in practice because the
4215              number of supported languages is low, and the cost here
4216              is tiny compared to the number of searches we'll do
4217              afterwards using this object.  */
4218           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4219               == matchers.end ())
4220             matchers.push_back (name_matcher);
4221         }
4222     }
4223 }
4224
4225 bool
4226 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4227 {
4228   for (auto matches_name : m_symbol_name_matcher_funcs)
4229     if (matches_name (symbol_name, m_lookup_name, NULL))
4230       return true;
4231
4232   return false;
4233 }
4234
4235 /* Starting from a search name, return the string that finds the upper
4236    bound of all strings that start with SEARCH_NAME in a sorted name
4237    list.  Returns the empty string to indicate that the upper bound is
4238    the end of the list.  */
4239
4240 static std::string
4241 make_sort_after_prefix_name (const char *search_name)
4242 {
4243   /* When looking to complete "func", we find the upper bound of all
4244      symbols that start with "func" by looking for where we'd insert
4245      the closest string that would follow "func" in lexicographical
4246      order.  Usually, that's "func"-with-last-character-incremented,
4247      i.e. "fund".  Mind non-ASCII characters, though.  Usually those
4248      will be UTF-8 multi-byte sequences, but we can't be certain.
4249      Especially mind the 0xff character, which is a valid character in
4250      non-UTF-8 source character sets (e.g. Latin1 'ÿ'), and we can't
4251      rule out compilers allowing it in identifiers.  Note that
4252      conveniently, strcmp/strcasecmp are specified to compare
4253      characters interpreted as unsigned char.  So what we do is treat
4254      the whole string as a base 256 number composed of a sequence of
4255      base 256 "digits" and add 1 to it.  I.e., adding 1 to 0xff wraps
4256      to 0, and carries 1 to the following more-significant position.
4257      If the very first character in SEARCH_NAME ends up incremented
4258      and carries/overflows, then the upper bound is the end of the
4259      list.  The string after the empty string is also the empty
4260      string.
4261
4262      Some examples of this operation:
4263
4264        SEARCH_NAME  => "+1" RESULT
4265
4266        "abc"              => "abd"
4267        "ab\xff"           => "ac"
4268        "\xff" "a" "\xff"  => "\xff" "b"
4269        "\xff"             => ""
4270        "\xff\xff"         => ""
4271        ""                 => ""
4272
4273      Then, with these symbols for example:
4274
4275       func
4276       func1
4277       fund
4278
4279      completing "func" looks for symbols between "func" and
4280      "func"-with-last-character-incremented, i.e. "fund" (exclusive),
4281      which finds "func" and "func1", but not "fund".
4282
4283      And with:
4284
4285       funcÿ     (Latin1 'ÿ' [0xff])
4286       funcÿ1
4287       fund
4288
4289      completing "funcÿ" looks for symbols between "funcÿ" and "fund"
4290      (exclusive), which finds "funcÿ" and "funcÿ1", but not "fund".
4291
4292      And with:
4293
4294       ÿÿ        (Latin1 'ÿ' [0xff])
4295       ÿÿ1
4296
4297      completing "ÿ" or "ÿÿ" looks for symbols between between "ÿÿ" and
4298      the end of the list.
4299   */
4300   std::string after = search_name;
4301   while (!after.empty () && (unsigned char) after.back () == 0xff)
4302     after.pop_back ();
4303   if (!after.empty ())
4304     after.back () = (unsigned char) after.back () + 1;
4305   return after;
4306 }
4307
4308 /* See declaration.  */
4309
4310 std::pair<std::vector<name_component>::const_iterator,
4311           std::vector<name_component>::const_iterator>
4312 mapped_index::find_name_components_bounds
4313   (const lookup_name_info &lookup_name_without_params) const
4314 {
4315   auto *name_cmp
4316     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4317
4318   const char *cplus
4319     = lookup_name_without_params.cplus ().lookup_name ().c_str ();
4320
4321   /* Comparison function object for lower_bound that matches against a
4322      given symbol name.  */
4323   auto lookup_compare_lower = [&] (const name_component &elem,
4324                                    const char *name)
4325     {
4326       const char *elem_qualified = this->symbol_name_at (elem.idx);
4327       const char *elem_name = elem_qualified + elem.name_offset;
4328       return name_cmp (elem_name, name) < 0;
4329     };
4330
4331   /* Comparison function object for upper_bound that matches against a
4332      given symbol name.  */
4333   auto lookup_compare_upper = [&] (const char *name,
4334                                    const name_component &elem)
4335     {
4336       const char *elem_qualified = this->symbol_name_at (elem.idx);
4337       const char *elem_name = elem_qualified + elem.name_offset;
4338       return name_cmp (name, elem_name) < 0;
4339     };
4340
4341   auto begin = this->name_components.begin ();
4342   auto end = this->name_components.end ();
4343
4344   /* Find the lower bound.  */
4345   auto lower = [&] ()
4346     {
4347       if (lookup_name_without_params.completion_mode () && cplus[0] == '\0')
4348         return begin;
4349       else
4350         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4351     } ();
4352
4353   /* Find the upper bound.  */
4354   auto upper = [&] ()
4355     {
4356       if (lookup_name_without_params.completion_mode ())
4357         {
4358           /* In completion mode, we want UPPER to point past all
4359              symbols names that have the same prefix.  I.e., with
4360              these symbols, and completing "func":
4361
4362               function        << lower bound
4363               function1
4364               other_function  << upper bound
4365
4366              We find the upper bound by looking for the insertion
4367              point of "func"-with-last-character-incremented,
4368              i.e. "fund".  */
4369           std::string after = make_sort_after_prefix_name (cplus);
4370           if (after.empty ())
4371             return end;
4372           return std::lower_bound (lower, end, after.c_str (),
4373                                    lookup_compare_lower);
4374         }
4375       else
4376         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4377     } ();
4378
4379   return {lower, upper};
4380 }
4381
4382 /* See declaration.  */
4383
4384 void
4385 mapped_index::build_name_components ()
4386 {
4387   if (!this->name_components.empty ())
4388     return;
4389
4390   this->name_components_casing = case_sensitivity;
4391   auto *name_cmp
4392     = this->name_components_casing == case_sensitive_on ? strcmp : strcasecmp;
4393
4394   /* The code below only knows how to break apart components of C++
4395      symbol names (and other languages that use '::' as
4396      namespace/module separator).  If we add support for wild matching
4397      to some language that uses some other operator (E.g., Ada, Go and
4398      D use '.'), then we'll need to try splitting the symbol name
4399      according to that language too.  Note that Ada does support wild
4400      matching, but doesn't currently support .gdb_index.  */
4401   for (size_t iter = 0; iter < this->symbol_table_slots; ++iter)
4402     {
4403       offset_type idx = 2 * iter;
4404
4405       if (this->symbol_table[idx] == 0
4406           && this->symbol_table[idx + 1] == 0)
4407         continue;
4408
4409       const char *name = this->symbol_name_at (idx);
4410
4411       /* Add each name component to the name component table.  */
4412       unsigned int previous_len = 0;
4413       for (unsigned int current_len = cp_find_first_component (name);
4414            name[current_len] != '\0';
4415            current_len += cp_find_first_component (name + current_len))
4416         {
4417           gdb_assert (name[current_len] == ':');
4418           this->name_components.push_back ({previous_len, idx});
4419           /* Skip the '::'.  */
4420           current_len += 2;
4421           previous_len = current_len;
4422         }
4423       this->name_components.push_back ({previous_len, idx});
4424     }
4425
4426   /* Sort name_components elements by name.  */
4427   auto name_comp_compare = [&] (const name_component &left,
4428                                 const name_component &right)
4429     {
4430       const char *left_qualified = this->symbol_name_at (left.idx);
4431       const char *right_qualified = this->symbol_name_at (right.idx);
4432
4433       const char *left_name = left_qualified + left.name_offset;
4434       const char *right_name = right_qualified + right.name_offset;
4435
4436       return name_cmp (left_name, right_name) < 0;
4437     };
4438
4439   std::sort (this->name_components.begin (),
4440              this->name_components.end (),
4441              name_comp_compare);
4442 }
4443
4444 /* Helper for dw2_expand_symtabs_matching that works with a
4445    mapped_index instead of the containing objfile.  This is split to a
4446    separate function in order to be able to unit test the
4447    name_components matching using a mock mapped_index.  For each
4448    symbol name that matches, calls MATCH_CALLBACK, passing it the
4449    symbol's index in the mapped_index symbol table.  */
4450
4451 static void
4452 dw2_expand_symtabs_matching_symbol
4453   (mapped_index &index,
4454    const lookup_name_info &lookup_name_in,
4455    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4456    enum search_domain kind,
4457    gdb::function_view<void (offset_type)> match_callback)
4458 {
4459   lookup_name_info lookup_name_without_params
4460     = lookup_name_in.make_ignore_params ();
4461   gdb_index_symbol_name_matcher lookup_name_matcher
4462     (lookup_name_without_params);
4463
4464   /* Build the symbol name component sorted vector, if we haven't
4465      yet.  */
4466   index.build_name_components ();
4467
4468   auto bounds = index.find_name_components_bounds (lookup_name_without_params);
4469
4470   /* Now for each symbol name in range, check to see if we have a name
4471      match, and if so, call the MATCH_CALLBACK callback.  */
4472
4473   /* The same symbol may appear more than once in the range though.
4474      E.g., if we're looking for symbols that complete "w", and we have
4475      a symbol named "w1::w2", we'll find the two name components for
4476      that same symbol in the range.  To be sure we only call the
4477      callback once per symbol, we first collect the symbol name
4478      indexes that matched in a temporary vector and ignore
4479      duplicates.  */
4480   std::vector<offset_type> matches;
4481   matches.reserve (std::distance (bounds.first, bounds.second));
4482
4483   for (; bounds.first != bounds.second; ++bounds.first)
4484     {
4485       const char *qualified = index.symbol_name_at (bounds.first->idx);
4486
4487       if (!lookup_name_matcher.matches (qualified)
4488           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4489         continue;
4490
4491       matches.push_back (bounds.first->idx);
4492     }
4493
4494   std::sort (matches.begin (), matches.end ());
4495
4496   /* Finally call the callback, once per match.  */
4497   ULONGEST prev = -1;
4498   for (offset_type idx : matches)
4499     {
4500       if (prev != idx)
4501         {
4502           match_callback (idx);
4503           prev = idx;
4504         }
4505     }
4506
4507   /* Above we use a type wider than idx's for 'prev', since 0 and
4508      (offset_type)-1 are both possible values.  */
4509   static_assert (sizeof (prev) > sizeof (offset_type), "");
4510 }
4511
4512 #if GDB_SELF_TEST
4513
4514 namespace selftests { namespace dw2_expand_symtabs_matching {
4515
4516 /* A wrapper around mapped_index that builds a mock mapped_index, from
4517    the symbol list passed as parameter to the constructor.  */
4518 class mock_mapped_index
4519 {
4520 public:
4521   template<size_t N>
4522   mock_mapped_index (const char *(&symbols)[N])
4523     : mock_mapped_index (symbols, N)
4524   {}
4525
4526   /* Access the built index.  */
4527   mapped_index &index ()
4528   { return m_index; }
4529
4530   /* Disable copy.  */
4531   mock_mapped_index(const mock_mapped_index &) = delete;
4532   void operator= (const mock_mapped_index &) = delete;
4533
4534 private:
4535   mock_mapped_index (const char **symbols, size_t symbols_size)
4536   {
4537     /* No string can live at offset zero.  Add a dummy entry.  */
4538     obstack_grow_str0 (&m_constant_pool, "");
4539
4540     for (size_t i = 0; i < symbols_size; i++)
4541       {
4542         const char *sym = symbols[i];
4543         size_t offset = obstack_object_size (&m_constant_pool);
4544         obstack_grow_str0 (&m_constant_pool, sym);
4545         m_symbol_table.push_back (offset);
4546         m_symbol_table.push_back (0);
4547       };
4548
4549     m_index.constant_pool = (const char *) obstack_base (&m_constant_pool);
4550     m_index.symbol_table = m_symbol_table.data ();
4551     m_index.symbol_table_slots = m_symbol_table.size () / 2;
4552   }
4553
4554 public:
4555   /* The built mapped_index.  */
4556   mapped_index m_index{};
4557
4558   /* The storage that the built mapped_index uses for symbol and
4559      constant pool tables.  */
4560   std::vector<offset_type> m_symbol_table;
4561   auto_obstack m_constant_pool;
4562 };
4563
4564 /* Convenience function that converts a NULL pointer to a "<null>"
4565    string, to pass to print routines.  */
4566
4567 static const char *
4568 string_or_null (const char *str)
4569 {
4570   return str != NULL ? str : "<null>";
4571 }
4572
4573 /* Check if a lookup_name_info built from
4574    NAME/MATCH_TYPE/COMPLETION_MODE matches the symbols in the mock
4575    index.  EXPECTED_LIST is the list of expected matches, in expected
4576    matching order.  If no match expected, then an empty list is
4577    specified.  Returns true on success.  On failure prints a warning
4578    indicating the file:line that failed, and returns false.  */
4579
4580 static bool
4581 check_match (const char *file, int line,
4582              mock_mapped_index &mock_index,
4583              const char *name, symbol_name_match_type match_type,
4584              bool completion_mode,
4585              std::initializer_list<const char *> expected_list)
4586 {
4587   lookup_name_info lookup_name (name, match_type, completion_mode);
4588
4589   bool matched = true;
4590
4591   auto mismatch = [&] (const char *expected_str,
4592                        const char *got)
4593   {
4594     warning (_("%s:%d: match_type=%s, looking-for=\"%s\", "
4595                "expected=\"%s\", got=\"%s\"\n"),
4596              file, line,
4597              (match_type == symbol_name_match_type::FULL
4598               ? "FULL" : "WILD"),
4599              name, string_or_null (expected_str), string_or_null (got));
4600     matched = false;
4601   };
4602
4603   auto expected_it = expected_list.begin ();
4604   auto expected_end = expected_list.end ();
4605
4606   dw2_expand_symtabs_matching_symbol (mock_index.index (), lookup_name,
4607                                       NULL, ALL_DOMAIN,
4608                                       [&] (offset_type idx)
4609   {
4610     const char *matched_name = mock_index.index ().symbol_name_at (idx);
4611     const char *expected_str
4612       = expected_it == expected_end ? NULL : *expected_it++;
4613
4614     if (expected_str == NULL || strcmp (expected_str, matched_name) != 0)
4615       mismatch (expected_str, matched_name);
4616   });
4617
4618   const char *expected_str
4619   = expected_it == expected_end ? NULL : *expected_it++;
4620   if (expected_str != NULL)
4621     mismatch (expected_str, NULL);
4622
4623   return matched;
4624 }
4625
4626 /* The symbols added to the mock mapped_index for testing (in
4627    canonical form).  */
4628 static const char *test_symbols[] = {
4629   "function",
4630   "std::bar",
4631   "std::zfunction",
4632   "std::zfunction2",
4633   "w1::w2",
4634   "ns::foo<char*>",
4635   "ns::foo<int>",
4636   "ns::foo<long>",
4637   "ns2::tmpl<int>::foo2",
4638   "(anonymous namespace)::A::B::C",
4639
4640   /* These are used to check that the increment-last-char in the
4641      matching algorithm for completion doesn't match "t1_fund" when
4642      completing "t1_func".  */
4643   "t1_func",
4644   "t1_func1",
4645   "t1_fund",
4646   "t1_fund1",
4647
4648   /* A UTF-8 name with multi-byte sequences to make sure that
4649      cp-name-parser understands this as a single identifier ("função"
4650      is "function" in PT).  */
4651   u8"u8função",
4652
4653   /* \377 (0xff) is Latin1 'ÿ'.  */
4654   "yfunc\377",
4655
4656   /* \377 (0xff) is Latin1 'ÿ'.  */
4657   "\377",
4658   "\377\377123",
4659
4660   /* A name with all sorts of complications.  Starts with "z" to make
4661      it easier for the completion tests below.  */
4662 #define Z_SYM_NAME \
4663   "z::std::tuple<(anonymous namespace)::ui*, std::bar<(anonymous namespace)::ui> >" \
4664     "::tuple<(anonymous namespace)::ui*, " \
4665     "std::default_delete<(anonymous namespace)::ui>, void>"
4666
4667   Z_SYM_NAME
4668 };
4669
4670 /* Returns true if the mapped_index::find_name_component_bounds method
4671    finds EXPECTED_SYMS in INDEX when looking for SEARCH_NAME, in
4672    completion mode.  */
4673
4674 static bool
4675 check_find_bounds_finds (mapped_index &index,
4676                          const char *search_name,
4677                          gdb::array_view<const char *> expected_syms)
4678 {
4679   lookup_name_info lookup_name (search_name,
4680                                 symbol_name_match_type::FULL, true);
4681
4682   auto bounds = index.find_name_components_bounds (lookup_name);
4683
4684   size_t distance = std::distance (bounds.first, bounds.second);
4685   if (distance != expected_syms.size ())
4686     return false;
4687
4688   for (size_t exp_elem = 0; exp_elem < distance; exp_elem++)
4689     {
4690       auto nc_elem = bounds.first + exp_elem;
4691       const char *qualified = index.symbol_name_at (nc_elem->idx);
4692       if (strcmp (qualified, expected_syms[exp_elem]) != 0)
4693         return false;
4694     }
4695
4696   return true;
4697 }
4698
4699 /* Test the lower-level mapped_index::find_name_component_bounds
4700    method.  */
4701
4702 static void
4703 test_mapped_index_find_name_component_bounds ()
4704 {
4705   mock_mapped_index mock_index (test_symbols);
4706
4707   mock_index.index ().build_name_components ();
4708
4709   /* Test the lower-level mapped_index::find_name_component_bounds
4710      method in completion mode.  */
4711   {
4712     static const char *expected_syms[] = {
4713       "t1_func",
4714       "t1_func1",
4715     };
4716
4717     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4718                                          "t1_func", expected_syms));
4719   }
4720
4721   /* Check that the increment-last-char in the name matching algorithm
4722      for completion doesn't get confused with Ansi1 'ÿ' / 0xff.  */
4723   {
4724     static const char *expected_syms1[] = {
4725       "\377",
4726       "\377\377123",
4727     };
4728     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4729                                          "\377", expected_syms1));
4730
4731     static const char *expected_syms2[] = {
4732       "\377\377123",
4733     };
4734     SELF_CHECK (check_find_bounds_finds (mock_index.index (),
4735                                          "\377\377", expected_syms2));
4736   }
4737 }
4738
4739 /* Test dw2_expand_symtabs_matching_symbol.  */
4740
4741 static void
4742 test_dw2_expand_symtabs_matching_symbol ()
4743 {
4744   mock_mapped_index mock_index (test_symbols);
4745
4746   /* We let all tests run until the end even if some fails, for debug
4747      convenience.  */
4748   bool any_mismatch = false;
4749
4750   /* Create the expected symbols list (an initializer_list).  Needed
4751      because lists have commas, and we need to pass them to CHECK,
4752      which is a macro.  */
4753 #define EXPECT(...) { __VA_ARGS__ }
4754
4755   /* Wrapper for check_match that passes down the current
4756      __FILE__/__LINE__.  */
4757 #define CHECK_MATCH(NAME, MATCH_TYPE, COMPLETION_MODE, EXPECTED_LIST)   \
4758   any_mismatch |= !check_match (__FILE__, __LINE__,                     \
4759                                 mock_index,                             \
4760                                 NAME, MATCH_TYPE, COMPLETION_MODE,      \
4761                                 EXPECTED_LIST)
4762
4763   /* Identity checks.  */
4764   for (const char *sym : test_symbols)
4765     {
4766       /* Should be able to match all existing symbols.  */
4767       CHECK_MATCH (sym, symbol_name_match_type::FULL, false,
4768                    EXPECT (sym));
4769
4770       /* Should be able to match all existing symbols with
4771          parameters.  */
4772       std::string with_params = std::string (sym) + "(int)";
4773       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4774                    EXPECT (sym));
4775
4776       /* Should be able to match all existing symbols with
4777          parameters and qualifiers.  */
4778       with_params = std::string (sym) + " ( int ) const";
4779       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4780                    EXPECT (sym));
4781
4782       /* This should really find sym, but cp-name-parser.y doesn't
4783          know about lvalue/rvalue qualifiers yet.  */
4784       with_params = std::string (sym) + " ( int ) &&";
4785       CHECK_MATCH (with_params.c_str (), symbol_name_match_type::FULL, false,
4786                    {});
4787     }
4788
4789   /* Check that the name matching algorithm for completion doesn't get
4790      confused with Latin1 'ÿ' / 0xff.  */
4791   {
4792     static const char str[] = "\377";
4793     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4794                  EXPECT ("\377", "\377\377123"));
4795   }
4796
4797   /* Check that the increment-last-char in the matching algorithm for
4798      completion doesn't match "t1_fund" when completing "t1_func".  */
4799   {
4800     static const char str[] = "t1_func";
4801     CHECK_MATCH (str, symbol_name_match_type::FULL, true,
4802                  EXPECT ("t1_func", "t1_func1"));
4803   }
4804
4805   /* Check that completion mode works at each prefix of the expected
4806      symbol name.  */
4807   {
4808     static const char str[] = "function(int)";
4809     size_t len = strlen (str);
4810     std::string lookup;
4811
4812     for (size_t i = 1; i < len; i++)
4813       {
4814         lookup.assign (str, i);
4815         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4816                      EXPECT ("function"));
4817       }
4818   }
4819
4820   /* While "w" is a prefix of both components, the match function
4821      should still only be called once.  */
4822   {
4823     CHECK_MATCH ("w", symbol_name_match_type::FULL, true,
4824                  EXPECT ("w1::w2"));
4825     CHECK_MATCH ("w", symbol_name_match_type::WILD, true,
4826                  EXPECT ("w1::w2"));
4827   }
4828
4829   /* Same, with a "complicated" symbol.  */
4830   {
4831     static const char str[] = Z_SYM_NAME;
4832     size_t len = strlen (str);
4833     std::string lookup;
4834
4835     for (size_t i = 1; i < len; i++)
4836       {
4837         lookup.assign (str, i);
4838         CHECK_MATCH (lookup.c_str (), symbol_name_match_type::FULL, true,
4839                      EXPECT (Z_SYM_NAME));
4840       }
4841   }
4842
4843   /* In FULL mode, an incomplete symbol doesn't match.  */
4844   {
4845     CHECK_MATCH ("std::zfunction(int", symbol_name_match_type::FULL, false,
4846                  {});
4847   }
4848
4849   /* A complete symbol with parameters matches any overload, since the
4850      index has no overload info.  */
4851   {
4852     CHECK_MATCH ("std::zfunction(int)", symbol_name_match_type::FULL, true,
4853                  EXPECT ("std::zfunction", "std::zfunction2"));
4854     CHECK_MATCH ("zfunction(int)", symbol_name_match_type::WILD, true,
4855                  EXPECT ("std::zfunction", "std::zfunction2"));
4856     CHECK_MATCH ("zfunc", symbol_name_match_type::WILD, true,
4857                  EXPECT ("std::zfunction", "std::zfunction2"));
4858   }
4859
4860   /* Check that whitespace is ignored appropriately.  A symbol with a
4861      template argument list. */
4862   {
4863     static const char expected[] = "ns::foo<int>";
4864     CHECK_MATCH ("ns :: foo < int > ", symbol_name_match_type::FULL, false,
4865                  EXPECT (expected));
4866     CHECK_MATCH ("foo < int > ", symbol_name_match_type::WILD, false,
4867                  EXPECT (expected));
4868   }
4869
4870   /* Check that whitespace is ignored appropriately.  A symbol with a
4871      template argument list that includes a pointer.  */
4872   {
4873     static const char expected[] = "ns::foo<char*>";
4874     /* Try both completion and non-completion modes.  */
4875     static const bool completion_mode[2] = {false, true};
4876     for (size_t i = 0; i < 2; i++)
4877       {
4878         CHECK_MATCH ("ns :: foo < char * >", symbol_name_match_type::FULL,
4879                      completion_mode[i], EXPECT (expected));
4880         CHECK_MATCH ("foo < char * >", symbol_name_match_type::WILD,
4881                      completion_mode[i], EXPECT (expected));
4882
4883         CHECK_MATCH ("ns :: foo < char * > (int)", symbol_name_match_type::FULL,
4884                      completion_mode[i], EXPECT (expected));
4885         CHECK_MATCH ("foo < char * > (int)", symbol_name_match_type::WILD,
4886                      completion_mode[i], EXPECT (expected));
4887       }
4888   }
4889
4890   {
4891     /* Check method qualifiers are ignored.  */
4892     static const char expected[] = "ns::foo<char*>";
4893     CHECK_MATCH ("ns :: foo < char * >  ( int ) const",
4894                  symbol_name_match_type::FULL, true, EXPECT (expected));
4895     CHECK_MATCH ("ns :: foo < char * >  ( int ) &&",
4896                  symbol_name_match_type::FULL, true, EXPECT (expected));
4897     CHECK_MATCH ("foo < char * >  ( int ) const",
4898                  symbol_name_match_type::WILD, true, EXPECT (expected));
4899     CHECK_MATCH ("foo < char * >  ( int ) &&",
4900                  symbol_name_match_type::WILD, true, EXPECT (expected));
4901   }
4902
4903   /* Test lookup names that don't match anything.  */
4904   {
4905     CHECK_MATCH ("bar2", symbol_name_match_type::WILD, false,
4906                  {});
4907
4908     CHECK_MATCH ("doesntexist", symbol_name_match_type::FULL, false,
4909                  {});
4910   }
4911
4912   /* Some wild matching tests, exercising "(anonymous namespace)",
4913      which should not be confused with a parameter list.  */
4914   {
4915     static const char *syms[] = {
4916       "A::B::C",
4917       "B::C",
4918       "C",
4919       "A :: B :: C ( int )",
4920       "B :: C ( int )",
4921       "C ( int )",
4922     };
4923
4924     for (const char *s : syms)
4925       {
4926         CHECK_MATCH (s, symbol_name_match_type::WILD, false,
4927                      EXPECT ("(anonymous namespace)::A::B::C"));
4928       }
4929   }
4930
4931   {
4932     static const char expected[] = "ns2::tmpl<int>::foo2";
4933     CHECK_MATCH ("tmp", symbol_name_match_type::WILD, true,
4934                  EXPECT (expected));
4935     CHECK_MATCH ("tmpl<", symbol_name_match_type::WILD, true,
4936                  EXPECT (expected));
4937   }
4938
4939   SELF_CHECK (!any_mismatch);
4940
4941 #undef EXPECT
4942 #undef CHECK_MATCH
4943 }
4944
4945 static void
4946 run_test ()
4947 {
4948   test_mapped_index_find_name_component_bounds ();
4949   test_dw2_expand_symtabs_matching_symbol ();
4950 }
4951
4952 }} // namespace selftests::dw2_expand_symtabs_matching
4953
4954 #endif /* GDB_SELF_TEST */
4955
4956 /* If FILE_MATCHER is NULL or if PER_CU has
4957    dwarf2_per_cu_quick_data::MARK set (see
4958    dw_expand_symtabs_matching_file_matcher), expand the CU and call
4959    EXPANSION_NOTIFY on it.  */
4960
4961 static void
4962 dw2_expand_symtabs_matching_one
4963   (struct dwarf2_per_cu_data *per_cu,
4964    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4965    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify)
4966 {
4967   if (file_matcher == NULL || per_cu->v.quick->mark)
4968     {
4969       bool symtab_was_null
4970         = (per_cu->v.quick->compunit_symtab == NULL);
4971
4972       dw2_instantiate_symtab (per_cu);
4973
4974       if (expansion_notify != NULL
4975           && symtab_was_null
4976           && per_cu->v.quick->compunit_symtab != NULL)
4977         expansion_notify (per_cu->v.quick->compunit_symtab);
4978     }
4979 }
4980
4981 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4982    matched, to expand corresponding CUs that were marked.  IDX is the
4983    index of the symbol name that matched.  */
4984
4985 static void
4986 dw2_expand_marked_cus
4987   (mapped_index &index, offset_type idx,
4988    struct objfile *objfile,
4989    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4990    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4991    search_domain kind)
4992 {
4993   offset_type *vec, vec_len, vec_idx;
4994   bool global_seen = false;
4995
4996   vec = (offset_type *) (index.constant_pool
4997                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
4998   vec_len = MAYBE_SWAP (vec[0]);
4999   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
5000     {
5001       struct dwarf2_per_cu_data *per_cu;
5002       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
5003       /* This value is only valid for index versions >= 7.  */
5004       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
5005       gdb_index_symbol_kind symbol_kind =
5006         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
5007       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
5008       /* Only check the symbol attributes if they're present.
5009          Indices prior to version 7 don't record them,
5010          and indices >= 7 may elide them for certain symbols
5011          (gold does this).  */
5012       int attrs_valid =
5013         (index.version >= 7
5014          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
5015
5016       /* Work around gold/15646.  */
5017       if (attrs_valid)
5018         {
5019           if (!is_static && global_seen)
5020             continue;
5021           if (!is_static)
5022             global_seen = true;
5023         }
5024
5025       /* Only check the symbol's kind if it has one.  */
5026       if (attrs_valid)
5027         {
5028           switch (kind)
5029             {
5030             case VARIABLES_DOMAIN:
5031               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
5032                 continue;
5033               break;
5034             case FUNCTIONS_DOMAIN:
5035               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
5036                 continue;
5037               break;
5038             case TYPES_DOMAIN:
5039               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
5040                 continue;
5041               break;
5042             default:
5043               break;
5044             }
5045         }
5046
5047       /* Don't crash on bad data.  */
5048       if (cu_index >= (dwarf2_per_objfile->n_comp_units
5049                        + dwarf2_per_objfile->n_type_units))
5050         {
5051           complaint (&symfile_complaints,
5052                      _(".gdb_index entry has bad CU index"
5053                        " [in module %s]"), objfile_name (objfile));
5054           continue;
5055         }
5056
5057       per_cu = dw2_get_cutu (cu_index);
5058       dw2_expand_symtabs_matching_one (per_cu, file_matcher,
5059                                        expansion_notify);
5060     }
5061 }
5062
5063 /* If FILE_MATCHER is non-NULL, set all the
5064    dwarf2_per_cu_quick_data::MARK of the current DWARF2_PER_OBJFILE
5065    that match FILE_MATCHER.  */
5066
5067 static void
5068 dw_expand_symtabs_matching_file_matcher
5069   (gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher)
5070 {
5071   if (file_matcher == NULL)
5072     return;
5073
5074   objfile *const objfile = dwarf2_per_objfile->objfile;
5075
5076   htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
5077                                             htab_eq_pointer,
5078                                             NULL, xcalloc, xfree));
5079   htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
5080                                                 htab_eq_pointer,
5081                                                 NULL, xcalloc, xfree));
5082
5083   /* The rule is CUs specify all the files, including those used by
5084      any TU, so there's no need to scan TUs here.  */
5085
5086   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5087     {
5088       int j;
5089       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5090       struct quick_file_names *file_data;
5091       void **slot;
5092
5093       QUIT;
5094
5095       per_cu->v.quick->mark = 0;
5096
5097       /* We only need to look at symtabs not already expanded.  */
5098       if (per_cu->v.quick->compunit_symtab)
5099         continue;
5100
5101       file_data = dw2_get_file_names (per_cu);
5102       if (file_data == NULL)
5103         continue;
5104
5105       if (htab_find (visited_not_found.get (), file_data) != NULL)
5106         continue;
5107       else if (htab_find (visited_found.get (), file_data) != NULL)
5108         {
5109           per_cu->v.quick->mark = 1;
5110           continue;
5111         }
5112
5113       for (j = 0; j < file_data->num_file_names; ++j)
5114         {
5115           const char *this_real_name;
5116
5117           if (file_matcher (file_data->file_names[j], false))
5118             {
5119               per_cu->v.quick->mark = 1;
5120               break;
5121             }
5122
5123           /* Before we invoke realpath, which can get expensive when many
5124              files are involved, do a quick comparison of the basenames.  */
5125           if (!basenames_may_differ
5126               && !file_matcher (lbasename (file_data->file_names[j]),
5127                                 true))
5128             continue;
5129
5130           this_real_name = dw2_get_real_path (objfile, file_data, j);
5131           if (file_matcher (this_real_name, false))
5132             {
5133               per_cu->v.quick->mark = 1;
5134               break;
5135             }
5136         }
5137
5138       slot = htab_find_slot (per_cu->v.quick->mark
5139                              ? visited_found.get ()
5140                              : visited_not_found.get (),
5141                              file_data, INSERT);
5142       *slot = file_data;
5143     }
5144 }
5145
5146 static void
5147 dw2_expand_symtabs_matching
5148   (struct objfile *objfile,
5149    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
5150    const lookup_name_info &lookup_name,
5151    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
5152    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
5153    enum search_domain kind)
5154 {
5155   int i;
5156
5157   dw2_setup (objfile);
5158
5159   /* index_table is NULL if OBJF_READNOW.  */
5160   if (!dwarf2_per_objfile->index_table)
5161     return;
5162
5163   dw_expand_symtabs_matching_file_matcher (file_matcher);
5164
5165   mapped_index &index = *dwarf2_per_objfile->index_table;
5166
5167   dw2_expand_symtabs_matching_symbol (index, lookup_name,
5168                                       symbol_matcher,
5169                                       kind, [&] (offset_type idx)
5170     {
5171       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
5172                              expansion_notify, kind);
5173     });
5174 }
5175
5176 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
5177    symtab.  */
5178
5179 static struct compunit_symtab *
5180 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
5181                                           CORE_ADDR pc)
5182 {
5183   int i;
5184
5185   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
5186       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
5187     return cust;
5188
5189   if (cust->includes == NULL)
5190     return NULL;
5191
5192   for (i = 0; cust->includes[i]; ++i)
5193     {
5194       struct compunit_symtab *s = cust->includes[i];
5195
5196       s = recursively_find_pc_sect_compunit_symtab (s, pc);
5197       if (s != NULL)
5198         return s;
5199     }
5200
5201   return NULL;
5202 }
5203
5204 static struct compunit_symtab *
5205 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
5206                                   struct bound_minimal_symbol msymbol,
5207                                   CORE_ADDR pc,
5208                                   struct obj_section *section,
5209                                   int warn_if_readin)
5210 {
5211   struct dwarf2_per_cu_data *data;
5212   struct compunit_symtab *result;
5213
5214   dw2_setup (objfile);
5215
5216   if (!objfile->psymtabs_addrmap)
5217     return NULL;
5218
5219   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
5220                                                      pc);
5221   if (!data)
5222     return NULL;
5223
5224   if (warn_if_readin && data->v.quick->compunit_symtab)
5225     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
5226              paddress (get_objfile_arch (objfile), pc));
5227
5228   result
5229     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
5230                                                 pc);
5231   gdb_assert (result != NULL);
5232   return result;
5233 }
5234
5235 static void
5236 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
5237                           void *data, int need_fullname)
5238 {
5239   dw2_setup (objfile);
5240
5241   if (!dwarf2_per_objfile->filenames_cache)
5242     {
5243       dwarf2_per_objfile->filenames_cache.emplace ();
5244
5245       htab_up visited (htab_create_alloc (10,
5246                                           htab_hash_pointer, htab_eq_pointer,
5247                                           NULL, xcalloc, xfree));
5248
5249       /* The rule is CUs specify all the files, including those used
5250          by any TU, so there's no need to scan TUs here.  We can
5251          ignore file names coming from already-expanded CUs.  */
5252
5253       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5254         {
5255           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5256
5257           if (per_cu->v.quick->compunit_symtab)
5258             {
5259               void **slot = htab_find_slot (visited.get (),
5260                                             per_cu->v.quick->file_names,
5261                                             INSERT);
5262
5263               *slot = per_cu->v.quick->file_names;
5264             }
5265         }
5266
5267       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
5268         {
5269           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
5270           struct quick_file_names *file_data;
5271           void **slot;
5272
5273           /* We only need to look at symtabs not already expanded.  */
5274           if (per_cu->v.quick->compunit_symtab)
5275             continue;
5276
5277           file_data = dw2_get_file_names (per_cu);
5278           if (file_data == NULL)
5279             continue;
5280
5281           slot = htab_find_slot (visited.get (), file_data, INSERT);
5282           if (*slot)
5283             {
5284               /* Already visited.  */
5285               continue;
5286             }
5287           *slot = file_data;
5288
5289           for (int j = 0; j < file_data->num_file_names; ++j)
5290             {
5291               const char *filename = file_data->file_names[j];
5292               dwarf2_per_objfile->filenames_cache->seen (filename);
5293             }
5294         }
5295     }
5296
5297   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
5298     {
5299       gdb::unique_xmalloc_ptr<char> this_real_name;
5300
5301       if (need_fullname)
5302         this_real_name = gdb_realpath (filename);
5303       (*fun) (filename, this_real_name.get (), data);
5304     });
5305 }
5306
5307 static int
5308 dw2_has_symbols (struct objfile *objfile)
5309 {
5310   return 1;
5311 }
5312
5313 const struct quick_symbol_functions dwarf2_gdb_index_functions =
5314 {
5315   dw2_has_symbols,
5316   dw2_find_last_source_symtab,
5317   dw2_forget_cached_source_info,
5318   dw2_map_symtabs_matching_filename,
5319   dw2_lookup_symbol,
5320   dw2_print_stats,
5321   dw2_dump,
5322   dw2_relocate,
5323   dw2_expand_symtabs_for_function,
5324   dw2_expand_all_symtabs,
5325   dw2_expand_symtabs_with_fullname,
5326   dw2_map_matching_symbols,
5327   dw2_expand_symtabs_matching,
5328   dw2_find_pc_sect_compunit_symtab,
5329   NULL,
5330   dw2_map_symbol_filenames
5331 };
5332
5333 /* Initialize for reading DWARF for this objfile.  Return 0 if this
5334    file will use psymtabs, or 1 if using the GNU index.  */
5335
5336 const sym_fns &
5337 dwarf2_initialize_objfile (struct objfile *objfile)
5338 {
5339   /* If we're about to read full symbols, don't bother with the
5340      indices.  In this case we also don't care if some other debug
5341      format is making psymtabs, because they are all about to be
5342      expanded anyway.  */
5343   if ((objfile->flags & OBJF_READNOW))
5344     {
5345       int i;
5346
5347       dwarf2_per_objfile->using_index = 1;
5348       create_all_comp_units (objfile);
5349       create_all_type_units (objfile);
5350       dwarf2_per_objfile->quick_file_names_table =
5351         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
5352
5353       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
5354                        + dwarf2_per_objfile->n_type_units); ++i)
5355         {
5356           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
5357
5358           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5359                                             struct dwarf2_per_cu_quick_data);
5360         }
5361
5362       /* Return 1 so that gdb sees the "quick" functions.  However,
5363          these functions will be no-ops because we will have expanded
5364          all symtabs.  */
5365       return elf_sym_fns_gdb_index;
5366     }
5367
5368   if (dwarf2_read_index (objfile))
5369     return elf_sym_fns_gdb_index;
5370
5371   return elf_sym_fns_lazy_psyms;
5372 }
5373
5374 \f
5375
5376 /* Build a partial symbol table.  */
5377
5378 void
5379 dwarf2_build_psymtabs (struct objfile *objfile)
5380 {
5381
5382   if (objfile->global_psymbols.capacity () == 0
5383       && objfile->static_psymbols.capacity () == 0)
5384     init_psymbol_list (objfile, 1024);
5385
5386   TRY
5387     {
5388       /* This isn't really ideal: all the data we allocate on the
5389          objfile's obstack is still uselessly kept around.  However,
5390          freeing it seems unsafe.  */
5391       psymtab_discarder psymtabs (objfile);
5392       dwarf2_build_psymtabs_hard (objfile);
5393       psymtabs.keep ();
5394     }
5395   CATCH (except, RETURN_MASK_ERROR)
5396     {
5397       exception_print (gdb_stderr, except);
5398     }
5399   END_CATCH
5400 }
5401
5402 /* Return the total length of the CU described by HEADER.  */
5403
5404 static unsigned int
5405 get_cu_length (const struct comp_unit_head *header)
5406 {
5407   return header->initial_length_size + header->length;
5408 }
5409
5410 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
5411
5412 static inline bool
5413 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
5414 {
5415   sect_offset bottom = cu_header->sect_off;
5416   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
5417
5418   return sect_off >= bottom && sect_off < top;
5419 }
5420
5421 /* Find the base address of the compilation unit for range lists and
5422    location lists.  It will normally be specified by DW_AT_low_pc.
5423    In DWARF-3 draft 4, the base address could be overridden by
5424    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
5425    compilation units with discontinuous ranges.  */
5426
5427 static void
5428 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
5429 {
5430   struct attribute *attr;
5431
5432   cu->base_known = 0;
5433   cu->base_address = 0;
5434
5435   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
5436   if (attr)
5437     {
5438       cu->base_address = attr_value_as_address (attr);
5439       cu->base_known = 1;
5440     }
5441   else
5442     {
5443       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
5444       if (attr)
5445         {
5446           cu->base_address = attr_value_as_address (attr);
5447           cu->base_known = 1;
5448         }
5449     }
5450 }
5451
5452 /* Read in the comp unit header information from the debug_info at info_ptr.
5453    Use rcuh_kind::COMPILE as the default type if not known by the caller.
5454    NOTE: This leaves members offset, first_die_offset to be filled in
5455    by the caller.  */
5456
5457 static const gdb_byte *
5458 read_comp_unit_head (struct comp_unit_head *cu_header,
5459                      const gdb_byte *info_ptr,
5460                      struct dwarf2_section_info *section,
5461                      rcuh_kind section_kind)
5462 {
5463   int signed_addr;
5464   unsigned int bytes_read;
5465   const char *filename = get_section_file_name (section);
5466   bfd *abfd = get_section_bfd_owner (section);
5467
5468   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
5469   cu_header->initial_length_size = bytes_read;
5470   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
5471   info_ptr += bytes_read;
5472   cu_header->version = read_2_bytes (abfd, info_ptr);
5473   info_ptr += 2;
5474   if (cu_header->version < 5)
5475     switch (section_kind)
5476       {
5477       case rcuh_kind::COMPILE:
5478         cu_header->unit_type = DW_UT_compile;
5479         break;
5480       case rcuh_kind::TYPE:
5481         cu_header->unit_type = DW_UT_type;
5482         break;
5483       default:
5484         internal_error (__FILE__, __LINE__,
5485                         _("read_comp_unit_head: invalid section_kind"));
5486       }
5487   else
5488     {
5489       cu_header->unit_type = static_cast<enum dwarf_unit_type>
5490                                                  (read_1_byte (abfd, info_ptr));
5491       info_ptr += 1;
5492       switch (cu_header->unit_type)
5493         {
5494         case DW_UT_compile:
5495           if (section_kind != rcuh_kind::COMPILE)
5496             error (_("Dwarf Error: wrong unit_type in compilation unit header "
5497                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
5498                    filename);
5499           break;
5500         case DW_UT_type:
5501           section_kind = rcuh_kind::TYPE;
5502           break;
5503         default:
5504           error (_("Dwarf Error: wrong unit_type in compilation unit header "
5505                  "(is %d, should be %d or %d) [in module %s]"),
5506                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
5507         }
5508
5509       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5510       info_ptr += 1;
5511     }
5512   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
5513                                                           cu_header,
5514                                                           &bytes_read);
5515   info_ptr += bytes_read;
5516   if (cu_header->version < 5)
5517     {
5518       cu_header->addr_size = read_1_byte (abfd, info_ptr);
5519       info_ptr += 1;
5520     }
5521   signed_addr = bfd_get_sign_extend_vma (abfd);
5522   if (signed_addr < 0)
5523     internal_error (__FILE__, __LINE__,
5524                     _("read_comp_unit_head: dwarf from non elf file"));
5525   cu_header->signed_addr_p = signed_addr;
5526
5527   if (section_kind == rcuh_kind::TYPE)
5528     {
5529       LONGEST type_offset;
5530
5531       cu_header->signature = read_8_bytes (abfd, info_ptr);
5532       info_ptr += 8;
5533
5534       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
5535       info_ptr += bytes_read;
5536       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
5537       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
5538         error (_("Dwarf Error: Too big type_offset in compilation unit "
5539                "header (is %s) [in module %s]"), plongest (type_offset),
5540                filename);
5541     }
5542
5543   return info_ptr;
5544 }
5545
5546 /* Helper function that returns the proper abbrev section for
5547    THIS_CU.  */
5548
5549 static struct dwarf2_section_info *
5550 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
5551 {
5552   struct dwarf2_section_info *abbrev;
5553
5554   if (this_cu->is_dwz)
5555     abbrev = &dwarf2_get_dwz_file ()->abbrev;
5556   else
5557     abbrev = &dwarf2_per_objfile->abbrev;
5558
5559   return abbrev;
5560 }
5561
5562 /* Subroutine of read_and_check_comp_unit_head and
5563    read_and_check_type_unit_head to simplify them.
5564    Perform various error checking on the header.  */
5565
5566 static void
5567 error_check_comp_unit_head (struct comp_unit_head *header,
5568                             struct dwarf2_section_info *section,
5569                             struct dwarf2_section_info *abbrev_section)
5570 {
5571   const char *filename = get_section_file_name (section);
5572
5573   if (header->version < 2 || header->version > 5)
5574     error (_("Dwarf Error: wrong version in compilation unit header "
5575            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
5576            filename);
5577
5578   if (to_underlying (header->abbrev_sect_off)
5579       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
5580     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
5581            "(offset 0x%x + 6) [in module %s]"),
5582            to_underlying (header->abbrev_sect_off),
5583            to_underlying (header->sect_off),
5584            filename);
5585
5586   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
5587      avoid potential 32-bit overflow.  */
5588   if (((ULONGEST) header->sect_off + get_cu_length (header))
5589       > section->size)
5590     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
5591            "(offset 0x%x + 0) [in module %s]"),
5592            header->length, to_underlying (header->sect_off),
5593            filename);
5594 }
5595
5596 /* Read in a CU/TU header and perform some basic error checking.
5597    The contents of the header are stored in HEADER.
5598    The result is a pointer to the start of the first DIE.  */
5599
5600 static const gdb_byte *
5601 read_and_check_comp_unit_head (struct comp_unit_head *header,
5602                                struct dwarf2_section_info *section,
5603                                struct dwarf2_section_info *abbrev_section,
5604                                const gdb_byte *info_ptr,
5605                                rcuh_kind section_kind)
5606 {
5607   const gdb_byte *beg_of_comp_unit = info_ptr;
5608
5609   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
5610
5611   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
5612
5613   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5614
5615   error_check_comp_unit_head (header, section, abbrev_section);
5616
5617   return info_ptr;
5618 }
5619
5620 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5621
5622 static sect_offset
5623 read_abbrev_offset (struct dwarf2_section_info *section,
5624                     sect_offset sect_off)
5625 {
5626   bfd *abfd = get_section_bfd_owner (section);
5627   const gdb_byte *info_ptr;
5628   unsigned int initial_length_size, offset_size;
5629   uint16_t version;
5630
5631   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5632   info_ptr = section->buffer + to_underlying (sect_off);
5633   read_initial_length (abfd, info_ptr, &initial_length_size);
5634   offset_size = initial_length_size == 4 ? 4 : 8;
5635   info_ptr += initial_length_size;
5636
5637   version = read_2_bytes (abfd, info_ptr);
5638   info_ptr += 2;
5639   if (version >= 5)
5640     {
5641       /* Skip unit type and address size.  */
5642       info_ptr += 2;
5643     }
5644
5645   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5646 }
5647
5648 /* Allocate a new partial symtab for file named NAME and mark this new
5649    partial symtab as being an include of PST.  */
5650
5651 static void
5652 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5653                                struct objfile *objfile)
5654 {
5655   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5656
5657   if (!IS_ABSOLUTE_PATH (subpst->filename))
5658     {
5659       /* It shares objfile->objfile_obstack.  */
5660       subpst->dirname = pst->dirname;
5661     }
5662
5663   subpst->textlow = 0;
5664   subpst->texthigh = 0;
5665
5666   subpst->dependencies
5667     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5668   subpst->dependencies[0] = pst;
5669   subpst->number_of_dependencies = 1;
5670
5671   subpst->globals_offset = 0;
5672   subpst->n_global_syms = 0;
5673   subpst->statics_offset = 0;
5674   subpst->n_static_syms = 0;
5675   subpst->compunit_symtab = NULL;
5676   subpst->read_symtab = pst->read_symtab;
5677   subpst->readin = 0;
5678
5679   /* No private part is necessary for include psymtabs.  This property
5680      can be used to differentiate between such include psymtabs and
5681      the regular ones.  */
5682   subpst->read_symtab_private = NULL;
5683 }
5684
5685 /* Read the Line Number Program data and extract the list of files
5686    included by the source file represented by PST.  Build an include
5687    partial symtab for each of these included files.  */
5688
5689 static void
5690 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5691                                struct die_info *die,
5692                                struct partial_symtab *pst)
5693 {
5694   line_header_up lh;
5695   struct attribute *attr;
5696
5697   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5698   if (attr)
5699     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5700   if (lh == NULL)
5701     return;  /* No linetable, so no includes.  */
5702
5703   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5704   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5705 }
5706
5707 static hashval_t
5708 hash_signatured_type (const void *item)
5709 {
5710   const struct signatured_type *sig_type
5711     = (const struct signatured_type *) item;
5712
5713   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5714   return sig_type->signature;
5715 }
5716
5717 static int
5718 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5719 {
5720   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5721   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5722
5723   return lhs->signature == rhs->signature;
5724 }
5725
5726 /* Allocate a hash table for signatured types.  */
5727
5728 static htab_t
5729 allocate_signatured_type_table (struct objfile *objfile)
5730 {
5731   return htab_create_alloc_ex (41,
5732                                hash_signatured_type,
5733                                eq_signatured_type,
5734                                NULL,
5735                                &objfile->objfile_obstack,
5736                                hashtab_obstack_allocate,
5737                                dummy_obstack_deallocate);
5738 }
5739
5740 /* A helper function to add a signatured type CU to a table.  */
5741
5742 static int
5743 add_signatured_type_cu_to_table (void **slot, void *datum)
5744 {
5745   struct signatured_type *sigt = (struct signatured_type *) *slot;
5746   struct signatured_type ***datap = (struct signatured_type ***) datum;
5747
5748   **datap = sigt;
5749   ++*datap;
5750
5751   return 1;
5752 }
5753
5754 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5755    and fill them into TYPES_HTAB.  It will process only type units,
5756    therefore DW_UT_type.  */
5757
5758 static void
5759 create_debug_type_hash_table (struct dwo_file *dwo_file,
5760                               dwarf2_section_info *section, htab_t &types_htab,
5761                               rcuh_kind section_kind)
5762 {
5763   struct objfile *objfile = dwarf2_per_objfile->objfile;
5764   struct dwarf2_section_info *abbrev_section;
5765   bfd *abfd;
5766   const gdb_byte *info_ptr, *end_ptr;
5767
5768   abbrev_section = (dwo_file != NULL
5769                     ? &dwo_file->sections.abbrev
5770                     : &dwarf2_per_objfile->abbrev);
5771
5772   if (dwarf_read_debug)
5773     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5774                         get_section_name (section),
5775                         get_section_file_name (abbrev_section));
5776
5777   dwarf2_read_section (objfile, section);
5778   info_ptr = section->buffer;
5779
5780   if (info_ptr == NULL)
5781     return;
5782
5783   /* We can't set abfd until now because the section may be empty or
5784      not present, in which case the bfd is unknown.  */
5785   abfd = get_section_bfd_owner (section);
5786
5787   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5788      because we don't need to read any dies: the signature is in the
5789      header.  */
5790
5791   end_ptr = info_ptr + section->size;
5792   while (info_ptr < end_ptr)
5793     {
5794       struct signatured_type *sig_type;
5795       struct dwo_unit *dwo_tu;
5796       void **slot;
5797       const gdb_byte *ptr = info_ptr;
5798       struct comp_unit_head header;
5799       unsigned int length;
5800
5801       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5802
5803       /* Initialize it due to a false compiler warning.  */
5804       header.signature = -1;
5805       header.type_cu_offset_in_tu = (cu_offset) -1;
5806
5807       /* We need to read the type's signature in order to build the hash
5808          table, but we don't need anything else just yet.  */
5809
5810       ptr = read_and_check_comp_unit_head (&header, section,
5811                                            abbrev_section, ptr, section_kind);
5812
5813       length = get_cu_length (&header);
5814
5815       /* Skip dummy type units.  */
5816       if (ptr >= info_ptr + length
5817           || peek_abbrev_code (abfd, ptr) == 0
5818           || header.unit_type != DW_UT_type)
5819         {
5820           info_ptr += length;
5821           continue;
5822         }
5823
5824       if (types_htab == NULL)
5825         {
5826           if (dwo_file)
5827             types_htab = allocate_dwo_unit_table (objfile);
5828           else
5829             types_htab = allocate_signatured_type_table (objfile);
5830         }
5831
5832       if (dwo_file)
5833         {
5834           sig_type = NULL;
5835           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5836                                    struct dwo_unit);
5837           dwo_tu->dwo_file = dwo_file;
5838           dwo_tu->signature = header.signature;
5839           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5840           dwo_tu->section = section;
5841           dwo_tu->sect_off = sect_off;
5842           dwo_tu->length = length;
5843         }
5844       else
5845         {
5846           /* N.B.: type_offset is not usable if this type uses a DWO file.
5847              The real type_offset is in the DWO file.  */
5848           dwo_tu = NULL;
5849           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5850                                      struct signatured_type);
5851           sig_type->signature = header.signature;
5852           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5853           sig_type->per_cu.objfile = objfile;
5854           sig_type->per_cu.is_debug_types = 1;
5855           sig_type->per_cu.section = section;
5856           sig_type->per_cu.sect_off = sect_off;
5857           sig_type->per_cu.length = length;
5858         }
5859
5860       slot = htab_find_slot (types_htab,
5861                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5862                              INSERT);
5863       gdb_assert (slot != NULL);
5864       if (*slot != NULL)
5865         {
5866           sect_offset dup_sect_off;
5867
5868           if (dwo_file)
5869             {
5870               const struct dwo_unit *dup_tu
5871                 = (const struct dwo_unit *) *slot;
5872
5873               dup_sect_off = dup_tu->sect_off;
5874             }
5875           else
5876             {
5877               const struct signatured_type *dup_tu
5878                 = (const struct signatured_type *) *slot;
5879
5880               dup_sect_off = dup_tu->per_cu.sect_off;
5881             }
5882
5883           complaint (&symfile_complaints,
5884                      _("debug type entry at offset 0x%x is duplicate to"
5885                        " the entry at offset 0x%x, signature %s"),
5886                      to_underlying (sect_off), to_underlying (dup_sect_off),
5887                      hex_string (header.signature));
5888         }
5889       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5890
5891       if (dwarf_read_debug > 1)
5892         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5893                             to_underlying (sect_off),
5894                             hex_string (header.signature));
5895
5896       info_ptr += length;
5897     }
5898 }
5899
5900 /* Create the hash table of all entries in the .debug_types
5901    (or .debug_types.dwo) section(s).
5902    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5903    otherwise it is NULL.
5904
5905    The result is a pointer to the hash table or NULL if there are no types.
5906
5907    Note: This function processes DWO files only, not DWP files.  */
5908
5909 static void
5910 create_debug_types_hash_table (struct dwo_file *dwo_file,
5911                                VEC (dwarf2_section_info_def) *types,
5912                                htab_t &types_htab)
5913 {
5914   int ix;
5915   struct dwarf2_section_info *section;
5916
5917   if (VEC_empty (dwarf2_section_info_def, types))
5918     return;
5919
5920   for (ix = 0;
5921        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5922        ++ix)
5923     create_debug_type_hash_table (dwo_file, section, types_htab,
5924                                   rcuh_kind::TYPE);
5925 }
5926
5927 /* Create the hash table of all entries in the .debug_types section,
5928    and initialize all_type_units.
5929    The result is zero if there is an error (e.g. missing .debug_types section),
5930    otherwise non-zero.  */
5931
5932 static int
5933 create_all_type_units (struct objfile *objfile)
5934 {
5935   htab_t types_htab = NULL;
5936   struct signatured_type **iter;
5937
5938   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5939                                 rcuh_kind::COMPILE);
5940   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5941   if (types_htab == NULL)
5942     {
5943       dwarf2_per_objfile->signatured_types = NULL;
5944       return 0;
5945     }
5946
5947   dwarf2_per_objfile->signatured_types = types_htab;
5948
5949   dwarf2_per_objfile->n_type_units
5950     = dwarf2_per_objfile->n_allocated_type_units
5951     = htab_elements (types_htab);
5952   dwarf2_per_objfile->all_type_units =
5953     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5954   iter = &dwarf2_per_objfile->all_type_units[0];
5955   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5956   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5957               == dwarf2_per_objfile->n_type_units);
5958
5959   return 1;
5960 }
5961
5962 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5963    If SLOT is non-NULL, it is the entry to use in the hash table.
5964    Otherwise we find one.  */
5965
5966 static struct signatured_type *
5967 add_type_unit (ULONGEST sig, void **slot)
5968 {
5969   struct objfile *objfile = dwarf2_per_objfile->objfile;
5970   int n_type_units = dwarf2_per_objfile->n_type_units;
5971   struct signatured_type *sig_type;
5972
5973   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5974   ++n_type_units;
5975   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5976     {
5977       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5978         dwarf2_per_objfile->n_allocated_type_units = 1;
5979       dwarf2_per_objfile->n_allocated_type_units *= 2;
5980       dwarf2_per_objfile->all_type_units
5981         = XRESIZEVEC (struct signatured_type *,
5982                       dwarf2_per_objfile->all_type_units,
5983                       dwarf2_per_objfile->n_allocated_type_units);
5984       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5985     }
5986   dwarf2_per_objfile->n_type_units = n_type_units;
5987
5988   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5989                              struct signatured_type);
5990   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5991   sig_type->signature = sig;
5992   sig_type->per_cu.is_debug_types = 1;
5993   if (dwarf2_per_objfile->using_index)
5994     {
5995       sig_type->per_cu.v.quick =
5996         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5997                         struct dwarf2_per_cu_quick_data);
5998     }
5999
6000   if (slot == NULL)
6001     {
6002       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6003                              sig_type, INSERT);
6004     }
6005   gdb_assert (*slot == NULL);
6006   *slot = sig_type;
6007   /* The rest of sig_type must be filled in by the caller.  */
6008   return sig_type;
6009 }
6010
6011 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
6012    Fill in SIG_ENTRY with DWO_ENTRY.  */
6013
6014 static void
6015 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
6016                                   struct signatured_type *sig_entry,
6017                                   struct dwo_unit *dwo_entry)
6018 {
6019   /* Make sure we're not clobbering something we don't expect to.  */
6020   gdb_assert (! sig_entry->per_cu.queued);
6021   gdb_assert (sig_entry->per_cu.cu == NULL);
6022   if (dwarf2_per_objfile->using_index)
6023     {
6024       gdb_assert (sig_entry->per_cu.v.quick != NULL);
6025       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
6026     }
6027   else
6028       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
6029   gdb_assert (sig_entry->signature == dwo_entry->signature);
6030   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
6031   gdb_assert (sig_entry->type_unit_group == NULL);
6032   gdb_assert (sig_entry->dwo_unit == NULL);
6033
6034   sig_entry->per_cu.section = dwo_entry->section;
6035   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
6036   sig_entry->per_cu.length = dwo_entry->length;
6037   sig_entry->per_cu.reading_dwo_directly = 1;
6038   sig_entry->per_cu.objfile = objfile;
6039   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
6040   sig_entry->dwo_unit = dwo_entry;
6041 }
6042
6043 /* Subroutine of lookup_signatured_type.
6044    If we haven't read the TU yet, create the signatured_type data structure
6045    for a TU to be read in directly from a DWO file, bypassing the stub.
6046    This is the "Stay in DWO Optimization": When there is no DWP file and we're
6047    using .gdb_index, then when reading a CU we want to stay in the DWO file
6048    containing that CU.  Otherwise we could end up reading several other DWO
6049    files (due to comdat folding) to process the transitive closure of all the
6050    mentioned TUs, and that can be slow.  The current DWO file will have every
6051    type signature that it needs.
6052    We only do this for .gdb_index because in the psymtab case we already have
6053    to read all the DWOs to build the type unit groups.  */
6054
6055 static struct signatured_type *
6056 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6057 {
6058   struct objfile *objfile = dwarf2_per_objfile->objfile;
6059   struct dwo_file *dwo_file;
6060   struct dwo_unit find_dwo_entry, *dwo_entry;
6061   struct signatured_type find_sig_entry, *sig_entry;
6062   void **slot;
6063
6064   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6065
6066   /* If TU skeletons have been removed then we may not have read in any
6067      TUs yet.  */
6068   if (dwarf2_per_objfile->signatured_types == NULL)
6069     {
6070       dwarf2_per_objfile->signatured_types
6071         = allocate_signatured_type_table (objfile);
6072     }
6073
6074   /* We only ever need to read in one copy of a signatured type.
6075      Use the global signatured_types array to do our own comdat-folding
6076      of types.  If this is the first time we're reading this TU, and
6077      the TU has an entry in .gdb_index, replace the recorded data from
6078      .gdb_index with this TU.  */
6079
6080   find_sig_entry.signature = sig;
6081   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6082                          &find_sig_entry, INSERT);
6083   sig_entry = (struct signatured_type *) *slot;
6084
6085   /* We can get here with the TU already read, *or* in the process of being
6086      read.  Don't reassign the global entry to point to this DWO if that's
6087      the case.  Also note that if the TU is already being read, it may not
6088      have come from a DWO, the program may be a mix of Fission-compiled
6089      code and non-Fission-compiled code.  */
6090
6091   /* Have we already tried to read this TU?
6092      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6093      needn't exist in the global table yet).  */
6094   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
6095     return sig_entry;
6096
6097   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
6098      dwo_unit of the TU itself.  */
6099   dwo_file = cu->dwo_unit->dwo_file;
6100
6101   /* Ok, this is the first time we're reading this TU.  */
6102   if (dwo_file->tus == NULL)
6103     return NULL;
6104   find_dwo_entry.signature = sig;
6105   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
6106   if (dwo_entry == NULL)
6107     return NULL;
6108
6109   /* If the global table doesn't have an entry for this TU, add one.  */
6110   if (sig_entry == NULL)
6111     sig_entry = add_type_unit (sig, slot);
6112
6113   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6114   sig_entry->per_cu.tu_read = 1;
6115   return sig_entry;
6116 }
6117
6118 /* Subroutine of lookup_signatured_type.
6119    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
6120    then try the DWP file.  If the TU stub (skeleton) has been removed then
6121    it won't be in .gdb_index.  */
6122
6123 static struct signatured_type *
6124 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6125 {
6126   struct objfile *objfile = dwarf2_per_objfile->objfile;
6127   struct dwp_file *dwp_file = get_dwp_file ();
6128   struct dwo_unit *dwo_entry;
6129   struct signatured_type find_sig_entry, *sig_entry;
6130   void **slot;
6131
6132   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
6133   gdb_assert (dwp_file != NULL);
6134
6135   /* If TU skeletons have been removed then we may not have read in any
6136      TUs yet.  */
6137   if (dwarf2_per_objfile->signatured_types == NULL)
6138     {
6139       dwarf2_per_objfile->signatured_types
6140         = allocate_signatured_type_table (objfile);
6141     }
6142
6143   find_sig_entry.signature = sig;
6144   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
6145                          &find_sig_entry, INSERT);
6146   sig_entry = (struct signatured_type *) *slot;
6147
6148   /* Have we already tried to read this TU?
6149      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
6150      needn't exist in the global table yet).  */
6151   if (sig_entry != NULL)
6152     return sig_entry;
6153
6154   if (dwp_file->tus == NULL)
6155     return NULL;
6156   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
6157                                       sig, 1 /* is_debug_types */);
6158   if (dwo_entry == NULL)
6159     return NULL;
6160
6161   sig_entry = add_type_unit (sig, slot);
6162   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
6163
6164   return sig_entry;
6165 }
6166
6167 /* Lookup a signature based type for DW_FORM_ref_sig8.
6168    Returns NULL if signature SIG is not present in the table.
6169    It is up to the caller to complain about this.  */
6170
6171 static struct signatured_type *
6172 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
6173 {
6174   if (cu->dwo_unit
6175       && dwarf2_per_objfile->using_index)
6176     {
6177       /* We're in a DWO/DWP file, and we're using .gdb_index.
6178          These cases require special processing.  */
6179       if (get_dwp_file () == NULL)
6180         return lookup_dwo_signatured_type (cu, sig);
6181       else
6182         return lookup_dwp_signatured_type (cu, sig);
6183     }
6184   else
6185     {
6186       struct signatured_type find_entry, *entry;
6187
6188       if (dwarf2_per_objfile->signatured_types == NULL)
6189         return NULL;
6190       find_entry.signature = sig;
6191       entry = ((struct signatured_type *)
6192                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
6193       return entry;
6194     }
6195 }
6196 \f
6197 /* Low level DIE reading support.  */
6198
6199 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
6200
6201 static void
6202 init_cu_die_reader (struct die_reader_specs *reader,
6203                     struct dwarf2_cu *cu,
6204                     struct dwarf2_section_info *section,
6205                     struct dwo_file *dwo_file)
6206 {
6207   gdb_assert (section->readin && section->buffer != NULL);
6208   reader->abfd = get_section_bfd_owner (section);
6209   reader->cu = cu;
6210   reader->dwo_file = dwo_file;
6211   reader->die_section = section;
6212   reader->buffer = section->buffer;
6213   reader->buffer_end = section->buffer + section->size;
6214   reader->comp_dir = NULL;
6215 }
6216
6217 /* Subroutine of init_cutu_and_read_dies to simplify it.
6218    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
6219    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
6220    already.
6221
6222    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
6223    from it to the DIE in the DWO.  If NULL we are skipping the stub.
6224    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
6225    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
6226    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
6227    STUB_COMP_DIR may be non-NULL.
6228    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
6229    are filled in with the info of the DIE from the DWO file.
6230    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
6231    provided an abbrev table to use.
6232    The result is non-zero if a valid (non-dummy) DIE was found.  */
6233
6234 static int
6235 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
6236                         struct dwo_unit *dwo_unit,
6237                         int abbrev_table_provided,
6238                         struct die_info *stub_comp_unit_die,
6239                         const char *stub_comp_dir,
6240                         struct die_reader_specs *result_reader,
6241                         const gdb_byte **result_info_ptr,
6242                         struct die_info **result_comp_unit_die,
6243                         int *result_has_children)
6244 {
6245   struct objfile *objfile = dwarf2_per_objfile->objfile;
6246   struct dwarf2_cu *cu = this_cu->cu;
6247   struct dwarf2_section_info *section;
6248   bfd *abfd;
6249   const gdb_byte *begin_info_ptr, *info_ptr;
6250   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
6251   int i,num_extra_attrs;
6252   struct dwarf2_section_info *dwo_abbrev_section;
6253   struct attribute *attr;
6254   struct die_info *comp_unit_die;
6255
6256   /* At most one of these may be provided.  */
6257   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
6258
6259   /* These attributes aren't processed until later:
6260      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
6261      DW_AT_comp_dir is used now, to find the DWO file, but it is also
6262      referenced later.  However, these attributes are found in the stub
6263      which we won't have later.  In order to not impose this complication
6264      on the rest of the code, we read them here and copy them to the
6265      DWO CU/TU die.  */
6266
6267   stmt_list = NULL;
6268   low_pc = NULL;
6269   high_pc = NULL;
6270   ranges = NULL;
6271   comp_dir = NULL;
6272
6273   if (stub_comp_unit_die != NULL)
6274     {
6275       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
6276          DWO file.  */
6277       if (! this_cu->is_debug_types)
6278         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
6279       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
6280       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
6281       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
6282       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
6283
6284       /* There should be a DW_AT_addr_base attribute here (if needed).
6285          We need the value before we can process DW_FORM_GNU_addr_index.  */
6286       cu->addr_base = 0;
6287       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
6288       if (attr)
6289         cu->addr_base = DW_UNSND (attr);
6290
6291       /* There should be a DW_AT_ranges_base attribute here (if needed).
6292          We need the value before we can process DW_AT_ranges.  */
6293       cu->ranges_base = 0;
6294       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
6295       if (attr)
6296         cu->ranges_base = DW_UNSND (attr);
6297     }
6298   else if (stub_comp_dir != NULL)
6299     {
6300       /* Reconstruct the comp_dir attribute to simplify the code below.  */
6301       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
6302       comp_dir->name = DW_AT_comp_dir;
6303       comp_dir->form = DW_FORM_string;
6304       DW_STRING_IS_CANONICAL (comp_dir) = 0;
6305       DW_STRING (comp_dir) = stub_comp_dir;
6306     }
6307
6308   /* Set up for reading the DWO CU/TU.  */
6309   cu->dwo_unit = dwo_unit;
6310   section = dwo_unit->section;
6311   dwarf2_read_section (objfile, section);
6312   abfd = get_section_bfd_owner (section);
6313   begin_info_ptr = info_ptr = (section->buffer
6314                                + to_underlying (dwo_unit->sect_off));
6315   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
6316   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
6317
6318   if (this_cu->is_debug_types)
6319     {
6320       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
6321
6322       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6323                                                 dwo_abbrev_section,
6324                                                 info_ptr, rcuh_kind::TYPE);
6325       /* This is not an assert because it can be caused by bad debug info.  */
6326       if (sig_type->signature != cu->header.signature)
6327         {
6328           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
6329                    " TU at offset 0x%x [in module %s]"),
6330                  hex_string (sig_type->signature),
6331                  hex_string (cu->header.signature),
6332                  to_underlying (dwo_unit->sect_off),
6333                  bfd_get_filename (abfd));
6334         }
6335       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6336       /* For DWOs coming from DWP files, we don't know the CU length
6337          nor the type's offset in the TU until now.  */
6338       dwo_unit->length = get_cu_length (&cu->header);
6339       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
6340
6341       /* Establish the type offset that can be used to lookup the type.
6342          For DWO files, we don't know it until now.  */
6343       sig_type->type_offset_in_section
6344         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
6345     }
6346   else
6347     {
6348       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6349                                                 dwo_abbrev_section,
6350                                                 info_ptr, rcuh_kind::COMPILE);
6351       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
6352       /* For DWOs coming from DWP files, we don't know the CU length
6353          until now.  */
6354       dwo_unit->length = get_cu_length (&cu->header);
6355     }
6356
6357   /* Replace the CU's original abbrev table with the DWO's.
6358      Reminder: We can't read the abbrev table until we've read the header.  */
6359   if (abbrev_table_provided)
6360     {
6361       /* Don't free the provided abbrev table, the caller of
6362          init_cutu_and_read_dies owns it.  */
6363       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6364       /* Ensure the DWO abbrev table gets freed.  */
6365       make_cleanup (dwarf2_free_abbrev_table, cu);
6366     }
6367   else
6368     {
6369       dwarf2_free_abbrev_table (cu);
6370       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
6371       /* Leave any existing abbrev table cleanup as is.  */
6372     }
6373
6374   /* Read in the die, but leave space to copy over the attributes
6375      from the stub.  This has the benefit of simplifying the rest of
6376      the code - all the work to maintain the illusion of a single
6377      DW_TAG_{compile,type}_unit DIE is done here.  */
6378   num_extra_attrs = ((stmt_list != NULL)
6379                      + (low_pc != NULL)
6380                      + (high_pc != NULL)
6381                      + (ranges != NULL)
6382                      + (comp_dir != NULL));
6383   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
6384                               result_has_children, num_extra_attrs);
6385
6386   /* Copy over the attributes from the stub to the DIE we just read in.  */
6387   comp_unit_die = *result_comp_unit_die;
6388   i = comp_unit_die->num_attrs;
6389   if (stmt_list != NULL)
6390     comp_unit_die->attrs[i++] = *stmt_list;
6391   if (low_pc != NULL)
6392     comp_unit_die->attrs[i++] = *low_pc;
6393   if (high_pc != NULL)
6394     comp_unit_die->attrs[i++] = *high_pc;
6395   if (ranges != NULL)
6396     comp_unit_die->attrs[i++] = *ranges;
6397   if (comp_dir != NULL)
6398     comp_unit_die->attrs[i++] = *comp_dir;
6399   comp_unit_die->num_attrs += num_extra_attrs;
6400
6401   if (dwarf_die_debug)
6402     {
6403       fprintf_unfiltered (gdb_stdlog,
6404                           "Read die from %s@0x%x of %s:\n",
6405                           get_section_name (section),
6406                           (unsigned) (begin_info_ptr - section->buffer),
6407                           bfd_get_filename (abfd));
6408       dump_die (comp_unit_die, dwarf_die_debug);
6409     }
6410
6411   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
6412      TUs by skipping the stub and going directly to the entry in the DWO file.
6413      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
6414      to get it via circuitous means.  Blech.  */
6415   if (comp_dir != NULL)
6416     result_reader->comp_dir = DW_STRING (comp_dir);
6417
6418   /* Skip dummy compilation units.  */
6419   if (info_ptr >= begin_info_ptr + dwo_unit->length
6420       || peek_abbrev_code (abfd, info_ptr) == 0)
6421     return 0;
6422
6423   *result_info_ptr = info_ptr;
6424   return 1;
6425 }
6426
6427 /* Subroutine of init_cutu_and_read_dies to simplify it.
6428    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
6429    Returns NULL if the specified DWO unit cannot be found.  */
6430
6431 static struct dwo_unit *
6432 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
6433                  struct die_info *comp_unit_die)
6434 {
6435   struct dwarf2_cu *cu = this_cu->cu;
6436   ULONGEST signature;
6437   struct dwo_unit *dwo_unit;
6438   const char *comp_dir, *dwo_name;
6439
6440   gdb_assert (cu != NULL);
6441
6442   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
6443   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6444   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6445
6446   if (this_cu->is_debug_types)
6447     {
6448       struct signatured_type *sig_type;
6449
6450       /* Since this_cu is the first member of struct signatured_type,
6451          we can go from a pointer to one to a pointer to the other.  */
6452       sig_type = (struct signatured_type *) this_cu;
6453       signature = sig_type->signature;
6454       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
6455     }
6456   else
6457     {
6458       struct attribute *attr;
6459
6460       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
6461       if (! attr)
6462         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
6463                  " [in module %s]"),
6464                dwo_name, objfile_name (this_cu->objfile));
6465       signature = DW_UNSND (attr);
6466       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
6467                                        signature);
6468     }
6469
6470   return dwo_unit;
6471 }
6472
6473 /* Subroutine of init_cutu_and_read_dies to simplify it.
6474    See it for a description of the parameters.
6475    Read a TU directly from a DWO file, bypassing the stub.
6476
6477    Note: This function could be a little bit simpler if we shared cleanups
6478    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
6479    to do, so we keep this function self-contained.  Or we could move this
6480    into our caller, but it's complex enough already.  */
6481
6482 static void
6483 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
6484                            int use_existing_cu, int keep,
6485                            die_reader_func_ftype *die_reader_func,
6486                            void *data)
6487 {
6488   struct dwarf2_cu *cu;
6489   struct signatured_type *sig_type;
6490   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6491   struct die_reader_specs reader;
6492   const gdb_byte *info_ptr;
6493   struct die_info *comp_unit_die;
6494   int has_children;
6495
6496   /* Verify we can do the following downcast, and that we have the
6497      data we need.  */
6498   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
6499   sig_type = (struct signatured_type *) this_cu;
6500   gdb_assert (sig_type->dwo_unit != NULL);
6501
6502   cleanups = make_cleanup (null_cleanup, NULL);
6503
6504   if (use_existing_cu && this_cu->cu != NULL)
6505     {
6506       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
6507       cu = this_cu->cu;
6508       /* There's no need to do the rereading_dwo_cu handling that
6509          init_cutu_and_read_dies does since we don't read the stub.  */
6510     }
6511   else
6512     {
6513       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6514       gdb_assert (this_cu->cu == NULL);
6515       cu = XNEW (struct dwarf2_cu);
6516       init_one_comp_unit (cu, this_cu);
6517       /* If an error occurs while loading, release our storage.  */
6518       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6519     }
6520
6521   /* A future optimization, if needed, would be to use an existing
6522      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
6523      could share abbrev tables.  */
6524
6525   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
6526                               0 /* abbrev_table_provided */,
6527                               NULL /* stub_comp_unit_die */,
6528                               sig_type->dwo_unit->dwo_file->comp_dir,
6529                               &reader, &info_ptr,
6530                               &comp_unit_die, &has_children) == 0)
6531     {
6532       /* Dummy die.  */
6533       do_cleanups (cleanups);
6534       return;
6535     }
6536
6537   /* All the "real" work is done here.  */
6538   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6539
6540   /* This duplicates the code in init_cutu_and_read_dies,
6541      but the alternative is making the latter more complex.
6542      This function is only for the special case of using DWO files directly:
6543      no point in overly complicating the general case just to handle this.  */
6544   if (free_cu_cleanup != NULL)
6545     {
6546       if (keep)
6547         {
6548           /* We've successfully allocated this compilation unit.  Let our
6549              caller clean it up when finished with it.  */
6550           discard_cleanups (free_cu_cleanup);
6551
6552           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6553              So we have to manually free the abbrev table.  */
6554           dwarf2_free_abbrev_table (cu);
6555
6556           /* Link this CU into read_in_chain.  */
6557           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6558           dwarf2_per_objfile->read_in_chain = this_cu;
6559         }
6560       else
6561         do_cleanups (free_cu_cleanup);
6562     }
6563
6564   do_cleanups (cleanups);
6565 }
6566
6567 /* Initialize a CU (or TU) and read its DIEs.
6568    If the CU defers to a DWO file, read the DWO file as well.
6569
6570    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
6571    Otherwise the table specified in the comp unit header is read in and used.
6572    This is an optimization for when we already have the abbrev table.
6573
6574    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
6575    Otherwise, a new CU is allocated with xmalloc.
6576
6577    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
6578    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
6579
6580    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6581    linker) then DIE_READER_FUNC will not get called.  */
6582
6583 static void
6584 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
6585                          struct abbrev_table *abbrev_table,
6586                          int use_existing_cu, int keep,
6587                          die_reader_func_ftype *die_reader_func,
6588                          void *data)
6589 {
6590   struct objfile *objfile = dwarf2_per_objfile->objfile;
6591   struct dwarf2_section_info *section = this_cu->section;
6592   bfd *abfd = get_section_bfd_owner (section);
6593   struct dwarf2_cu *cu;
6594   const gdb_byte *begin_info_ptr, *info_ptr;
6595   struct die_reader_specs reader;
6596   struct die_info *comp_unit_die;
6597   int has_children;
6598   struct attribute *attr;
6599   struct cleanup *cleanups, *free_cu_cleanup = NULL;
6600   struct signatured_type *sig_type = NULL;
6601   struct dwarf2_section_info *abbrev_section;
6602   /* Non-zero if CU currently points to a DWO file and we need to
6603      reread it.  When this happens we need to reread the skeleton die
6604      before we can reread the DWO file (this only applies to CUs, not TUs).  */
6605   int rereading_dwo_cu = 0;
6606
6607   if (dwarf_die_debug)
6608     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6609                         this_cu->is_debug_types ? "type" : "comp",
6610                         to_underlying (this_cu->sect_off));
6611
6612   if (use_existing_cu)
6613     gdb_assert (keep);
6614
6615   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6616      file (instead of going through the stub), short-circuit all of this.  */
6617   if (this_cu->reading_dwo_directly)
6618     {
6619       /* Narrow down the scope of possibilities to have to understand.  */
6620       gdb_assert (this_cu->is_debug_types);
6621       gdb_assert (abbrev_table == NULL);
6622       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6623                                  die_reader_func, data);
6624       return;
6625     }
6626
6627   cleanups = make_cleanup (null_cleanup, NULL);
6628
6629   /* This is cheap if the section is already read in.  */
6630   dwarf2_read_section (objfile, section);
6631
6632   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6633
6634   abbrev_section = get_abbrev_section_for_cu (this_cu);
6635
6636   if (use_existing_cu && this_cu->cu != NULL)
6637     {
6638       cu = this_cu->cu;
6639       /* If this CU is from a DWO file we need to start over, we need to
6640          refetch the attributes from the skeleton CU.
6641          This could be optimized by retrieving those attributes from when we
6642          were here the first time: the previous comp_unit_die was stored in
6643          comp_unit_obstack.  But there's no data yet that we need this
6644          optimization.  */
6645       if (cu->dwo_unit != NULL)
6646         rereading_dwo_cu = 1;
6647     }
6648   else
6649     {
6650       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6651       gdb_assert (this_cu->cu == NULL);
6652       cu = XNEW (struct dwarf2_cu);
6653       init_one_comp_unit (cu, this_cu);
6654       /* If an error occurs while loading, release our storage.  */
6655       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6656     }
6657
6658   /* Get the header.  */
6659   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6660     {
6661       /* We already have the header, there's no need to read it in again.  */
6662       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6663     }
6664   else
6665     {
6666       if (this_cu->is_debug_types)
6667         {
6668           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6669                                                     abbrev_section, info_ptr,
6670                                                     rcuh_kind::TYPE);
6671
6672           /* Since per_cu is the first member of struct signatured_type,
6673              we can go from a pointer to one to a pointer to the other.  */
6674           sig_type = (struct signatured_type *) this_cu;
6675           gdb_assert (sig_type->signature == cu->header.signature);
6676           gdb_assert (sig_type->type_offset_in_tu
6677                       == cu->header.type_cu_offset_in_tu);
6678           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6679
6680           /* LENGTH has not been set yet for type units if we're
6681              using .gdb_index.  */
6682           this_cu->length = get_cu_length (&cu->header);
6683
6684           /* Establish the type offset that can be used to lookup the type.  */
6685           sig_type->type_offset_in_section =
6686             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6687
6688           this_cu->dwarf_version = cu->header.version;
6689         }
6690       else
6691         {
6692           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6693                                                     abbrev_section,
6694                                                     info_ptr,
6695                                                     rcuh_kind::COMPILE);
6696
6697           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6698           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6699           this_cu->dwarf_version = cu->header.version;
6700         }
6701     }
6702
6703   /* Skip dummy compilation units.  */
6704   if (info_ptr >= begin_info_ptr + this_cu->length
6705       || peek_abbrev_code (abfd, info_ptr) == 0)
6706     {
6707       do_cleanups (cleanups);
6708       return;
6709     }
6710
6711   /* If we don't have them yet, read the abbrevs for this compilation unit.
6712      And if we need to read them now, make sure they're freed when we're
6713      done.  Note that it's important that if the CU had an abbrev table
6714      on entry we don't free it when we're done: Somewhere up the call stack
6715      it may be in use.  */
6716   if (abbrev_table != NULL)
6717     {
6718       gdb_assert (cu->abbrev_table == NULL);
6719       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6720       cu->abbrev_table = abbrev_table;
6721     }
6722   else if (cu->abbrev_table == NULL)
6723     {
6724       dwarf2_read_abbrevs (cu, abbrev_section);
6725       make_cleanup (dwarf2_free_abbrev_table, cu);
6726     }
6727   else if (rereading_dwo_cu)
6728     {
6729       dwarf2_free_abbrev_table (cu);
6730       dwarf2_read_abbrevs (cu, abbrev_section);
6731     }
6732
6733   /* Read the top level CU/TU die.  */
6734   init_cu_die_reader (&reader, cu, section, NULL);
6735   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6736
6737   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6738      from the DWO file.
6739      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6740      DWO CU, that this test will fail (the attribute will not be present).  */
6741   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6742   if (attr)
6743     {
6744       struct dwo_unit *dwo_unit;
6745       struct die_info *dwo_comp_unit_die;
6746
6747       if (has_children)
6748         {
6749           complaint (&symfile_complaints,
6750                      _("compilation unit with DW_AT_GNU_dwo_name"
6751                        " has children (offset 0x%x) [in module %s]"),
6752                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6753         }
6754       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6755       if (dwo_unit != NULL)
6756         {
6757           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6758                                       abbrev_table != NULL,
6759                                       comp_unit_die, NULL,
6760                                       &reader, &info_ptr,
6761                                       &dwo_comp_unit_die, &has_children) == 0)
6762             {
6763               /* Dummy die.  */
6764               do_cleanups (cleanups);
6765               return;
6766             }
6767           comp_unit_die = dwo_comp_unit_die;
6768         }
6769       else
6770         {
6771           /* Yikes, we couldn't find the rest of the DIE, we only have
6772              the stub.  A complaint has already been logged.  There's
6773              not much more we can do except pass on the stub DIE to
6774              die_reader_func.  We don't want to throw an error on bad
6775              debug info.  */
6776         }
6777     }
6778
6779   /* All of the above is setup for this call.  Yikes.  */
6780   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6781
6782   /* Done, clean up.  */
6783   if (free_cu_cleanup != NULL)
6784     {
6785       if (keep)
6786         {
6787           /* We've successfully allocated this compilation unit.  Let our
6788              caller clean it up when finished with it.  */
6789           discard_cleanups (free_cu_cleanup);
6790
6791           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6792              So we have to manually free the abbrev table.  */
6793           dwarf2_free_abbrev_table (cu);
6794
6795           /* Link this CU into read_in_chain.  */
6796           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6797           dwarf2_per_objfile->read_in_chain = this_cu;
6798         }
6799       else
6800         do_cleanups (free_cu_cleanup);
6801     }
6802
6803   do_cleanups (cleanups);
6804 }
6805
6806 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6807    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6808    to have already done the lookup to find the DWO file).
6809
6810    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6811    THIS_CU->is_debug_types, but nothing else.
6812
6813    We fill in THIS_CU->length.
6814
6815    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6816    linker) then DIE_READER_FUNC will not get called.
6817
6818    THIS_CU->cu is always freed when done.
6819    This is done in order to not leave THIS_CU->cu in a state where we have
6820    to care whether it refers to the "main" CU or the DWO CU.  */
6821
6822 static void
6823 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6824                                    struct dwo_file *dwo_file,
6825                                    die_reader_func_ftype *die_reader_func,
6826                                    void *data)
6827 {
6828   struct objfile *objfile = dwarf2_per_objfile->objfile;
6829   struct dwarf2_section_info *section = this_cu->section;
6830   bfd *abfd = get_section_bfd_owner (section);
6831   struct dwarf2_section_info *abbrev_section;
6832   struct dwarf2_cu cu;
6833   const gdb_byte *begin_info_ptr, *info_ptr;
6834   struct die_reader_specs reader;
6835   struct cleanup *cleanups;
6836   struct die_info *comp_unit_die;
6837   int has_children;
6838
6839   if (dwarf_die_debug)
6840     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6841                         this_cu->is_debug_types ? "type" : "comp",
6842                         to_underlying (this_cu->sect_off));
6843
6844   gdb_assert (this_cu->cu == NULL);
6845
6846   abbrev_section = (dwo_file != NULL
6847                     ? &dwo_file->sections.abbrev
6848                     : get_abbrev_section_for_cu (this_cu));
6849
6850   /* This is cheap if the section is already read in.  */
6851   dwarf2_read_section (objfile, section);
6852
6853   init_one_comp_unit (&cu, this_cu);
6854
6855   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6856
6857   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6858   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6859                                             abbrev_section, info_ptr,
6860                                             (this_cu->is_debug_types
6861                                              ? rcuh_kind::TYPE
6862                                              : rcuh_kind::COMPILE));
6863
6864   this_cu->length = get_cu_length (&cu.header);
6865
6866   /* Skip dummy compilation units.  */
6867   if (info_ptr >= begin_info_ptr + this_cu->length
6868       || peek_abbrev_code (abfd, info_ptr) == 0)
6869     {
6870       do_cleanups (cleanups);
6871       return;
6872     }
6873
6874   dwarf2_read_abbrevs (&cu, abbrev_section);
6875   make_cleanup (dwarf2_free_abbrev_table, &cu);
6876
6877   init_cu_die_reader (&reader, &cu, section, dwo_file);
6878   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6879
6880   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6881
6882   do_cleanups (cleanups);
6883 }
6884
6885 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6886    does not lookup the specified DWO file.
6887    This cannot be used to read DWO files.
6888
6889    THIS_CU->cu is always freed when done.
6890    This is done in order to not leave THIS_CU->cu in a state where we have
6891    to care whether it refers to the "main" CU or the DWO CU.
6892    We can revisit this if the data shows there's a performance issue.  */
6893
6894 static void
6895 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6896                                 die_reader_func_ftype *die_reader_func,
6897                                 void *data)
6898 {
6899   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6900 }
6901 \f
6902 /* Type Unit Groups.
6903
6904    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6905    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6906    so that all types coming from the same compilation (.o file) are grouped
6907    together.  A future step could be to put the types in the same symtab as
6908    the CU the types ultimately came from.  */
6909
6910 static hashval_t
6911 hash_type_unit_group (const void *item)
6912 {
6913   const struct type_unit_group *tu_group
6914     = (const struct type_unit_group *) item;
6915
6916   return hash_stmt_list_entry (&tu_group->hash);
6917 }
6918
6919 static int
6920 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6921 {
6922   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6923   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6924
6925   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6926 }
6927
6928 /* Allocate a hash table for type unit groups.  */
6929
6930 static htab_t
6931 allocate_type_unit_groups_table (void)
6932 {
6933   return htab_create_alloc_ex (3,
6934                                hash_type_unit_group,
6935                                eq_type_unit_group,
6936                                NULL,
6937                                &dwarf2_per_objfile->objfile->objfile_obstack,
6938                                hashtab_obstack_allocate,
6939                                dummy_obstack_deallocate);
6940 }
6941
6942 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6943    partial symtabs.  We combine several TUs per psymtab to not let the size
6944    of any one psymtab grow too big.  */
6945 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6946 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6947
6948 /* Helper routine for get_type_unit_group.
6949    Create the type_unit_group object used to hold one or more TUs.  */
6950
6951 static struct type_unit_group *
6952 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6953 {
6954   struct objfile *objfile = dwarf2_per_objfile->objfile;
6955   struct dwarf2_per_cu_data *per_cu;
6956   struct type_unit_group *tu_group;
6957
6958   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6959                              struct type_unit_group);
6960   per_cu = &tu_group->per_cu;
6961   per_cu->objfile = objfile;
6962
6963   if (dwarf2_per_objfile->using_index)
6964     {
6965       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6966                                         struct dwarf2_per_cu_quick_data);
6967     }
6968   else
6969     {
6970       unsigned int line_offset = to_underlying (line_offset_struct);
6971       struct partial_symtab *pst;
6972       char *name;
6973
6974       /* Give the symtab a useful name for debug purposes.  */
6975       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6976         name = xstrprintf ("<type_units_%d>",
6977                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6978       else
6979         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6980
6981       pst = create_partial_symtab (per_cu, name);
6982       pst->anonymous = 1;
6983
6984       xfree (name);
6985     }
6986
6987   tu_group->hash.dwo_unit = cu->dwo_unit;
6988   tu_group->hash.line_sect_off = line_offset_struct;
6989
6990   return tu_group;
6991 }
6992
6993 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6994    STMT_LIST is a DW_AT_stmt_list attribute.  */
6995
6996 static struct type_unit_group *
6997 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6998 {
6999   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7000   struct type_unit_group *tu_group;
7001   void **slot;
7002   unsigned int line_offset;
7003   struct type_unit_group type_unit_group_for_lookup;
7004
7005   if (dwarf2_per_objfile->type_unit_groups == NULL)
7006     {
7007       dwarf2_per_objfile->type_unit_groups =
7008         allocate_type_unit_groups_table ();
7009     }
7010
7011   /* Do we need to create a new group, or can we use an existing one?  */
7012
7013   if (stmt_list)
7014     {
7015       line_offset = DW_UNSND (stmt_list);
7016       ++tu_stats->nr_symtab_sharers;
7017     }
7018   else
7019     {
7020       /* Ugh, no stmt_list.  Rare, but we have to handle it.
7021          We can do various things here like create one group per TU or
7022          spread them over multiple groups to split up the expansion work.
7023          To avoid worst case scenarios (too many groups or too large groups)
7024          we, umm, group them in bunches.  */
7025       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
7026                      | (tu_stats->nr_stmt_less_type_units
7027                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
7028       ++tu_stats->nr_stmt_less_type_units;
7029     }
7030
7031   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
7032   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
7033   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
7034                          &type_unit_group_for_lookup, INSERT);
7035   if (*slot != NULL)
7036     {
7037       tu_group = (struct type_unit_group *) *slot;
7038       gdb_assert (tu_group != NULL);
7039     }
7040   else
7041     {
7042       sect_offset line_offset_struct = (sect_offset) line_offset;
7043       tu_group = create_type_unit_group (cu, line_offset_struct);
7044       *slot = tu_group;
7045       ++tu_stats->nr_symtabs;
7046     }
7047
7048   return tu_group;
7049 }
7050 \f
7051 /* Partial symbol tables.  */
7052
7053 /* Create a psymtab named NAME and assign it to PER_CU.
7054
7055    The caller must fill in the following details:
7056    dirname, textlow, texthigh.  */
7057
7058 static struct partial_symtab *
7059 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
7060 {
7061   struct objfile *objfile = per_cu->objfile;
7062   struct partial_symtab *pst;
7063
7064   pst = start_psymtab_common (objfile, name, 0,
7065                               objfile->global_psymbols,
7066                               objfile->static_psymbols);
7067
7068   pst->psymtabs_addrmap_supported = 1;
7069
7070   /* This is the glue that links PST into GDB's symbol API.  */
7071   pst->read_symtab_private = per_cu;
7072   pst->read_symtab = dwarf2_read_symtab;
7073   per_cu->v.psymtab = pst;
7074
7075   return pst;
7076 }
7077
7078 /* The DATA object passed to process_psymtab_comp_unit_reader has this
7079    type.  */
7080
7081 struct process_psymtab_comp_unit_data
7082 {
7083   /* True if we are reading a DW_TAG_partial_unit.  */
7084
7085   int want_partial_unit;
7086
7087   /* The "pretend" language that is used if the CU doesn't declare a
7088      language.  */
7089
7090   enum language pretend_language;
7091 };
7092
7093 /* die_reader_func for process_psymtab_comp_unit.  */
7094
7095 static void
7096 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
7097                                   const gdb_byte *info_ptr,
7098                                   struct die_info *comp_unit_die,
7099                                   int has_children,
7100                                   void *data)
7101 {
7102   struct dwarf2_cu *cu = reader->cu;
7103   struct objfile *objfile = cu->objfile;
7104   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7105   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7106   CORE_ADDR baseaddr;
7107   CORE_ADDR best_lowpc = 0, best_highpc = 0;
7108   struct partial_symtab *pst;
7109   enum pc_bounds_kind cu_bounds_kind;
7110   const char *filename;
7111   struct process_psymtab_comp_unit_data *info
7112     = (struct process_psymtab_comp_unit_data *) data;
7113
7114   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
7115     return;
7116
7117   gdb_assert (! per_cu->is_debug_types);
7118
7119   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
7120
7121   cu->list_in_scope = &file_symbols;
7122
7123   /* Allocate a new partial symbol table structure.  */
7124   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
7125   if (filename == NULL)
7126     filename = "";
7127
7128   pst = create_partial_symtab (per_cu, filename);
7129
7130   /* This must be done before calling dwarf2_build_include_psymtabs.  */
7131   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
7132
7133   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7134
7135   dwarf2_find_base_address (comp_unit_die, cu);
7136
7137   /* Possibly set the default values of LOWPC and HIGHPC from
7138      `DW_AT_ranges'.  */
7139   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
7140                                          &best_highpc, cu, pst);
7141   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
7142     /* Store the contiguous range if it is not empty; it can be empty for
7143        CUs with no code.  */
7144     addrmap_set_empty (objfile->psymtabs_addrmap,
7145                        gdbarch_adjust_dwarf2_addr (gdbarch,
7146                                                    best_lowpc + baseaddr),
7147                        gdbarch_adjust_dwarf2_addr (gdbarch,
7148                                                    best_highpc + baseaddr) - 1,
7149                        pst);
7150
7151   /* Check if comp unit has_children.
7152      If so, read the rest of the partial symbols from this comp unit.
7153      If not, there's no more debug_info for this comp unit.  */
7154   if (has_children)
7155     {
7156       struct partial_die_info *first_die;
7157       CORE_ADDR lowpc, highpc;
7158
7159       lowpc = ((CORE_ADDR) -1);
7160       highpc = ((CORE_ADDR) 0);
7161
7162       first_die = load_partial_dies (reader, info_ptr, 1);
7163
7164       scan_partial_symbols (first_die, &lowpc, &highpc,
7165                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
7166
7167       /* If we didn't find a lowpc, set it to highpc to avoid
7168          complaints from `maint check'.  */
7169       if (lowpc == ((CORE_ADDR) -1))
7170         lowpc = highpc;
7171
7172       /* If the compilation unit didn't have an explicit address range,
7173          then use the information extracted from its child dies.  */
7174       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
7175         {
7176           best_lowpc = lowpc;
7177           best_highpc = highpc;
7178         }
7179     }
7180   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
7181   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
7182
7183   end_psymtab_common (objfile, pst);
7184
7185   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
7186     {
7187       int i;
7188       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7189       struct dwarf2_per_cu_data *iter;
7190
7191       /* Fill in 'dependencies' here; we fill in 'users' in a
7192          post-pass.  */
7193       pst->number_of_dependencies = len;
7194       pst->dependencies =
7195         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7196       for (i = 0;
7197            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
7198                         i, iter);
7199            ++i)
7200         pst->dependencies[i] = iter->v.psymtab;
7201
7202       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
7203     }
7204
7205   /* Get the list of files included in the current compilation unit,
7206      and build a psymtab for each of them.  */
7207   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
7208
7209   if (dwarf_read_debug)
7210     {
7211       struct gdbarch *gdbarch = get_objfile_arch (objfile);
7212
7213       fprintf_unfiltered (gdb_stdlog,
7214                           "Psymtab for %s unit @0x%x: %s - %s"
7215                           ", %d global, %d static syms\n",
7216                           per_cu->is_debug_types ? "type" : "comp",
7217                           to_underlying (per_cu->sect_off),
7218                           paddress (gdbarch, pst->textlow),
7219                           paddress (gdbarch, pst->texthigh),
7220                           pst->n_global_syms, pst->n_static_syms);
7221     }
7222 }
7223
7224 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7225    Process compilation unit THIS_CU for a psymtab.  */
7226
7227 static void
7228 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
7229                            int want_partial_unit,
7230                            enum language pretend_language)
7231 {
7232   /* If this compilation unit was already read in, free the
7233      cached copy in order to read it in again.  This is
7234      necessary because we skipped some symbols when we first
7235      read in the compilation unit (see load_partial_dies).
7236      This problem could be avoided, but the benefit is unclear.  */
7237   if (this_cu->cu != NULL)
7238     free_one_cached_comp_unit (this_cu);
7239
7240   if (this_cu->is_debug_types)
7241     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
7242                              NULL);
7243   else
7244     {
7245       process_psymtab_comp_unit_data info;
7246       info.want_partial_unit = want_partial_unit;
7247       info.pretend_language = pretend_language;
7248       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
7249                                process_psymtab_comp_unit_reader, &info);
7250     }
7251
7252   /* Age out any secondary CUs.  */
7253   age_cached_comp_units ();
7254 }
7255
7256 /* Reader function for build_type_psymtabs.  */
7257
7258 static void
7259 build_type_psymtabs_reader (const struct die_reader_specs *reader,
7260                             const gdb_byte *info_ptr,
7261                             struct die_info *type_unit_die,
7262                             int has_children,
7263                             void *data)
7264 {
7265   struct objfile *objfile = dwarf2_per_objfile->objfile;
7266   struct dwarf2_cu *cu = reader->cu;
7267   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
7268   struct signatured_type *sig_type;
7269   struct type_unit_group *tu_group;
7270   struct attribute *attr;
7271   struct partial_die_info *first_die;
7272   CORE_ADDR lowpc, highpc;
7273   struct partial_symtab *pst;
7274
7275   gdb_assert (data == NULL);
7276   gdb_assert (per_cu->is_debug_types);
7277   sig_type = (struct signatured_type *) per_cu;
7278
7279   if (! has_children)
7280     return;
7281
7282   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
7283   tu_group = get_type_unit_group (cu, attr);
7284
7285   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
7286
7287   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
7288   cu->list_in_scope = &file_symbols;
7289   pst = create_partial_symtab (per_cu, "");
7290   pst->anonymous = 1;
7291
7292   first_die = load_partial_dies (reader, info_ptr, 1);
7293
7294   lowpc = (CORE_ADDR) -1;
7295   highpc = (CORE_ADDR) 0;
7296   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
7297
7298   end_psymtab_common (objfile, pst);
7299 }
7300
7301 /* Struct used to sort TUs by their abbreviation table offset.  */
7302
7303 struct tu_abbrev_offset
7304 {
7305   struct signatured_type *sig_type;
7306   sect_offset abbrev_offset;
7307 };
7308
7309 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
7310
7311 static int
7312 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
7313 {
7314   const struct tu_abbrev_offset * const *a
7315     = (const struct tu_abbrev_offset * const*) ap;
7316   const struct tu_abbrev_offset * const *b
7317     = (const struct tu_abbrev_offset * const*) bp;
7318   sect_offset aoff = (*a)->abbrev_offset;
7319   sect_offset boff = (*b)->abbrev_offset;
7320
7321   return (aoff > boff) - (aoff < boff);
7322 }
7323
7324 /* Efficiently read all the type units.
7325    This does the bulk of the work for build_type_psymtabs.
7326
7327    The efficiency is because we sort TUs by the abbrev table they use and
7328    only read each abbrev table once.  In one program there are 200K TUs
7329    sharing 8K abbrev tables.
7330
7331    The main purpose of this function is to support building the
7332    dwarf2_per_objfile->type_unit_groups table.
7333    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
7334    can collapse the search space by grouping them by stmt_list.
7335    The savings can be significant, in the same program from above the 200K TUs
7336    share 8K stmt_list tables.
7337
7338    FUNC is expected to call get_type_unit_group, which will create the
7339    struct type_unit_group if necessary and add it to
7340    dwarf2_per_objfile->type_unit_groups.  */
7341
7342 static void
7343 build_type_psymtabs_1 (void)
7344 {
7345   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7346   struct cleanup *cleanups;
7347   struct abbrev_table *abbrev_table;
7348   sect_offset abbrev_offset;
7349   struct tu_abbrev_offset *sorted_by_abbrev;
7350   int i;
7351
7352   /* It's up to the caller to not call us multiple times.  */
7353   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
7354
7355   if (dwarf2_per_objfile->n_type_units == 0)
7356     return;
7357
7358   /* TUs typically share abbrev tables, and there can be way more TUs than
7359      abbrev tables.  Sort by abbrev table to reduce the number of times we
7360      read each abbrev table in.
7361      Alternatives are to punt or to maintain a cache of abbrev tables.
7362      This is simpler and efficient enough for now.
7363
7364      Later we group TUs by their DW_AT_stmt_list value (as this defines the
7365      symtab to use).  Typically TUs with the same abbrev offset have the same
7366      stmt_list value too so in practice this should work well.
7367
7368      The basic algorithm here is:
7369
7370       sort TUs by abbrev table
7371       for each TU with same abbrev table:
7372         read abbrev table if first user
7373         read TU top level DIE
7374           [IWBN if DWO skeletons had DW_AT_stmt_list]
7375         call FUNC  */
7376
7377   if (dwarf_read_debug)
7378     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
7379
7380   /* Sort in a separate table to maintain the order of all_type_units
7381      for .gdb_index: TU indices directly index all_type_units.  */
7382   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
7383                               dwarf2_per_objfile->n_type_units);
7384   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7385     {
7386       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
7387
7388       sorted_by_abbrev[i].sig_type = sig_type;
7389       sorted_by_abbrev[i].abbrev_offset =
7390         read_abbrev_offset (sig_type->per_cu.section,
7391                             sig_type->per_cu.sect_off);
7392     }
7393   cleanups = make_cleanup (xfree, sorted_by_abbrev);
7394   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
7395          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
7396
7397   abbrev_offset = (sect_offset) ~(unsigned) 0;
7398   abbrev_table = NULL;
7399   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
7400
7401   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
7402     {
7403       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
7404
7405       /* Switch to the next abbrev table if necessary.  */
7406       if (abbrev_table == NULL
7407           || tu->abbrev_offset != abbrev_offset)
7408         {
7409           if (abbrev_table != NULL)
7410             {
7411               abbrev_table_free (abbrev_table);
7412               /* Reset to NULL in case abbrev_table_read_table throws
7413                  an error: abbrev_table_free_cleanup will get called.  */
7414               abbrev_table = NULL;
7415             }
7416           abbrev_offset = tu->abbrev_offset;
7417           abbrev_table =
7418             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
7419                                      abbrev_offset);
7420           ++tu_stats->nr_uniq_abbrev_tables;
7421         }
7422
7423       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
7424                                build_type_psymtabs_reader, NULL);
7425     }
7426
7427   do_cleanups (cleanups);
7428 }
7429
7430 /* Print collected type unit statistics.  */
7431
7432 static void
7433 print_tu_stats (void)
7434 {
7435   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
7436
7437   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
7438   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
7439                       dwarf2_per_objfile->n_type_units);
7440   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
7441                       tu_stats->nr_uniq_abbrev_tables);
7442   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
7443                       tu_stats->nr_symtabs);
7444   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
7445                       tu_stats->nr_symtab_sharers);
7446   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
7447                       tu_stats->nr_stmt_less_type_units);
7448   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
7449                       tu_stats->nr_all_type_units_reallocs);
7450 }
7451
7452 /* Traversal function for build_type_psymtabs.  */
7453
7454 static int
7455 build_type_psymtab_dependencies (void **slot, void *info)
7456 {
7457   struct objfile *objfile = dwarf2_per_objfile->objfile;
7458   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
7459   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
7460   struct partial_symtab *pst = per_cu->v.psymtab;
7461   int len = VEC_length (sig_type_ptr, tu_group->tus);
7462   struct signatured_type *iter;
7463   int i;
7464
7465   gdb_assert (len > 0);
7466   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
7467
7468   pst->number_of_dependencies = len;
7469   pst->dependencies =
7470     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
7471   for (i = 0;
7472        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
7473        ++i)
7474     {
7475       gdb_assert (iter->per_cu.is_debug_types);
7476       pst->dependencies[i] = iter->per_cu.v.psymtab;
7477       iter->type_unit_group = tu_group;
7478     }
7479
7480   VEC_free (sig_type_ptr, tu_group->tus);
7481
7482   return 1;
7483 }
7484
7485 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
7486    Build partial symbol tables for the .debug_types comp-units.  */
7487
7488 static void
7489 build_type_psymtabs (struct objfile *objfile)
7490 {
7491   if (! create_all_type_units (objfile))
7492     return;
7493
7494   build_type_psymtabs_1 ();
7495 }
7496
7497 /* Traversal function for process_skeletonless_type_unit.
7498    Read a TU in a DWO file and build partial symbols for it.  */
7499
7500 static int
7501 process_skeletonless_type_unit (void **slot, void *info)
7502 {
7503   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
7504   struct objfile *objfile = (struct objfile *) info;
7505   struct signatured_type find_entry, *entry;
7506
7507   /* If this TU doesn't exist in the global table, add it and read it in.  */
7508
7509   if (dwarf2_per_objfile->signatured_types == NULL)
7510     {
7511       dwarf2_per_objfile->signatured_types
7512         = allocate_signatured_type_table (objfile);
7513     }
7514
7515   find_entry.signature = dwo_unit->signature;
7516   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
7517                          INSERT);
7518   /* If we've already seen this type there's nothing to do.  What's happening
7519      is we're doing our own version of comdat-folding here.  */
7520   if (*slot != NULL)
7521     return 1;
7522
7523   /* This does the job that create_all_type_units would have done for
7524      this TU.  */
7525   entry = add_type_unit (dwo_unit->signature, slot);
7526   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
7527   *slot = entry;
7528
7529   /* This does the job that build_type_psymtabs_1 would have done.  */
7530   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
7531                            build_type_psymtabs_reader, NULL);
7532
7533   return 1;
7534 }
7535
7536 /* Traversal function for process_skeletonless_type_units.  */
7537
7538 static int
7539 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
7540 {
7541   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
7542
7543   if (dwo_file->tus != NULL)
7544     {
7545       htab_traverse_noresize (dwo_file->tus,
7546                               process_skeletonless_type_unit, info);
7547     }
7548
7549   return 1;
7550 }
7551
7552 /* Scan all TUs of DWO files, verifying we've processed them.
7553    This is needed in case a TU was emitted without its skeleton.
7554    Note: This can't be done until we know what all the DWO files are.  */
7555
7556 static void
7557 process_skeletonless_type_units (struct objfile *objfile)
7558 {
7559   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
7560   if (get_dwp_file () == NULL
7561       && dwarf2_per_objfile->dwo_files != NULL)
7562     {
7563       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
7564                               process_dwo_file_for_skeletonless_type_units,
7565                               objfile);
7566     }
7567 }
7568
7569 /* Compute the 'user' field for each psymtab in OBJFILE.  */
7570
7571 static void
7572 set_partial_user (struct objfile *objfile)
7573 {
7574   int i;
7575
7576   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7577     {
7578       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7579       struct partial_symtab *pst = per_cu->v.psymtab;
7580       int j;
7581
7582       if (pst == NULL)
7583         continue;
7584
7585       for (j = 0; j < pst->number_of_dependencies; ++j)
7586         {
7587           /* Set the 'user' field only if it is not already set.  */
7588           if (pst->dependencies[j]->user == NULL)
7589             pst->dependencies[j]->user = pst;
7590         }
7591     }
7592 }
7593
7594 /* Build the partial symbol table by doing a quick pass through the
7595    .debug_info and .debug_abbrev sections.  */
7596
7597 static void
7598 dwarf2_build_psymtabs_hard (struct objfile *objfile)
7599 {
7600   struct cleanup *back_to;
7601   int i;
7602
7603   if (dwarf_read_debug)
7604     {
7605       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
7606                           objfile_name (objfile));
7607     }
7608
7609   dwarf2_per_objfile->reading_partial_symbols = 1;
7610
7611   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7612
7613   /* Any cached compilation units will be linked by the per-objfile
7614      read_in_chain.  Make sure to free them when we're done.  */
7615   back_to = make_cleanup (free_cached_comp_units, NULL);
7616
7617   build_type_psymtabs (objfile);
7618
7619   create_all_comp_units (objfile);
7620
7621   /* Create a temporary address map on a temporary obstack.  We later
7622      copy this to the final obstack.  */
7623   auto_obstack temp_obstack;
7624
7625   scoped_restore save_psymtabs_addrmap
7626     = make_scoped_restore (&objfile->psymtabs_addrmap,
7627                            addrmap_create_mutable (&temp_obstack));
7628
7629   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7630     {
7631       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7632
7633       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7634     }
7635
7636   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7637   process_skeletonless_type_units (objfile);
7638
7639   /* Now that all TUs have been processed we can fill in the dependencies.  */
7640   if (dwarf2_per_objfile->type_unit_groups != NULL)
7641     {
7642       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7643                               build_type_psymtab_dependencies, NULL);
7644     }
7645
7646   if (dwarf_read_debug)
7647     print_tu_stats ();
7648
7649   set_partial_user (objfile);
7650
7651   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7652                                                     &objfile->objfile_obstack);
7653   /* At this point we want to keep the address map.  */
7654   save_psymtabs_addrmap.release ();
7655
7656   do_cleanups (back_to);
7657
7658   if (dwarf_read_debug)
7659     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7660                         objfile_name (objfile));
7661 }
7662
7663 /* die_reader_func for load_partial_comp_unit.  */
7664
7665 static void
7666 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7667                                const gdb_byte *info_ptr,
7668                                struct die_info *comp_unit_die,
7669                                int has_children,
7670                                void *data)
7671 {
7672   struct dwarf2_cu *cu = reader->cu;
7673
7674   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7675
7676   /* Check if comp unit has_children.
7677      If so, read the rest of the partial symbols from this comp unit.
7678      If not, there's no more debug_info for this comp unit.  */
7679   if (has_children)
7680     load_partial_dies (reader, info_ptr, 0);
7681 }
7682
7683 /* Load the partial DIEs for a secondary CU into memory.
7684    This is also used when rereading a primary CU with load_all_dies.  */
7685
7686 static void
7687 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7688 {
7689   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7690                            load_partial_comp_unit_reader, NULL);
7691 }
7692
7693 static void
7694 read_comp_units_from_section (struct objfile *objfile,
7695                               struct dwarf2_section_info *section,
7696                               struct dwarf2_section_info *abbrev_section,
7697                               unsigned int is_dwz,
7698                               int *n_allocated,
7699                               int *n_comp_units,
7700                               struct dwarf2_per_cu_data ***all_comp_units)
7701 {
7702   const gdb_byte *info_ptr;
7703
7704   if (dwarf_read_debug)
7705     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7706                         get_section_name (section),
7707                         get_section_file_name (section));
7708
7709   dwarf2_read_section (objfile, section);
7710
7711   info_ptr = section->buffer;
7712
7713   while (info_ptr < section->buffer + section->size)
7714     {
7715       struct dwarf2_per_cu_data *this_cu;
7716
7717       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7718
7719       comp_unit_head cu_header;
7720       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7721                                      info_ptr, rcuh_kind::COMPILE);
7722
7723       /* Save the compilation unit for later lookup.  */
7724       if (cu_header.unit_type != DW_UT_type)
7725         {
7726           this_cu = XOBNEW (&objfile->objfile_obstack,
7727                             struct dwarf2_per_cu_data);
7728           memset (this_cu, 0, sizeof (*this_cu));
7729         }
7730       else
7731         {
7732           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7733                                   struct signatured_type);
7734           memset (sig_type, 0, sizeof (*sig_type));
7735           sig_type->signature = cu_header.signature;
7736           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7737           this_cu = &sig_type->per_cu;
7738         }
7739       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7740       this_cu->sect_off = sect_off;
7741       this_cu->length = cu_header.length + cu_header.initial_length_size;
7742       this_cu->is_dwz = is_dwz;
7743       this_cu->objfile = objfile;
7744       this_cu->section = section;
7745
7746       if (*n_comp_units == *n_allocated)
7747         {
7748           *n_allocated *= 2;
7749           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7750                                         *all_comp_units, *n_allocated);
7751         }
7752       (*all_comp_units)[*n_comp_units] = this_cu;
7753       ++*n_comp_units;
7754
7755       info_ptr = info_ptr + this_cu->length;
7756     }
7757 }
7758
7759 /* Create a list of all compilation units in OBJFILE.
7760    This is only done for -readnow and building partial symtabs.  */
7761
7762 static void
7763 create_all_comp_units (struct objfile *objfile)
7764 {
7765   int n_allocated;
7766   int n_comp_units;
7767   struct dwarf2_per_cu_data **all_comp_units;
7768   struct dwz_file *dwz;
7769
7770   n_comp_units = 0;
7771   n_allocated = 10;
7772   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7773
7774   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7775                                 &dwarf2_per_objfile->abbrev, 0,
7776                                 &n_allocated, &n_comp_units, &all_comp_units);
7777
7778   dwz = dwarf2_get_dwz_file ();
7779   if (dwz != NULL)
7780     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7781                                   &n_allocated, &n_comp_units,
7782                                   &all_comp_units);
7783
7784   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7785                                                   struct dwarf2_per_cu_data *,
7786                                                   n_comp_units);
7787   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7788           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7789   xfree (all_comp_units);
7790   dwarf2_per_objfile->n_comp_units = n_comp_units;
7791 }
7792
7793 /* Process all loaded DIEs for compilation unit CU, starting at
7794    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7795    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7796    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7797    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7798
7799 static void
7800 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7801                       CORE_ADDR *highpc, int set_addrmap,
7802                       struct dwarf2_cu *cu)
7803 {
7804   struct partial_die_info *pdi;
7805
7806   /* Now, march along the PDI's, descending into ones which have
7807      interesting children but skipping the children of the other ones,
7808      until we reach the end of the compilation unit.  */
7809
7810   pdi = first_die;
7811
7812   while (pdi != NULL)
7813     {
7814       fixup_partial_die (pdi, cu);
7815
7816       /* Anonymous namespaces or modules have no name but have interesting
7817          children, so we need to look at them.  Ditto for anonymous
7818          enums.  */
7819
7820       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7821           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7822           || pdi->tag == DW_TAG_imported_unit)
7823         {
7824           switch (pdi->tag)
7825             {
7826             case DW_TAG_subprogram:
7827               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7828               break;
7829             case DW_TAG_constant:
7830             case DW_TAG_variable:
7831             case DW_TAG_typedef:
7832             case DW_TAG_union_type:
7833               if (!pdi->is_declaration)
7834                 {
7835                   add_partial_symbol (pdi, cu);
7836                 }
7837               break;
7838             case DW_TAG_class_type:
7839             case DW_TAG_interface_type:
7840             case DW_TAG_structure_type:
7841               if (!pdi->is_declaration)
7842                 {
7843                   add_partial_symbol (pdi, cu);
7844                 }
7845               if (cu->language == language_rust && pdi->has_children)
7846                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7847                                       set_addrmap, cu);
7848               break;
7849             case DW_TAG_enumeration_type:
7850               if (!pdi->is_declaration)
7851                 add_partial_enumeration (pdi, cu);
7852               break;
7853             case DW_TAG_base_type:
7854             case DW_TAG_subrange_type:
7855               /* File scope base type definitions are added to the partial
7856                  symbol table.  */
7857               add_partial_symbol (pdi, cu);
7858               break;
7859             case DW_TAG_namespace:
7860               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7861               break;
7862             case DW_TAG_module:
7863               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7864               break;
7865             case DW_TAG_imported_unit:
7866               {
7867                 struct dwarf2_per_cu_data *per_cu;
7868
7869                 /* For now we don't handle imported units in type units.  */
7870                 if (cu->per_cu->is_debug_types)
7871                   {
7872                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7873                              " supported in type units [in module %s]"),
7874                            objfile_name (cu->objfile));
7875                   }
7876
7877                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7878                                                            pdi->is_dwz,
7879                                                            cu->objfile);
7880
7881                 /* Go read the partial unit, if needed.  */
7882                 if (per_cu->v.psymtab == NULL)
7883                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7884
7885                 VEC_safe_push (dwarf2_per_cu_ptr,
7886                                cu->per_cu->imported_symtabs, per_cu);
7887               }
7888               break;
7889             case DW_TAG_imported_declaration:
7890               add_partial_symbol (pdi, cu);
7891               break;
7892             default:
7893               break;
7894             }
7895         }
7896
7897       /* If the die has a sibling, skip to the sibling.  */
7898
7899       pdi = pdi->die_sibling;
7900     }
7901 }
7902
7903 /* Functions used to compute the fully scoped name of a partial DIE.
7904
7905    Normally, this is simple.  For C++, the parent DIE's fully scoped
7906    name is concatenated with "::" and the partial DIE's name.
7907    Enumerators are an exception; they use the scope of their parent
7908    enumeration type, i.e. the name of the enumeration type is not
7909    prepended to the enumerator.
7910
7911    There are two complexities.  One is DW_AT_specification; in this
7912    case "parent" means the parent of the target of the specification,
7913    instead of the direct parent of the DIE.  The other is compilers
7914    which do not emit DW_TAG_namespace; in this case we try to guess
7915    the fully qualified name of structure types from their members'
7916    linkage names.  This must be done using the DIE's children rather
7917    than the children of any DW_AT_specification target.  We only need
7918    to do this for structures at the top level, i.e. if the target of
7919    any DW_AT_specification (if any; otherwise the DIE itself) does not
7920    have a parent.  */
7921
7922 /* Compute the scope prefix associated with PDI's parent, in
7923    compilation unit CU.  The result will be allocated on CU's
7924    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7925    field.  NULL is returned if no prefix is necessary.  */
7926 static const char *
7927 partial_die_parent_scope (struct partial_die_info *pdi,
7928                           struct dwarf2_cu *cu)
7929 {
7930   const char *grandparent_scope;
7931   struct partial_die_info *parent, *real_pdi;
7932
7933   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7934      then this means the parent of the specification DIE.  */
7935
7936   real_pdi = pdi;
7937   while (real_pdi->has_specification)
7938     real_pdi = find_partial_die (real_pdi->spec_offset,
7939                                  real_pdi->spec_is_dwz, cu);
7940
7941   parent = real_pdi->die_parent;
7942   if (parent == NULL)
7943     return NULL;
7944
7945   if (parent->scope_set)
7946     return parent->scope;
7947
7948   fixup_partial_die (parent, cu);
7949
7950   grandparent_scope = partial_die_parent_scope (parent, cu);
7951
7952   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7953      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7954      Work around this problem here.  */
7955   if (cu->language == language_cplus
7956       && parent->tag == DW_TAG_namespace
7957       && strcmp (parent->name, "::") == 0
7958       && grandparent_scope == NULL)
7959     {
7960       parent->scope = NULL;
7961       parent->scope_set = 1;
7962       return NULL;
7963     }
7964
7965   if (pdi->tag == DW_TAG_enumerator)
7966     /* Enumerators should not get the name of the enumeration as a prefix.  */
7967     parent->scope = grandparent_scope;
7968   else if (parent->tag == DW_TAG_namespace
7969       || parent->tag == DW_TAG_module
7970       || parent->tag == DW_TAG_structure_type
7971       || parent->tag == DW_TAG_class_type
7972       || parent->tag == DW_TAG_interface_type
7973       || parent->tag == DW_TAG_union_type
7974       || parent->tag == DW_TAG_enumeration_type)
7975     {
7976       if (grandparent_scope == NULL)
7977         parent->scope = parent->name;
7978       else
7979         parent->scope = typename_concat (&cu->comp_unit_obstack,
7980                                          grandparent_scope,
7981                                          parent->name, 0, cu);
7982     }
7983   else
7984     {
7985       /* FIXME drow/2004-04-01: What should we be doing with
7986          function-local names?  For partial symbols, we should probably be
7987          ignoring them.  */
7988       complaint (&symfile_complaints,
7989                  _("unhandled containing DIE tag %d for DIE at %d"),
7990                  parent->tag, to_underlying (pdi->sect_off));
7991       parent->scope = grandparent_scope;
7992     }
7993
7994   parent->scope_set = 1;
7995   return parent->scope;
7996 }
7997
7998 /* Return the fully scoped name associated with PDI, from compilation unit
7999    CU.  The result will be allocated with malloc.  */
8000
8001 static char *
8002 partial_die_full_name (struct partial_die_info *pdi,
8003                        struct dwarf2_cu *cu)
8004 {
8005   const char *parent_scope;
8006
8007   /* If this is a template instantiation, we can not work out the
8008      template arguments from partial DIEs.  So, unfortunately, we have
8009      to go through the full DIEs.  At least any work we do building
8010      types here will be reused if full symbols are loaded later.  */
8011   if (pdi->has_template_arguments)
8012     {
8013       fixup_partial_die (pdi, cu);
8014
8015       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
8016         {
8017           struct die_info *die;
8018           struct attribute attr;
8019           struct dwarf2_cu *ref_cu = cu;
8020
8021           /* DW_FORM_ref_addr is using section offset.  */
8022           attr.name = (enum dwarf_attribute) 0;
8023           attr.form = DW_FORM_ref_addr;
8024           attr.u.unsnd = to_underlying (pdi->sect_off);
8025           die = follow_die_ref (NULL, &attr, &ref_cu);
8026
8027           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
8028         }
8029     }
8030
8031   parent_scope = partial_die_parent_scope (pdi, cu);
8032   if (parent_scope == NULL)
8033     return NULL;
8034   else
8035     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
8036 }
8037
8038 static void
8039 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
8040 {
8041   struct objfile *objfile = cu->objfile;
8042   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8043   CORE_ADDR addr = 0;
8044   const char *actual_name = NULL;
8045   CORE_ADDR baseaddr;
8046   char *built_actual_name;
8047
8048   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8049
8050   built_actual_name = partial_die_full_name (pdi, cu);
8051   if (built_actual_name != NULL)
8052     actual_name = built_actual_name;
8053
8054   if (actual_name == NULL)
8055     actual_name = pdi->name;
8056
8057   switch (pdi->tag)
8058     {
8059     case DW_TAG_subprogram:
8060       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
8061       if (pdi->is_external || cu->language == language_ada)
8062         {
8063           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
8064              of the global scope.  But in Ada, we want to be able to access
8065              nested procedures globally.  So all Ada subprograms are stored
8066              in the global scope.  */
8067           add_psymbol_to_list (actual_name, strlen (actual_name),
8068                                built_actual_name != NULL,
8069                                VAR_DOMAIN, LOC_BLOCK,
8070                                &objfile->global_psymbols,
8071                                addr, cu->language, objfile);
8072         }
8073       else
8074         {
8075           add_psymbol_to_list (actual_name, strlen (actual_name),
8076                                built_actual_name != NULL,
8077                                VAR_DOMAIN, LOC_BLOCK,
8078                                &objfile->static_psymbols,
8079                                addr, cu->language, objfile);
8080         }
8081
8082       if (pdi->main_subprogram && actual_name != NULL)
8083         set_objfile_main_name (objfile, actual_name, cu->language);
8084       break;
8085     case DW_TAG_constant:
8086       {
8087         std::vector<partial_symbol *> *list;
8088
8089         if (pdi->is_external)
8090           list = &objfile->global_psymbols;
8091         else
8092           list = &objfile->static_psymbols;
8093         add_psymbol_to_list (actual_name, strlen (actual_name),
8094                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
8095                              list, 0, cu->language, objfile);
8096       }
8097       break;
8098     case DW_TAG_variable:
8099       if (pdi->d.locdesc)
8100         addr = decode_locdesc (pdi->d.locdesc, cu);
8101
8102       if (pdi->d.locdesc
8103           && addr == 0
8104           && !dwarf2_per_objfile->has_section_at_zero)
8105         {
8106           /* A global or static variable may also have been stripped
8107              out by the linker if unused, in which case its address
8108              will be nullified; do not add such variables into partial
8109              symbol table then.  */
8110         }
8111       else if (pdi->is_external)
8112         {
8113           /* Global Variable.
8114              Don't enter into the minimal symbol tables as there is
8115              a minimal symbol table entry from the ELF symbols already.
8116              Enter into partial symbol table if it has a location
8117              descriptor or a type.
8118              If the location descriptor is missing, new_symbol will create
8119              a LOC_UNRESOLVED symbol, the address of the variable will then
8120              be determined from the minimal symbol table whenever the variable
8121              is referenced.
8122              The address for the partial symbol table entry is not
8123              used by GDB, but it comes in handy for debugging partial symbol
8124              table building.  */
8125
8126           if (pdi->d.locdesc || pdi->has_type)
8127             add_psymbol_to_list (actual_name, strlen (actual_name),
8128                                  built_actual_name != NULL,
8129                                  VAR_DOMAIN, LOC_STATIC,
8130                                  &objfile->global_psymbols,
8131                                  addr + baseaddr,
8132                                  cu->language, objfile);
8133         }
8134       else
8135         {
8136           int has_loc = pdi->d.locdesc != NULL;
8137
8138           /* Static Variable.  Skip symbols whose value we cannot know (those
8139              without location descriptors or constant values).  */
8140           if (!has_loc && !pdi->has_const_value)
8141             {
8142               xfree (built_actual_name);
8143               return;
8144             }
8145
8146           add_psymbol_to_list (actual_name, strlen (actual_name),
8147                                built_actual_name != NULL,
8148                                VAR_DOMAIN, LOC_STATIC,
8149                                &objfile->static_psymbols,
8150                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
8151                                cu->language, objfile);
8152         }
8153       break;
8154     case DW_TAG_typedef:
8155     case DW_TAG_base_type:
8156     case DW_TAG_subrange_type:
8157       add_psymbol_to_list (actual_name, strlen (actual_name),
8158                            built_actual_name != NULL,
8159                            VAR_DOMAIN, LOC_TYPEDEF,
8160                            &objfile->static_psymbols,
8161                            0, cu->language, objfile);
8162       break;
8163     case DW_TAG_imported_declaration:
8164     case DW_TAG_namespace:
8165       add_psymbol_to_list (actual_name, strlen (actual_name),
8166                            built_actual_name != NULL,
8167                            VAR_DOMAIN, LOC_TYPEDEF,
8168                            &objfile->global_psymbols,
8169                            0, cu->language, objfile);
8170       break;
8171     case DW_TAG_module:
8172       add_psymbol_to_list (actual_name, strlen (actual_name),
8173                            built_actual_name != NULL,
8174                            MODULE_DOMAIN, LOC_TYPEDEF,
8175                            &objfile->global_psymbols,
8176                            0, cu->language, objfile);
8177       break;
8178     case DW_TAG_class_type:
8179     case DW_TAG_interface_type:
8180     case DW_TAG_structure_type:
8181     case DW_TAG_union_type:
8182     case DW_TAG_enumeration_type:
8183       /* Skip external references.  The DWARF standard says in the section
8184          about "Structure, Union, and Class Type Entries": "An incomplete
8185          structure, union or class type is represented by a structure,
8186          union or class entry that does not have a byte size attribute
8187          and that has a DW_AT_declaration attribute."  */
8188       if (!pdi->has_byte_size && pdi->is_declaration)
8189         {
8190           xfree (built_actual_name);
8191           return;
8192         }
8193
8194       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
8195          static vs. global.  */
8196       add_psymbol_to_list (actual_name, strlen (actual_name),
8197                            built_actual_name != NULL,
8198                            STRUCT_DOMAIN, LOC_TYPEDEF,
8199                            cu->language == language_cplus
8200                            ? &objfile->global_psymbols
8201                            : &objfile->static_psymbols,
8202                            0, cu->language, objfile);
8203
8204       break;
8205     case DW_TAG_enumerator:
8206       add_psymbol_to_list (actual_name, strlen (actual_name),
8207                            built_actual_name != NULL,
8208                            VAR_DOMAIN, LOC_CONST,
8209                            cu->language == language_cplus
8210                            ? &objfile->global_psymbols
8211                            : &objfile->static_psymbols,
8212                            0, cu->language, objfile);
8213       break;
8214     default:
8215       break;
8216     }
8217
8218   xfree (built_actual_name);
8219 }
8220
8221 /* Read a partial die corresponding to a namespace; also, add a symbol
8222    corresponding to that namespace to the symbol table.  NAMESPACE is
8223    the name of the enclosing namespace.  */
8224
8225 static void
8226 add_partial_namespace (struct partial_die_info *pdi,
8227                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
8228                        int set_addrmap, struct dwarf2_cu *cu)
8229 {
8230   /* Add a symbol for the namespace.  */
8231
8232   add_partial_symbol (pdi, cu);
8233
8234   /* Now scan partial symbols in that namespace.  */
8235
8236   if (pdi->has_children)
8237     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8238 }
8239
8240 /* Read a partial die corresponding to a Fortran module.  */
8241
8242 static void
8243 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
8244                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
8245 {
8246   /* Add a symbol for the namespace.  */
8247
8248   add_partial_symbol (pdi, cu);
8249
8250   /* Now scan partial symbols in that module.  */
8251
8252   if (pdi->has_children)
8253     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
8254 }
8255
8256 /* Read a partial die corresponding to a subprogram and create a partial
8257    symbol for that subprogram.  When the CU language allows it, this
8258    routine also defines a partial symbol for each nested subprogram
8259    that this subprogram contains.  If SET_ADDRMAP is true, record the
8260    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
8261    and highest PC values found in PDI.
8262
8263    PDI may also be a lexical block, in which case we simply search
8264    recursively for subprograms defined inside that lexical block.
8265    Again, this is only performed when the CU language allows this
8266    type of definitions.  */
8267
8268 static void
8269 add_partial_subprogram (struct partial_die_info *pdi,
8270                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
8271                         int set_addrmap, struct dwarf2_cu *cu)
8272 {
8273   if (pdi->tag == DW_TAG_subprogram)
8274     {
8275       if (pdi->has_pc_info)
8276         {
8277           if (pdi->lowpc < *lowpc)
8278             *lowpc = pdi->lowpc;
8279           if (pdi->highpc > *highpc)
8280             *highpc = pdi->highpc;
8281           if (set_addrmap)
8282             {
8283               struct objfile *objfile = cu->objfile;
8284               struct gdbarch *gdbarch = get_objfile_arch (objfile);
8285               CORE_ADDR baseaddr;
8286               CORE_ADDR highpc;
8287               CORE_ADDR lowpc;
8288
8289               baseaddr = ANOFFSET (objfile->section_offsets,
8290                                    SECT_OFF_TEXT (objfile));
8291               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8292                                                   pdi->lowpc + baseaddr);
8293               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
8294                                                    pdi->highpc + baseaddr);
8295               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
8296                                  cu->per_cu->v.psymtab);
8297             }
8298         }
8299
8300       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
8301         {
8302           if (!pdi->is_declaration)
8303             /* Ignore subprogram DIEs that do not have a name, they are
8304                illegal.  Do not emit a complaint at this point, we will
8305                do so when we convert this psymtab into a symtab.  */
8306             if (pdi->name)
8307               add_partial_symbol (pdi, cu);
8308         }
8309     }
8310
8311   if (! pdi->has_children)
8312     return;
8313
8314   if (cu->language == language_ada)
8315     {
8316       pdi = pdi->die_child;
8317       while (pdi != NULL)
8318         {
8319           fixup_partial_die (pdi, cu);
8320           if (pdi->tag == DW_TAG_subprogram
8321               || pdi->tag == DW_TAG_lexical_block)
8322             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
8323           pdi = pdi->die_sibling;
8324         }
8325     }
8326 }
8327
8328 /* Read a partial die corresponding to an enumeration type.  */
8329
8330 static void
8331 add_partial_enumeration (struct partial_die_info *enum_pdi,
8332                          struct dwarf2_cu *cu)
8333 {
8334   struct partial_die_info *pdi;
8335
8336   if (enum_pdi->name != NULL)
8337     add_partial_symbol (enum_pdi, cu);
8338
8339   pdi = enum_pdi->die_child;
8340   while (pdi)
8341     {
8342       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
8343         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
8344       else
8345         add_partial_symbol (pdi, cu);
8346       pdi = pdi->die_sibling;
8347     }
8348 }
8349
8350 /* Return the initial uleb128 in the die at INFO_PTR.  */
8351
8352 static unsigned int
8353 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
8354 {
8355   unsigned int bytes_read;
8356
8357   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8358 }
8359
8360 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
8361    Return the corresponding abbrev, or NULL if the number is zero (indicating
8362    an empty DIE).  In either case *BYTES_READ will be set to the length of
8363    the initial number.  */
8364
8365 static struct abbrev_info *
8366 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
8367                  struct dwarf2_cu *cu)
8368 {
8369   bfd *abfd = cu->objfile->obfd;
8370   unsigned int abbrev_number;
8371   struct abbrev_info *abbrev;
8372
8373   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
8374
8375   if (abbrev_number == 0)
8376     return NULL;
8377
8378   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
8379   if (!abbrev)
8380     {
8381       error (_("Dwarf Error: Could not find abbrev number %d in %s"
8382                " at offset 0x%x [in module %s]"),
8383              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
8384              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
8385     }
8386
8387   return abbrev;
8388 }
8389
8390 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8391    Returns a pointer to the end of a series of DIEs, terminated by an empty
8392    DIE.  Any children of the skipped DIEs will also be skipped.  */
8393
8394 static const gdb_byte *
8395 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
8396 {
8397   struct dwarf2_cu *cu = reader->cu;
8398   struct abbrev_info *abbrev;
8399   unsigned int bytes_read;
8400
8401   while (1)
8402     {
8403       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
8404       if (abbrev == NULL)
8405         return info_ptr + bytes_read;
8406       else
8407         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
8408     }
8409 }
8410
8411 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
8412    INFO_PTR should point just after the initial uleb128 of a DIE, and the
8413    abbrev corresponding to that skipped uleb128 should be passed in
8414    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
8415    children.  */
8416
8417 static const gdb_byte *
8418 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
8419               struct abbrev_info *abbrev)
8420 {
8421   unsigned int bytes_read;
8422   struct attribute attr;
8423   bfd *abfd = reader->abfd;
8424   struct dwarf2_cu *cu = reader->cu;
8425   const gdb_byte *buffer = reader->buffer;
8426   const gdb_byte *buffer_end = reader->buffer_end;
8427   unsigned int form, i;
8428
8429   for (i = 0; i < abbrev->num_attrs; i++)
8430     {
8431       /* The only abbrev we care about is DW_AT_sibling.  */
8432       if (abbrev->attrs[i].name == DW_AT_sibling)
8433         {
8434           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
8435           if (attr.form == DW_FORM_ref_addr)
8436             complaint (&symfile_complaints,
8437                        _("ignoring absolute DW_AT_sibling"));
8438           else
8439             {
8440               sect_offset off = dwarf2_get_ref_die_offset (&attr);
8441               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
8442
8443               if (sibling_ptr < info_ptr)
8444                 complaint (&symfile_complaints,
8445                            _("DW_AT_sibling points backwards"));
8446               else if (sibling_ptr > reader->buffer_end)
8447                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
8448               else
8449                 return sibling_ptr;
8450             }
8451         }
8452
8453       /* If it isn't DW_AT_sibling, skip this attribute.  */
8454       form = abbrev->attrs[i].form;
8455     skip_attribute:
8456       switch (form)
8457         {
8458         case DW_FORM_ref_addr:
8459           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
8460              and later it is offset sized.  */
8461           if (cu->header.version == 2)
8462             info_ptr += cu->header.addr_size;
8463           else
8464             info_ptr += cu->header.offset_size;
8465           break;
8466         case DW_FORM_GNU_ref_alt:
8467           info_ptr += cu->header.offset_size;
8468           break;
8469         case DW_FORM_addr:
8470           info_ptr += cu->header.addr_size;
8471           break;
8472         case DW_FORM_data1:
8473         case DW_FORM_ref1:
8474         case DW_FORM_flag:
8475           info_ptr += 1;
8476           break;
8477         case DW_FORM_flag_present:
8478         case DW_FORM_implicit_const:
8479           break;
8480         case DW_FORM_data2:
8481         case DW_FORM_ref2:
8482           info_ptr += 2;
8483           break;
8484         case DW_FORM_data4:
8485         case DW_FORM_ref4:
8486           info_ptr += 4;
8487           break;
8488         case DW_FORM_data8:
8489         case DW_FORM_ref8:
8490         case DW_FORM_ref_sig8:
8491           info_ptr += 8;
8492           break;
8493         case DW_FORM_data16:
8494           info_ptr += 16;
8495           break;
8496         case DW_FORM_string:
8497           read_direct_string (abfd, info_ptr, &bytes_read);
8498           info_ptr += bytes_read;
8499           break;
8500         case DW_FORM_sec_offset:
8501         case DW_FORM_strp:
8502         case DW_FORM_GNU_strp_alt:
8503           info_ptr += cu->header.offset_size;
8504           break;
8505         case DW_FORM_exprloc:
8506         case DW_FORM_block:
8507           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8508           info_ptr += bytes_read;
8509           break;
8510         case DW_FORM_block1:
8511           info_ptr += 1 + read_1_byte (abfd, info_ptr);
8512           break;
8513         case DW_FORM_block2:
8514           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
8515           break;
8516         case DW_FORM_block4:
8517           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
8518           break;
8519         case DW_FORM_sdata:
8520         case DW_FORM_udata:
8521         case DW_FORM_ref_udata:
8522         case DW_FORM_GNU_addr_index:
8523         case DW_FORM_GNU_str_index:
8524           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
8525           break;
8526         case DW_FORM_indirect:
8527           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
8528           info_ptr += bytes_read;
8529           /* We need to continue parsing from here, so just go back to
8530              the top.  */
8531           goto skip_attribute;
8532
8533         default:
8534           error (_("Dwarf Error: Cannot handle %s "
8535                    "in DWARF reader [in module %s]"),
8536                  dwarf_form_name (form),
8537                  bfd_get_filename (abfd));
8538         }
8539     }
8540
8541   if (abbrev->has_children)
8542     return skip_children (reader, info_ptr);
8543   else
8544     return info_ptr;
8545 }
8546
8547 /* Locate ORIG_PDI's sibling.
8548    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
8549
8550 static const gdb_byte *
8551 locate_pdi_sibling (const struct die_reader_specs *reader,
8552                     struct partial_die_info *orig_pdi,
8553                     const gdb_byte *info_ptr)
8554 {
8555   /* Do we know the sibling already?  */
8556
8557   if (orig_pdi->sibling)
8558     return orig_pdi->sibling;
8559
8560   /* Are there any children to deal with?  */
8561
8562   if (!orig_pdi->has_children)
8563     return info_ptr;
8564
8565   /* Skip the children the long way.  */
8566
8567   return skip_children (reader, info_ptr);
8568 }
8569
8570 /* Expand this partial symbol table into a full symbol table.  SELF is
8571    not NULL.  */
8572
8573 static void
8574 dwarf2_read_symtab (struct partial_symtab *self,
8575                     struct objfile *objfile)
8576 {
8577   if (self->readin)
8578     {
8579       warning (_("bug: psymtab for %s is already read in."),
8580                self->filename);
8581     }
8582   else
8583     {
8584       if (info_verbose)
8585         {
8586           printf_filtered (_("Reading in symbols for %s..."),
8587                            self->filename);
8588           gdb_flush (gdb_stdout);
8589         }
8590
8591       /* Restore our global data.  */
8592       dwarf2_per_objfile
8593         = (struct dwarf2_per_objfile *) objfile_data (objfile,
8594                                                       dwarf2_objfile_data_key);
8595
8596       /* If this psymtab is constructed from a debug-only objfile, the
8597          has_section_at_zero flag will not necessarily be correct.  We
8598          can get the correct value for this flag by looking at the data
8599          associated with the (presumably stripped) associated objfile.  */
8600       if (objfile->separate_debug_objfile_backlink)
8601         {
8602           struct dwarf2_per_objfile *dpo_backlink
8603             = ((struct dwarf2_per_objfile *)
8604                objfile_data (objfile->separate_debug_objfile_backlink,
8605                              dwarf2_objfile_data_key));
8606
8607           dwarf2_per_objfile->has_section_at_zero
8608             = dpo_backlink->has_section_at_zero;
8609         }
8610
8611       dwarf2_per_objfile->reading_partial_symbols = 0;
8612
8613       psymtab_to_symtab_1 (self);
8614
8615       /* Finish up the debug error message.  */
8616       if (info_verbose)
8617         printf_filtered (_("done.\n"));
8618     }
8619
8620   process_cu_includes ();
8621 }
8622 \f
8623 /* Reading in full CUs.  */
8624
8625 /* Add PER_CU to the queue.  */
8626
8627 static void
8628 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8629                  enum language pretend_language)
8630 {
8631   struct dwarf2_queue_item *item;
8632
8633   per_cu->queued = 1;
8634   item = XNEW (struct dwarf2_queue_item);
8635   item->per_cu = per_cu;
8636   item->pretend_language = pretend_language;
8637   item->next = NULL;
8638
8639   if (dwarf2_queue == NULL)
8640     dwarf2_queue = item;
8641   else
8642     dwarf2_queue_tail->next = item;
8643
8644   dwarf2_queue_tail = item;
8645 }
8646
8647 /* If PER_CU is not yet queued, add it to the queue.
8648    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8649    dependency.
8650    The result is non-zero if PER_CU was queued, otherwise the result is zero
8651    meaning either PER_CU is already queued or it is already loaded.
8652
8653    N.B. There is an invariant here that if a CU is queued then it is loaded.
8654    The caller is required to load PER_CU if we return non-zero.  */
8655
8656 static int
8657 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8658                        struct dwarf2_per_cu_data *per_cu,
8659                        enum language pretend_language)
8660 {
8661   /* We may arrive here during partial symbol reading, if we need full
8662      DIEs to process an unusual case (e.g. template arguments).  Do
8663      not queue PER_CU, just tell our caller to load its DIEs.  */
8664   if (dwarf2_per_objfile->reading_partial_symbols)
8665     {
8666       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8667         return 1;
8668       return 0;
8669     }
8670
8671   /* Mark the dependence relation so that we don't flush PER_CU
8672      too early.  */
8673   if (dependent_cu != NULL)
8674     dwarf2_add_dependence (dependent_cu, per_cu);
8675
8676   /* If it's already on the queue, we have nothing to do.  */
8677   if (per_cu->queued)
8678     return 0;
8679
8680   /* If the compilation unit is already loaded, just mark it as
8681      used.  */
8682   if (per_cu->cu != NULL)
8683     {
8684       per_cu->cu->last_used = 0;
8685       return 0;
8686     }
8687
8688   /* Add it to the queue.  */
8689   queue_comp_unit (per_cu, pretend_language);
8690
8691   return 1;
8692 }
8693
8694 /* Process the queue.  */
8695
8696 static void
8697 process_queue (void)
8698 {
8699   struct dwarf2_queue_item *item, *next_item;
8700
8701   if (dwarf_read_debug)
8702     {
8703       fprintf_unfiltered (gdb_stdlog,
8704                           "Expanding one or more symtabs of objfile %s ...\n",
8705                           objfile_name (dwarf2_per_objfile->objfile));
8706     }
8707
8708   /* The queue starts out with one item, but following a DIE reference
8709      may load a new CU, adding it to the end of the queue.  */
8710   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8711     {
8712       if ((dwarf2_per_objfile->using_index
8713            ? !item->per_cu->v.quick->compunit_symtab
8714            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8715           /* Skip dummy CUs.  */
8716           && item->per_cu->cu != NULL)
8717         {
8718           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8719           unsigned int debug_print_threshold;
8720           char buf[100];
8721
8722           if (per_cu->is_debug_types)
8723             {
8724               struct signatured_type *sig_type =
8725                 (struct signatured_type *) per_cu;
8726
8727               sprintf (buf, "TU %s at offset 0x%x",
8728                        hex_string (sig_type->signature),
8729                        to_underlying (per_cu->sect_off));
8730               /* There can be 100s of TUs.
8731                  Only print them in verbose mode.  */
8732               debug_print_threshold = 2;
8733             }
8734           else
8735             {
8736               sprintf (buf, "CU at offset 0x%x",
8737                        to_underlying (per_cu->sect_off));
8738               debug_print_threshold = 1;
8739             }
8740
8741           if (dwarf_read_debug >= debug_print_threshold)
8742             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8743
8744           if (per_cu->is_debug_types)
8745             process_full_type_unit (per_cu, item->pretend_language);
8746           else
8747             process_full_comp_unit (per_cu, item->pretend_language);
8748
8749           if (dwarf_read_debug >= debug_print_threshold)
8750             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8751         }
8752
8753       item->per_cu->queued = 0;
8754       next_item = item->next;
8755       xfree (item);
8756     }
8757
8758   dwarf2_queue_tail = NULL;
8759
8760   if (dwarf_read_debug)
8761     {
8762       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8763                           objfile_name (dwarf2_per_objfile->objfile));
8764     }
8765 }
8766
8767 /* Free all allocated queue entries.  This function only releases anything if
8768    an error was thrown; if the queue was processed then it would have been
8769    freed as we went along.  */
8770
8771 static void
8772 dwarf2_release_queue (void *dummy)
8773 {
8774   struct dwarf2_queue_item *item, *last;
8775
8776   item = dwarf2_queue;
8777   while (item)
8778     {
8779       /* Anything still marked queued is likely to be in an
8780          inconsistent state, so discard it.  */
8781       if (item->per_cu->queued)
8782         {
8783           if (item->per_cu->cu != NULL)
8784             free_one_cached_comp_unit (item->per_cu);
8785           item->per_cu->queued = 0;
8786         }
8787
8788       last = item;
8789       item = item->next;
8790       xfree (last);
8791     }
8792
8793   dwarf2_queue = dwarf2_queue_tail = NULL;
8794 }
8795
8796 /* Read in full symbols for PST, and anything it depends on.  */
8797
8798 static void
8799 psymtab_to_symtab_1 (struct partial_symtab *pst)
8800 {
8801   struct dwarf2_per_cu_data *per_cu;
8802   int i;
8803
8804   if (pst->readin)
8805     return;
8806
8807   for (i = 0; i < pst->number_of_dependencies; i++)
8808     if (!pst->dependencies[i]->readin
8809         && pst->dependencies[i]->user == NULL)
8810       {
8811         /* Inform about additional files that need to be read in.  */
8812         if (info_verbose)
8813           {
8814             /* FIXME: i18n: Need to make this a single string.  */
8815             fputs_filtered (" ", gdb_stdout);
8816             wrap_here ("");
8817             fputs_filtered ("and ", gdb_stdout);
8818             wrap_here ("");
8819             printf_filtered ("%s...", pst->dependencies[i]->filename);
8820             wrap_here ("");     /* Flush output.  */
8821             gdb_flush (gdb_stdout);
8822           }
8823         psymtab_to_symtab_1 (pst->dependencies[i]);
8824       }
8825
8826   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8827
8828   if (per_cu == NULL)
8829     {
8830       /* It's an include file, no symbols to read for it.
8831          Everything is in the parent symtab.  */
8832       pst->readin = 1;
8833       return;
8834     }
8835
8836   dw2_do_instantiate_symtab (per_cu);
8837 }
8838
8839 /* Trivial hash function for die_info: the hash value of a DIE
8840    is its offset in .debug_info for this objfile.  */
8841
8842 static hashval_t
8843 die_hash (const void *item)
8844 {
8845   const struct die_info *die = (const struct die_info *) item;
8846
8847   return to_underlying (die->sect_off);
8848 }
8849
8850 /* Trivial comparison function for die_info structures: two DIEs
8851    are equal if they have the same offset.  */
8852
8853 static int
8854 die_eq (const void *item_lhs, const void *item_rhs)
8855 {
8856   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8857   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8858
8859   return die_lhs->sect_off == die_rhs->sect_off;
8860 }
8861
8862 /* die_reader_func for load_full_comp_unit.
8863    This is identical to read_signatured_type_reader,
8864    but is kept separate for now.  */
8865
8866 static void
8867 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8868                             const gdb_byte *info_ptr,
8869                             struct die_info *comp_unit_die,
8870                             int has_children,
8871                             void *data)
8872 {
8873   struct dwarf2_cu *cu = reader->cu;
8874   enum language *language_ptr = (enum language *) data;
8875
8876   gdb_assert (cu->die_hash == NULL);
8877   cu->die_hash =
8878     htab_create_alloc_ex (cu->header.length / 12,
8879                           die_hash,
8880                           die_eq,
8881                           NULL,
8882                           &cu->comp_unit_obstack,
8883                           hashtab_obstack_allocate,
8884                           dummy_obstack_deallocate);
8885
8886   if (has_children)
8887     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8888                                                   &info_ptr, comp_unit_die);
8889   cu->dies = comp_unit_die;
8890   /* comp_unit_die is not stored in die_hash, no need.  */
8891
8892   /* We try not to read any attributes in this function, because not
8893      all CUs needed for references have been loaded yet, and symbol
8894      table processing isn't initialized.  But we have to set the CU language,
8895      or we won't be able to build types correctly.
8896      Similarly, if we do not read the producer, we can not apply
8897      producer-specific interpretation.  */
8898   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8899 }
8900
8901 /* Load the DIEs associated with PER_CU into memory.  */
8902
8903 static void
8904 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8905                      enum language pretend_language)
8906 {
8907   gdb_assert (! this_cu->is_debug_types);
8908
8909   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8910                            load_full_comp_unit_reader, &pretend_language);
8911 }
8912
8913 /* Add a DIE to the delayed physname list.  */
8914
8915 static void
8916 add_to_method_list (struct type *type, int fnfield_index, int index,
8917                     const char *name, struct die_info *die,
8918                     struct dwarf2_cu *cu)
8919 {
8920   struct delayed_method_info mi;
8921   mi.type = type;
8922   mi.fnfield_index = fnfield_index;
8923   mi.index = index;
8924   mi.name = name;
8925   mi.die = die;
8926   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8927 }
8928
8929 /* A cleanup for freeing the delayed method list.  */
8930
8931 static void
8932 free_delayed_list (void *ptr)
8933 {
8934   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8935   if (cu->method_list != NULL)
8936     {
8937       VEC_free (delayed_method_info, cu->method_list);
8938       cu->method_list = NULL;
8939     }
8940 }
8941
8942 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8943    "const" / "volatile".  If so, decrements LEN by the length of the
8944    modifier and return true.  Otherwise return false.  */
8945
8946 template<size_t N>
8947 static bool
8948 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8949 {
8950   size_t mod_len = sizeof (mod) - 1;
8951   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8952     {
8953       len -= mod_len;
8954       return true;
8955     }
8956   return false;
8957 }
8958
8959 /* Compute the physnames of any methods on the CU's method list.
8960
8961    The computation of method physnames is delayed in order to avoid the
8962    (bad) condition that one of the method's formal parameters is of an as yet
8963    incomplete type.  */
8964
8965 static void
8966 compute_delayed_physnames (struct dwarf2_cu *cu)
8967 {
8968   int i;
8969   struct delayed_method_info *mi;
8970
8971   /* Only C++ delays computing physnames.  */
8972   if (VEC_empty (delayed_method_info, cu->method_list))
8973     return;
8974   gdb_assert (cu->language == language_cplus);
8975
8976   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8977     {
8978       const char *physname;
8979       struct fn_fieldlist *fn_flp
8980         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8981       physname = dwarf2_physname (mi->name, mi->die, cu);
8982       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8983         = physname ? physname : "";
8984
8985       /* Since there's no tag to indicate whether a method is a
8986          const/volatile overload, extract that information out of the
8987          demangled name.  */
8988       if (physname != NULL)
8989         {
8990           size_t len = strlen (physname);
8991
8992           while (1)
8993             {
8994               if (physname[len] == ')') /* shortcut */
8995                 break;
8996               else if (check_modifier (physname, len, " const"))
8997                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8998               else if (check_modifier (physname, len, " volatile"))
8999                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
9000               else
9001                 break;
9002             }
9003         }
9004     }
9005 }
9006
9007 /* Go objects should be embedded in a DW_TAG_module DIE,
9008    and it's not clear if/how imported objects will appear.
9009    To keep Go support simple until that's worked out,
9010    go back through what we've read and create something usable.
9011    We could do this while processing each DIE, and feels kinda cleaner,
9012    but that way is more invasive.
9013    This is to, for example, allow the user to type "p var" or "b main"
9014    without having to specify the package name, and allow lookups
9015    of module.object to work in contexts that use the expression
9016    parser.  */
9017
9018 static void
9019 fixup_go_packaging (struct dwarf2_cu *cu)
9020 {
9021   char *package_name = NULL;
9022   struct pending *list;
9023   int i;
9024
9025   for (list = global_symbols; list != NULL; list = list->next)
9026     {
9027       for (i = 0; i < list->nsyms; ++i)
9028         {
9029           struct symbol *sym = list->symbol[i];
9030
9031           if (SYMBOL_LANGUAGE (sym) == language_go
9032               && SYMBOL_CLASS (sym) == LOC_BLOCK)
9033             {
9034               char *this_package_name = go_symbol_package_name (sym);
9035
9036               if (this_package_name == NULL)
9037                 continue;
9038               if (package_name == NULL)
9039                 package_name = this_package_name;
9040               else
9041                 {
9042                   if (strcmp (package_name, this_package_name) != 0)
9043                     complaint (&symfile_complaints,
9044                                _("Symtab %s has objects from two different Go packages: %s and %s"),
9045                                (symbol_symtab (sym) != NULL
9046                                 ? symtab_to_filename_for_display
9047                                     (symbol_symtab (sym))
9048                                 : objfile_name (cu->objfile)),
9049                                this_package_name, package_name);
9050                   xfree (this_package_name);
9051                 }
9052             }
9053         }
9054     }
9055
9056   if (package_name != NULL)
9057     {
9058       struct objfile *objfile = cu->objfile;
9059       const char *saved_package_name
9060         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
9061                                         package_name,
9062                                         strlen (package_name));
9063       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
9064                                      saved_package_name);
9065       struct symbol *sym;
9066
9067       TYPE_TAG_NAME (type) = TYPE_NAME (type);
9068
9069       sym = allocate_symbol (objfile);
9070       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
9071       SYMBOL_SET_NAMES (sym, saved_package_name,
9072                         strlen (saved_package_name), 0, objfile);
9073       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
9074          e.g., "main" finds the "main" module and not C's main().  */
9075       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
9076       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
9077       SYMBOL_TYPE (sym) = type;
9078
9079       add_symbol_to_list (sym, &global_symbols);
9080
9081       xfree (package_name);
9082     }
9083 }
9084
9085 /* Return the symtab for PER_CU.  This works properly regardless of
9086    whether we're using the index or psymtabs.  */
9087
9088 static struct compunit_symtab *
9089 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
9090 {
9091   return (dwarf2_per_objfile->using_index
9092           ? per_cu->v.quick->compunit_symtab
9093           : per_cu->v.psymtab->compunit_symtab);
9094 }
9095
9096 /* A helper function for computing the list of all symbol tables
9097    included by PER_CU.  */
9098
9099 static void
9100 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
9101                                 htab_t all_children, htab_t all_type_symtabs,
9102                                 struct dwarf2_per_cu_data *per_cu,
9103                                 struct compunit_symtab *immediate_parent)
9104 {
9105   void **slot;
9106   int ix;
9107   struct compunit_symtab *cust;
9108   struct dwarf2_per_cu_data *iter;
9109
9110   slot = htab_find_slot (all_children, per_cu, INSERT);
9111   if (*slot != NULL)
9112     {
9113       /* This inclusion and its children have been processed.  */
9114       return;
9115     }
9116
9117   *slot = per_cu;
9118   /* Only add a CU if it has a symbol table.  */
9119   cust = get_compunit_symtab (per_cu);
9120   if (cust != NULL)
9121     {
9122       /* If this is a type unit only add its symbol table if we haven't
9123          seen it yet (type unit per_cu's can share symtabs).  */
9124       if (per_cu->is_debug_types)
9125         {
9126           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
9127           if (*slot == NULL)
9128             {
9129               *slot = cust;
9130               VEC_safe_push (compunit_symtab_ptr, *result, cust);
9131               if (cust->user == NULL)
9132                 cust->user = immediate_parent;
9133             }
9134         }
9135       else
9136         {
9137           VEC_safe_push (compunit_symtab_ptr, *result, cust);
9138           if (cust->user == NULL)
9139             cust->user = immediate_parent;
9140         }
9141     }
9142
9143   for (ix = 0;
9144        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
9145        ++ix)
9146     {
9147       recursively_compute_inclusions (result, all_children,
9148                                       all_type_symtabs, iter, cust);
9149     }
9150 }
9151
9152 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
9153    PER_CU.  */
9154
9155 static void
9156 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
9157 {
9158   gdb_assert (! per_cu->is_debug_types);
9159
9160   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
9161     {
9162       int ix, len;
9163       struct dwarf2_per_cu_data *per_cu_iter;
9164       struct compunit_symtab *compunit_symtab_iter;
9165       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
9166       htab_t all_children, all_type_symtabs;
9167       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
9168
9169       /* If we don't have a symtab, we can just skip this case.  */
9170       if (cust == NULL)
9171         return;
9172
9173       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9174                                         NULL, xcalloc, xfree);
9175       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
9176                                             NULL, xcalloc, xfree);
9177
9178       for (ix = 0;
9179            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
9180                         ix, per_cu_iter);
9181            ++ix)
9182         {
9183           recursively_compute_inclusions (&result_symtabs, all_children,
9184                                           all_type_symtabs, per_cu_iter,
9185                                           cust);
9186         }
9187
9188       /* Now we have a transitive closure of all the included symtabs.  */
9189       len = VEC_length (compunit_symtab_ptr, result_symtabs);
9190       cust->includes
9191         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
9192                      struct compunit_symtab *, len + 1);
9193       for (ix = 0;
9194            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
9195                         compunit_symtab_iter);
9196            ++ix)
9197         cust->includes[ix] = compunit_symtab_iter;
9198       cust->includes[len] = NULL;
9199
9200       VEC_free (compunit_symtab_ptr, result_symtabs);
9201       htab_delete (all_children);
9202       htab_delete (all_type_symtabs);
9203     }
9204 }
9205
9206 /* Compute the 'includes' field for the symtabs of all the CUs we just
9207    read.  */
9208
9209 static void
9210 process_cu_includes (void)
9211 {
9212   int ix;
9213   struct dwarf2_per_cu_data *iter;
9214
9215   for (ix = 0;
9216        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
9217                     ix, iter);
9218        ++ix)
9219     {
9220       if (! iter->is_debug_types)
9221         compute_compunit_symtab_includes (iter);
9222     }
9223
9224   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
9225 }
9226
9227 /* Generate full symbol information for PER_CU, whose DIEs have
9228    already been loaded into memory.  */
9229
9230 static void
9231 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
9232                         enum language pretend_language)
9233 {
9234   struct dwarf2_cu *cu = per_cu->cu;
9235   struct objfile *objfile = per_cu->objfile;
9236   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9237   CORE_ADDR lowpc, highpc;
9238   struct compunit_symtab *cust;
9239   struct cleanup *delayed_list_cleanup;
9240   CORE_ADDR baseaddr;
9241   struct block *static_block;
9242   CORE_ADDR addr;
9243
9244   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9245
9246   buildsym_init ();
9247   scoped_free_pendings free_pending;
9248   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9249
9250   cu->list_in_scope = &file_symbols;
9251
9252   cu->language = pretend_language;
9253   cu->language_defn = language_def (cu->language);
9254
9255   /* Do line number decoding in read_file_scope () */
9256   process_die (cu->dies, cu);
9257
9258   /* For now fudge the Go package.  */
9259   if (cu->language == language_go)
9260     fixup_go_packaging (cu);
9261
9262   /* Now that we have processed all the DIEs in the CU, all the types 
9263      should be complete, and it should now be safe to compute all of the
9264      physnames.  */
9265   compute_delayed_physnames (cu);
9266   do_cleanups (delayed_list_cleanup);
9267
9268   /* Some compilers don't define a DW_AT_high_pc attribute for the
9269      compilation unit.  If the DW_AT_high_pc is missing, synthesize
9270      it, by scanning the DIE's below the compilation unit.  */
9271   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
9272
9273   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
9274   static_block = end_symtab_get_static_block (addr, 0, 1);
9275
9276   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
9277      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
9278      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
9279      addrmap to help ensure it has an accurate map of pc values belonging to
9280      this comp unit.  */
9281   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
9282
9283   cust = end_symtab_from_static_block (static_block,
9284                                        SECT_OFF_TEXT (objfile), 0);
9285
9286   if (cust != NULL)
9287     {
9288       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
9289
9290       /* Set symtab language to language from DW_AT_language.  If the
9291          compilation is from a C file generated by language preprocessors, do
9292          not set the language if it was already deduced by start_subfile.  */
9293       if (!(cu->language == language_c
9294             && COMPUNIT_FILETABS (cust)->language != language_unknown))
9295         COMPUNIT_FILETABS (cust)->language = cu->language;
9296
9297       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
9298          produce DW_AT_location with location lists but it can be possibly
9299          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
9300          there were bugs in prologue debug info, fixed later in GCC-4.5
9301          by "unwind info for epilogues" patch (which is not directly related).
9302
9303          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
9304          needed, it would be wrong due to missing DW_AT_producer there.
9305
9306          Still one can confuse GDB by using non-standard GCC compilation
9307          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
9308          */ 
9309       if (cu->has_loclist && gcc_4_minor >= 5)
9310         cust->locations_valid = 1;
9311
9312       if (gcc_4_minor >= 5)
9313         cust->epilogue_unwind_valid = 1;
9314
9315       cust->call_site_htab = cu->call_site_htab;
9316     }
9317
9318   if (dwarf2_per_objfile->using_index)
9319     per_cu->v.quick->compunit_symtab = cust;
9320   else
9321     {
9322       struct partial_symtab *pst = per_cu->v.psymtab;
9323       pst->compunit_symtab = cust;
9324       pst->readin = 1;
9325     }
9326
9327   /* Push it for inclusion processing later.  */
9328   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
9329 }
9330
9331 /* Generate full symbol information for type unit PER_CU, whose DIEs have
9332    already been loaded into memory.  */
9333
9334 static void
9335 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
9336                         enum language pretend_language)
9337 {
9338   struct dwarf2_cu *cu = per_cu->cu;
9339   struct objfile *objfile = per_cu->objfile;
9340   struct compunit_symtab *cust;
9341   struct cleanup *delayed_list_cleanup;
9342   struct signatured_type *sig_type;
9343
9344   gdb_assert (per_cu->is_debug_types);
9345   sig_type = (struct signatured_type *) per_cu;
9346
9347   buildsym_init ();
9348   scoped_free_pendings free_pending;
9349   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
9350
9351   cu->list_in_scope = &file_symbols;
9352
9353   cu->language = pretend_language;
9354   cu->language_defn = language_def (cu->language);
9355
9356   /* The symbol tables are set up in read_type_unit_scope.  */
9357   process_die (cu->dies, cu);
9358
9359   /* For now fudge the Go package.  */
9360   if (cu->language == language_go)
9361     fixup_go_packaging (cu);
9362
9363   /* Now that we have processed all the DIEs in the CU, all the types 
9364      should be complete, and it should now be safe to compute all of the
9365      physnames.  */
9366   compute_delayed_physnames (cu);
9367   do_cleanups (delayed_list_cleanup);
9368
9369   /* TUs share symbol tables.
9370      If this is the first TU to use this symtab, complete the construction
9371      of it with end_expandable_symtab.  Otherwise, complete the addition of
9372      this TU's symbols to the existing symtab.  */
9373   if (sig_type->type_unit_group->compunit_symtab == NULL)
9374     {
9375       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
9376       sig_type->type_unit_group->compunit_symtab = cust;
9377
9378       if (cust != NULL)
9379         {
9380           /* Set symtab language to language from DW_AT_language.  If the
9381              compilation is from a C file generated by language preprocessors,
9382              do not set the language if it was already deduced by
9383              start_subfile.  */
9384           if (!(cu->language == language_c
9385                 && COMPUNIT_FILETABS (cust)->language != language_c))
9386             COMPUNIT_FILETABS (cust)->language = cu->language;
9387         }
9388     }
9389   else
9390     {
9391       augment_type_symtab ();
9392       cust = sig_type->type_unit_group->compunit_symtab;
9393     }
9394
9395   if (dwarf2_per_objfile->using_index)
9396     per_cu->v.quick->compunit_symtab = cust;
9397   else
9398     {
9399       struct partial_symtab *pst = per_cu->v.psymtab;
9400       pst->compunit_symtab = cust;
9401       pst->readin = 1;
9402     }
9403 }
9404
9405 /* Process an imported unit DIE.  */
9406
9407 static void
9408 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
9409 {
9410   struct attribute *attr;
9411
9412   /* For now we don't handle imported units in type units.  */
9413   if (cu->per_cu->is_debug_types)
9414     {
9415       error (_("Dwarf Error: DW_TAG_imported_unit is not"
9416                " supported in type units [in module %s]"),
9417              objfile_name (cu->objfile));
9418     }
9419
9420   attr = dwarf2_attr (die, DW_AT_import, cu);
9421   if (attr != NULL)
9422     {
9423       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9424       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
9425       dwarf2_per_cu_data *per_cu
9426         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
9427
9428       /* If necessary, add it to the queue and load its DIEs.  */
9429       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
9430         load_full_comp_unit (per_cu, cu->language);
9431
9432       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
9433                      per_cu);
9434     }
9435 }
9436
9437 /* RAII object that represents a process_die scope: i.e.,
9438    starts/finishes processing a DIE.  */
9439 class process_die_scope
9440 {
9441 public:
9442   process_die_scope (die_info *die, dwarf2_cu *cu)
9443     : m_die (die), m_cu (cu)
9444   {
9445     /* We should only be processing DIEs not already in process.  */
9446     gdb_assert (!m_die->in_process);
9447     m_die->in_process = true;
9448   }
9449
9450   ~process_die_scope ()
9451   {
9452     m_die->in_process = false;
9453
9454     /* If we're done processing the DIE for the CU that owns the line
9455        header, we don't need the line header anymore.  */
9456     if (m_cu->line_header_die_owner == m_die)
9457       {
9458         delete m_cu->line_header;
9459         m_cu->line_header = NULL;
9460         m_cu->line_header_die_owner = NULL;
9461       }
9462   }
9463
9464 private:
9465   die_info *m_die;
9466   dwarf2_cu *m_cu;
9467 };
9468
9469 /* Process a die and its children.  */
9470
9471 static void
9472 process_die (struct die_info *die, struct dwarf2_cu *cu)
9473 {
9474   process_die_scope scope (die, cu);
9475
9476   switch (die->tag)
9477     {
9478     case DW_TAG_padding:
9479       break;
9480     case DW_TAG_compile_unit:
9481     case DW_TAG_partial_unit:
9482       read_file_scope (die, cu);
9483       break;
9484     case DW_TAG_type_unit:
9485       read_type_unit_scope (die, cu);
9486       break;
9487     case DW_TAG_subprogram:
9488     case DW_TAG_inlined_subroutine:
9489       read_func_scope (die, cu);
9490       break;
9491     case DW_TAG_lexical_block:
9492     case DW_TAG_try_block:
9493     case DW_TAG_catch_block:
9494       read_lexical_block_scope (die, cu);
9495       break;
9496     case DW_TAG_call_site:
9497     case DW_TAG_GNU_call_site:
9498       read_call_site_scope (die, cu);
9499       break;
9500     case DW_TAG_class_type:
9501     case DW_TAG_interface_type:
9502     case DW_TAG_structure_type:
9503     case DW_TAG_union_type:
9504       process_structure_scope (die, cu);
9505       break;
9506     case DW_TAG_enumeration_type:
9507       process_enumeration_scope (die, cu);
9508       break;
9509
9510     /* These dies have a type, but processing them does not create
9511        a symbol or recurse to process the children.  Therefore we can
9512        read them on-demand through read_type_die.  */
9513     case DW_TAG_subroutine_type:
9514     case DW_TAG_set_type:
9515     case DW_TAG_array_type:
9516     case DW_TAG_pointer_type:
9517     case DW_TAG_ptr_to_member_type:
9518     case DW_TAG_reference_type:
9519     case DW_TAG_rvalue_reference_type:
9520     case DW_TAG_string_type:
9521       break;
9522
9523     case DW_TAG_base_type:
9524     case DW_TAG_subrange_type:
9525     case DW_TAG_typedef:
9526       /* Add a typedef symbol for the type definition, if it has a
9527          DW_AT_name.  */
9528       new_symbol (die, read_type_die (die, cu), cu);
9529       break;
9530     case DW_TAG_common_block:
9531       read_common_block (die, cu);
9532       break;
9533     case DW_TAG_common_inclusion:
9534       break;
9535     case DW_TAG_namespace:
9536       cu->processing_has_namespace_info = 1;
9537       read_namespace (die, cu);
9538       break;
9539     case DW_TAG_module:
9540       cu->processing_has_namespace_info = 1;
9541       read_module (die, cu);
9542       break;
9543     case DW_TAG_imported_declaration:
9544       cu->processing_has_namespace_info = 1;
9545       if (read_namespace_alias (die, cu))
9546         break;
9547       /* The declaration is not a global namespace alias: fall through.  */
9548     case DW_TAG_imported_module:
9549       cu->processing_has_namespace_info = 1;
9550       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
9551                                  || cu->language != language_fortran))
9552         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
9553                    dwarf_tag_name (die->tag));
9554       read_import_statement (die, cu);
9555       break;
9556
9557     case DW_TAG_imported_unit:
9558       process_imported_unit_die (die, cu);
9559       break;
9560
9561     case DW_TAG_variable:
9562       read_variable (die, cu);
9563       break;
9564
9565     default:
9566       new_symbol (die, NULL, cu);
9567       break;
9568     }
9569 }
9570 \f
9571 /* DWARF name computation.  */
9572
9573 /* A helper function for dwarf2_compute_name which determines whether DIE
9574    needs to have the name of the scope prepended to the name listed in the
9575    die.  */
9576
9577 static int
9578 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
9579 {
9580   struct attribute *attr;
9581
9582   switch (die->tag)
9583     {
9584     case DW_TAG_namespace:
9585     case DW_TAG_typedef:
9586     case DW_TAG_class_type:
9587     case DW_TAG_interface_type:
9588     case DW_TAG_structure_type:
9589     case DW_TAG_union_type:
9590     case DW_TAG_enumeration_type:
9591     case DW_TAG_enumerator:
9592     case DW_TAG_subprogram:
9593     case DW_TAG_inlined_subroutine:
9594     case DW_TAG_member:
9595     case DW_TAG_imported_declaration:
9596       return 1;
9597
9598     case DW_TAG_variable:
9599     case DW_TAG_constant:
9600       /* We only need to prefix "globally" visible variables.  These include
9601          any variable marked with DW_AT_external or any variable that
9602          lives in a namespace.  [Variables in anonymous namespaces
9603          require prefixing, but they are not DW_AT_external.]  */
9604
9605       if (dwarf2_attr (die, DW_AT_specification, cu))
9606         {
9607           struct dwarf2_cu *spec_cu = cu;
9608
9609           return die_needs_namespace (die_specification (die, &spec_cu),
9610                                       spec_cu);
9611         }
9612
9613       attr = dwarf2_attr (die, DW_AT_external, cu);
9614       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9615           && die->parent->tag != DW_TAG_module)
9616         return 0;
9617       /* A variable in a lexical block of some kind does not need a
9618          namespace, even though in C++ such variables may be external
9619          and have a mangled name.  */
9620       if (die->parent->tag ==  DW_TAG_lexical_block
9621           || die->parent->tag ==  DW_TAG_try_block
9622           || die->parent->tag ==  DW_TAG_catch_block
9623           || die->parent->tag == DW_TAG_subprogram)
9624         return 0;
9625       return 1;
9626
9627     default:
9628       return 0;
9629     }
9630 }
9631
9632 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9633    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9634    defined for the given DIE.  */
9635
9636 static struct attribute *
9637 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9638 {
9639   struct attribute *attr;
9640
9641   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9642   if (attr == NULL)
9643     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9644
9645   return attr;
9646 }
9647
9648 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9649    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9650    defined for the given DIE.  */
9651
9652 static const char *
9653 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9654 {
9655   const char *linkage_name;
9656
9657   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9658   if (linkage_name == NULL)
9659     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9660
9661   return linkage_name;
9662 }
9663
9664 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9665    compute the physname for the object, which include a method's:
9666    - formal parameters (C++),
9667    - receiver type (Go),
9668
9669    The term "physname" is a bit confusing.
9670    For C++, for example, it is the demangled name.
9671    For Go, for example, it's the mangled name.
9672
9673    For Ada, return the DIE's linkage name rather than the fully qualified
9674    name.  PHYSNAME is ignored..
9675
9676    The result is allocated on the objfile_obstack and canonicalized.  */
9677
9678 static const char *
9679 dwarf2_compute_name (const char *name,
9680                      struct die_info *die, struct dwarf2_cu *cu,
9681                      int physname)
9682 {
9683   struct objfile *objfile = cu->objfile;
9684
9685   if (name == NULL)
9686     name = dwarf2_name (die, cu);
9687
9688   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9689      but otherwise compute it by typename_concat inside GDB.
9690      FIXME: Actually this is not really true, or at least not always true.
9691      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9692      Fortran names because there is no mangling standard.  So new_symbol_full
9693      will set the demangled name to the result of dwarf2_full_name, and it is
9694      the demangled name that GDB uses if it exists.  */
9695   if (cu->language == language_ada
9696       || (cu->language == language_fortran && physname))
9697     {
9698       /* For Ada unit, we prefer the linkage name over the name, as
9699          the former contains the exported name, which the user expects
9700          to be able to reference.  Ideally, we want the user to be able
9701          to reference this entity using either natural or linkage name,
9702          but we haven't started looking at this enhancement yet.  */
9703       const char *linkage_name = dw2_linkage_name (die, cu);
9704
9705       if (linkage_name != NULL)
9706         return linkage_name;
9707     }
9708
9709   /* These are the only languages we know how to qualify names in.  */
9710   if (name != NULL
9711       && (cu->language == language_cplus
9712           || cu->language == language_fortran || cu->language == language_d
9713           || cu->language == language_rust))
9714     {
9715       if (die_needs_namespace (die, cu))
9716         {
9717           const char *prefix;
9718           const char *canonical_name = NULL;
9719
9720           string_file buf;
9721
9722           prefix = determine_prefix (die, cu);
9723           if (*prefix != '\0')
9724             {
9725               char *prefixed_name = typename_concat (NULL, prefix, name,
9726                                                      physname, cu);
9727
9728               buf.puts (prefixed_name);
9729               xfree (prefixed_name);
9730             }
9731           else
9732             buf.puts (name);
9733
9734           /* Template parameters may be specified in the DIE's DW_AT_name, or
9735              as children with DW_TAG_template_type_param or
9736              DW_TAG_value_type_param.  If the latter, add them to the name
9737              here.  If the name already has template parameters, then
9738              skip this step; some versions of GCC emit both, and
9739              it is more efficient to use the pre-computed name.
9740
9741              Something to keep in mind about this process: it is very
9742              unlikely, or in some cases downright impossible, to produce
9743              something that will match the mangled name of a function.
9744              If the definition of the function has the same debug info,
9745              we should be able to match up with it anyway.  But fallbacks
9746              using the minimal symbol, for instance to find a method
9747              implemented in a stripped copy of libstdc++, will not work.
9748              If we do not have debug info for the definition, we will have to
9749              match them up some other way.
9750
9751              When we do name matching there is a related problem with function
9752              templates; two instantiated function templates are allowed to
9753              differ only by their return types, which we do not add here.  */
9754
9755           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9756             {
9757               struct attribute *attr;
9758               struct die_info *child;
9759               int first = 1;
9760
9761               die->building_fullname = 1;
9762
9763               for (child = die->child; child != NULL; child = child->sibling)
9764                 {
9765                   struct type *type;
9766                   LONGEST value;
9767                   const gdb_byte *bytes;
9768                   struct dwarf2_locexpr_baton *baton;
9769                   struct value *v;
9770
9771                   if (child->tag != DW_TAG_template_type_param
9772                       && child->tag != DW_TAG_template_value_param)
9773                     continue;
9774
9775                   if (first)
9776                     {
9777                       buf.puts ("<");
9778                       first = 0;
9779                     }
9780                   else
9781                     buf.puts (", ");
9782
9783                   attr = dwarf2_attr (child, DW_AT_type, cu);
9784                   if (attr == NULL)
9785                     {
9786                       complaint (&symfile_complaints,
9787                                  _("template parameter missing DW_AT_type"));
9788                       buf.puts ("UNKNOWN_TYPE");
9789                       continue;
9790                     }
9791                   type = die_type (child, cu);
9792
9793                   if (child->tag == DW_TAG_template_type_param)
9794                     {
9795                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9796                       continue;
9797                     }
9798
9799                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9800                   if (attr == NULL)
9801                     {
9802                       complaint (&symfile_complaints,
9803                                  _("template parameter missing "
9804                                    "DW_AT_const_value"));
9805                       buf.puts ("UNKNOWN_VALUE");
9806                       continue;
9807                     }
9808
9809                   dwarf2_const_value_attr (attr, type, name,
9810                                            &cu->comp_unit_obstack, cu,
9811                                            &value, &bytes, &baton);
9812
9813                   if (TYPE_NOSIGN (type))
9814                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9815                        changed, this can use value_print instead.  */
9816                     c_printchar (value, type, &buf);
9817                   else
9818                     {
9819                       struct value_print_options opts;
9820
9821                       if (baton != NULL)
9822                         v = dwarf2_evaluate_loc_desc (type, NULL,
9823                                                       baton->data,
9824                                                       baton->size,
9825                                                       baton->per_cu);
9826                       else if (bytes != NULL)
9827                         {
9828                           v = allocate_value (type);
9829                           memcpy (value_contents_writeable (v), bytes,
9830                                   TYPE_LENGTH (type));
9831                         }
9832                       else
9833                         v = value_from_longest (type, value);
9834
9835                       /* Specify decimal so that we do not depend on
9836                          the radix.  */
9837                       get_formatted_print_options (&opts, 'd');
9838                       opts.raw = 1;
9839                       value_print (v, &buf, &opts);
9840                       release_value (v);
9841                       value_free (v);
9842                     }
9843                 }
9844
9845               die->building_fullname = 0;
9846
9847               if (!first)
9848                 {
9849                   /* Close the argument list, with a space if necessary
9850                      (nested templates).  */
9851                   if (!buf.empty () && buf.string ().back () == '>')
9852                     buf.puts (" >");
9853                   else
9854                     buf.puts (">");
9855                 }
9856             }
9857
9858           /* For C++ methods, append formal parameter type
9859              information, if PHYSNAME.  */
9860
9861           if (physname && die->tag == DW_TAG_subprogram
9862               && cu->language == language_cplus)
9863             {
9864               struct type *type = read_type_die (die, cu);
9865
9866               c_type_print_args (type, &buf, 1, cu->language,
9867                                  &type_print_raw_options);
9868
9869               if (cu->language == language_cplus)
9870                 {
9871                   /* Assume that an artificial first parameter is
9872                      "this", but do not crash if it is not.  RealView
9873                      marks unnamed (and thus unused) parameters as
9874                      artificial; there is no way to differentiate
9875                      the two cases.  */
9876                   if (TYPE_NFIELDS (type) > 0
9877                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9878                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9879                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9880                                                                         0))))
9881                     buf.puts (" const");
9882                 }
9883             }
9884
9885           const std::string &intermediate_name = buf.string ();
9886
9887           if (cu->language == language_cplus)
9888             canonical_name
9889               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9890                                           &objfile->per_bfd->storage_obstack);
9891
9892           /* If we only computed INTERMEDIATE_NAME, or if
9893              INTERMEDIATE_NAME is already canonical, then we need to
9894              copy it to the appropriate obstack.  */
9895           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9896             name = ((const char *)
9897                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9898                                    intermediate_name.c_str (),
9899                                    intermediate_name.length ()));
9900           else
9901             name = canonical_name;
9902         }
9903     }
9904
9905   return name;
9906 }
9907
9908 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9909    If scope qualifiers are appropriate they will be added.  The result
9910    will be allocated on the storage_obstack, or NULL if the DIE does
9911    not have a name.  NAME may either be from a previous call to
9912    dwarf2_name or NULL.
9913
9914    The output string will be canonicalized (if C++).  */
9915
9916 static const char *
9917 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9918 {
9919   return dwarf2_compute_name (name, die, cu, 0);
9920 }
9921
9922 /* Construct a physname for the given DIE in CU.  NAME may either be
9923    from a previous call to dwarf2_name or NULL.  The result will be
9924    allocated on the objfile_objstack or NULL if the DIE does not have a
9925    name.
9926
9927    The output string will be canonicalized (if C++).  */
9928
9929 static const char *
9930 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9931 {
9932   struct objfile *objfile = cu->objfile;
9933   const char *retval, *mangled = NULL, *canon = NULL;
9934   int need_copy = 1;
9935
9936   /* In this case dwarf2_compute_name is just a shortcut not building anything
9937      on its own.  */
9938   if (!die_needs_namespace (die, cu))
9939     return dwarf2_compute_name (name, die, cu, 1);
9940
9941   mangled = dw2_linkage_name (die, cu);
9942
9943   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9944      See https://github.com/rust-lang/rust/issues/32925.  */
9945   if (cu->language == language_rust && mangled != NULL
9946       && strchr (mangled, '{') != NULL)
9947     mangled = NULL;
9948
9949   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9950      has computed.  */
9951   gdb::unique_xmalloc_ptr<char> demangled;
9952   if (mangled != NULL)
9953     {
9954       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9955          type.  It is easier for GDB users to search for such functions as
9956          `name(params)' than `long name(params)'.  In such case the minimal
9957          symbol names do not match the full symbol names but for template
9958          functions there is never a need to look up their definition from their
9959          declaration so the only disadvantage remains the minimal symbol
9960          variant `long name(params)' does not have the proper inferior type.
9961          */
9962
9963       if (cu->language == language_go)
9964         {
9965           /* This is a lie, but we already lie to the caller new_symbol_full.
9966              new_symbol_full assumes we return the mangled name.
9967              This just undoes that lie until things are cleaned up.  */
9968         }
9969       else
9970         {
9971           demangled.reset (gdb_demangle (mangled,
9972                                          (DMGL_PARAMS | DMGL_ANSI
9973                                           | DMGL_RET_DROP)));
9974         }
9975       if (demangled)
9976         canon = demangled.get ();
9977       else
9978         {
9979           canon = mangled;
9980           need_copy = 0;
9981         }
9982     }
9983
9984   if (canon == NULL || check_physname)
9985     {
9986       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9987
9988       if (canon != NULL && strcmp (physname, canon) != 0)
9989         {
9990           /* It may not mean a bug in GDB.  The compiler could also
9991              compute DW_AT_linkage_name incorrectly.  But in such case
9992              GDB would need to be bug-to-bug compatible.  */
9993
9994           complaint (&symfile_complaints,
9995                      _("Computed physname <%s> does not match demangled <%s> "
9996                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9997                      physname, canon, mangled, to_underlying (die->sect_off),
9998                      objfile_name (objfile));
9999
10000           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
10001              is available here - over computed PHYSNAME.  It is safer
10002              against both buggy GDB and buggy compilers.  */
10003
10004           retval = canon;
10005         }
10006       else
10007         {
10008           retval = physname;
10009           need_copy = 0;
10010         }
10011     }
10012   else
10013     retval = canon;
10014
10015   if (need_copy)
10016     retval = ((const char *)
10017               obstack_copy0 (&objfile->per_bfd->storage_obstack,
10018                              retval, strlen (retval)));
10019
10020   return retval;
10021 }
10022
10023 /* Inspect DIE in CU for a namespace alias.  If one exists, record
10024    a new symbol for it.
10025
10026    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
10027
10028 static int
10029 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
10030 {
10031   struct attribute *attr;
10032
10033   /* If the die does not have a name, this is not a namespace
10034      alias.  */
10035   attr = dwarf2_attr (die, DW_AT_name, cu);
10036   if (attr != NULL)
10037     {
10038       int num;
10039       struct die_info *d = die;
10040       struct dwarf2_cu *imported_cu = cu;
10041
10042       /* If the compiler has nested DW_AT_imported_declaration DIEs,
10043          keep inspecting DIEs until we hit the underlying import.  */
10044 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
10045       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
10046         {
10047           attr = dwarf2_attr (d, DW_AT_import, cu);
10048           if (attr == NULL)
10049             break;
10050
10051           d = follow_die_ref (d, attr, &imported_cu);
10052           if (d->tag != DW_TAG_imported_declaration)
10053             break;
10054         }
10055
10056       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
10057         {
10058           complaint (&symfile_complaints,
10059                      _("DIE at 0x%x has too many recursively imported "
10060                        "declarations"), to_underlying (d->sect_off));
10061           return 0;
10062         }
10063
10064       if (attr != NULL)
10065         {
10066           struct type *type;
10067           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
10068
10069           type = get_die_type_at_offset (sect_off, cu->per_cu);
10070           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
10071             {
10072               /* This declaration is a global namespace alias.  Add
10073                  a symbol for it whose type is the aliased namespace.  */
10074               new_symbol (die, type, cu);
10075               return 1;
10076             }
10077         }
10078     }
10079
10080   return 0;
10081 }
10082
10083 /* Return the using directives repository (global or local?) to use in the
10084    current context for LANGUAGE.
10085
10086    For Ada, imported declarations can materialize renamings, which *may* be
10087    global.  However it is impossible (for now?) in DWARF to distinguish
10088    "external" imported declarations and "static" ones.  As all imported
10089    declarations seem to be static in all other languages, make them all CU-wide
10090    global only in Ada.  */
10091
10092 static struct using_direct **
10093 using_directives (enum language language)
10094 {
10095   if (language == language_ada && context_stack_depth == 0)
10096     return &global_using_directives;
10097   else
10098     return &local_using_directives;
10099 }
10100
10101 /* Read the import statement specified by the given die and record it.  */
10102
10103 static void
10104 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
10105 {
10106   struct objfile *objfile = cu->objfile;
10107   struct attribute *import_attr;
10108   struct die_info *imported_die, *child_die;
10109   struct dwarf2_cu *imported_cu;
10110   const char *imported_name;
10111   const char *imported_name_prefix;
10112   const char *canonical_name;
10113   const char *import_alias;
10114   const char *imported_declaration = NULL;
10115   const char *import_prefix;
10116   std::vector<const char *> excludes;
10117
10118   import_attr = dwarf2_attr (die, DW_AT_import, cu);
10119   if (import_attr == NULL)
10120     {
10121       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10122                  dwarf_tag_name (die->tag));
10123       return;
10124     }
10125
10126   imported_cu = cu;
10127   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
10128   imported_name = dwarf2_name (imported_die, imported_cu);
10129   if (imported_name == NULL)
10130     {
10131       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
10132
10133         The import in the following code:
10134         namespace A
10135           {
10136             typedef int B;
10137           }
10138
10139         int main ()
10140           {
10141             using A::B;
10142             B b;
10143             return b;
10144           }
10145
10146         ...
10147          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
10148             <52>   DW_AT_decl_file   : 1
10149             <53>   DW_AT_decl_line   : 6
10150             <54>   DW_AT_import      : <0x75>
10151          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
10152             <59>   DW_AT_name        : B
10153             <5b>   DW_AT_decl_file   : 1
10154             <5c>   DW_AT_decl_line   : 2
10155             <5d>   DW_AT_type        : <0x6e>
10156         ...
10157          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
10158             <76>   DW_AT_byte_size   : 4
10159             <77>   DW_AT_encoding    : 5        (signed)
10160
10161         imports the wrong die ( 0x75 instead of 0x58 ).
10162         This case will be ignored until the gcc bug is fixed.  */
10163       return;
10164     }
10165
10166   /* Figure out the local name after import.  */
10167   import_alias = dwarf2_name (die, cu);
10168
10169   /* Figure out where the statement is being imported to.  */
10170   import_prefix = determine_prefix (die, cu);
10171
10172   /* Figure out what the scope of the imported die is and prepend it
10173      to the name of the imported die.  */
10174   imported_name_prefix = determine_prefix (imported_die, imported_cu);
10175
10176   if (imported_die->tag != DW_TAG_namespace
10177       && imported_die->tag != DW_TAG_module)
10178     {
10179       imported_declaration = imported_name;
10180       canonical_name = imported_name_prefix;
10181     }
10182   else if (strlen (imported_name_prefix) > 0)
10183     canonical_name = obconcat (&objfile->objfile_obstack,
10184                                imported_name_prefix,
10185                                (cu->language == language_d ? "." : "::"),
10186                                imported_name, (char *) NULL);
10187   else
10188     canonical_name = imported_name;
10189
10190   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
10191     for (child_die = die->child; child_die && child_die->tag;
10192          child_die = sibling_die (child_die))
10193       {
10194         /* DWARF-4: A Fortran use statement with a “rename list” may be
10195            represented by an imported module entry with an import attribute
10196            referring to the module and owned entries corresponding to those
10197            entities that are renamed as part of being imported.  */
10198
10199         if (child_die->tag != DW_TAG_imported_declaration)
10200           {
10201             complaint (&symfile_complaints,
10202                        _("child DW_TAG_imported_declaration expected "
10203                          "- DIE at 0x%x [in module %s]"),
10204                        to_underlying (child_die->sect_off), objfile_name (objfile));
10205             continue;
10206           }
10207
10208         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
10209         if (import_attr == NULL)
10210           {
10211             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
10212                        dwarf_tag_name (child_die->tag));
10213             continue;
10214           }
10215
10216         imported_cu = cu;
10217         imported_die = follow_die_ref_or_sig (child_die, import_attr,
10218                                               &imported_cu);
10219         imported_name = dwarf2_name (imported_die, imported_cu);
10220         if (imported_name == NULL)
10221           {
10222             complaint (&symfile_complaints,
10223                        _("child DW_TAG_imported_declaration has unknown "
10224                          "imported name - DIE at 0x%x [in module %s]"),
10225                        to_underlying (child_die->sect_off), objfile_name (objfile));
10226             continue;
10227           }
10228
10229         excludes.push_back (imported_name);
10230
10231         process_die (child_die, cu);
10232       }
10233
10234   add_using_directive (using_directives (cu->language),
10235                        import_prefix,
10236                        canonical_name,
10237                        import_alias,
10238                        imported_declaration,
10239                        excludes,
10240                        0,
10241                        &objfile->objfile_obstack);
10242 }
10243
10244 /* ICC<14 does not output the required DW_AT_declaration on incomplete
10245    types, but gives them a size of zero.  Starting with version 14,
10246    ICC is compatible with GCC.  */
10247
10248 static int
10249 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
10250 {
10251   if (!cu->checked_producer)
10252     check_producer (cu);
10253
10254   return cu->producer_is_icc_lt_14;
10255 }
10256
10257 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
10258    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
10259    this, it was first present in GCC release 4.3.0.  */
10260
10261 static int
10262 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
10263 {
10264   if (!cu->checked_producer)
10265     check_producer (cu);
10266
10267   return cu->producer_is_gcc_lt_4_3;
10268 }
10269
10270 static file_and_directory
10271 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
10272 {
10273   file_and_directory res;
10274
10275   /* Find the filename.  Do not use dwarf2_name here, since the filename
10276      is not a source language identifier.  */
10277   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
10278   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
10279
10280   if (res.comp_dir == NULL
10281       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
10282       && IS_ABSOLUTE_PATH (res.name))
10283     {
10284       res.comp_dir_storage = ldirname (res.name);
10285       if (!res.comp_dir_storage.empty ())
10286         res.comp_dir = res.comp_dir_storage.c_str ();
10287     }
10288   if (res.comp_dir != NULL)
10289     {
10290       /* Irix 6.2 native cc prepends <machine>.: to the compilation
10291          directory, get rid of it.  */
10292       const char *cp = strchr (res.comp_dir, ':');
10293
10294       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
10295         res.comp_dir = cp + 1;
10296     }
10297
10298   if (res.name == NULL)
10299     res.name = "<unknown>";
10300
10301   return res;
10302 }
10303
10304 /* Handle DW_AT_stmt_list for a compilation unit.
10305    DIE is the DW_TAG_compile_unit die for CU.
10306    COMP_DIR is the compilation directory.  LOWPC is passed to
10307    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
10308
10309 static void
10310 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
10311                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
10312 {
10313   struct objfile *objfile = dwarf2_per_objfile->objfile;
10314   struct attribute *attr;
10315   struct line_header line_header_local;
10316   hashval_t line_header_local_hash;
10317   void **slot;
10318   int decode_mapping;
10319
10320   gdb_assert (! cu->per_cu->is_debug_types);
10321
10322   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10323   if (attr == NULL)
10324     return;
10325
10326   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10327
10328   /* The line header hash table is only created if needed (it exists to
10329      prevent redundant reading of the line table for partial_units).
10330      If we're given a partial_unit, we'll need it.  If we're given a
10331      compile_unit, then use the line header hash table if it's already
10332      created, but don't create one just yet.  */
10333
10334   if (dwarf2_per_objfile->line_header_hash == NULL
10335       && die->tag == DW_TAG_partial_unit)
10336     {
10337       dwarf2_per_objfile->line_header_hash
10338         = htab_create_alloc_ex (127, line_header_hash_voidp,
10339                                 line_header_eq_voidp,
10340                                 free_line_header_voidp,
10341                                 &objfile->objfile_obstack,
10342                                 hashtab_obstack_allocate,
10343                                 dummy_obstack_deallocate);
10344     }
10345
10346   line_header_local.sect_off = line_offset;
10347   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
10348   line_header_local_hash = line_header_hash (&line_header_local);
10349   if (dwarf2_per_objfile->line_header_hash != NULL)
10350     {
10351       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10352                                        &line_header_local,
10353                                        line_header_local_hash, NO_INSERT);
10354
10355       /* For DW_TAG_compile_unit we need info like symtab::linetable which
10356          is not present in *SLOT (since if there is something in *SLOT then
10357          it will be for a partial_unit).  */
10358       if (die->tag == DW_TAG_partial_unit && slot != NULL)
10359         {
10360           gdb_assert (*slot != NULL);
10361           cu->line_header = (struct line_header *) *slot;
10362           return;
10363         }
10364     }
10365
10366   /* dwarf_decode_line_header does not yet provide sufficient information.
10367      We always have to call also dwarf_decode_lines for it.  */
10368   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
10369   if (lh == NULL)
10370     return;
10371
10372   cu->line_header = lh.release ();
10373   cu->line_header_die_owner = die;
10374
10375   if (dwarf2_per_objfile->line_header_hash == NULL)
10376     slot = NULL;
10377   else
10378     {
10379       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
10380                                        &line_header_local,
10381                                        line_header_local_hash, INSERT);
10382       gdb_assert (slot != NULL);
10383     }
10384   if (slot != NULL && *slot == NULL)
10385     {
10386       /* This newly decoded line number information unit will be owned
10387          by line_header_hash hash table.  */
10388       *slot = cu->line_header;
10389       cu->line_header_die_owner = NULL;
10390     }
10391   else
10392     {
10393       /* We cannot free any current entry in (*slot) as that struct line_header
10394          may be already used by multiple CUs.  Create only temporary decoded
10395          line_header for this CU - it may happen at most once for each line
10396          number information unit.  And if we're not using line_header_hash
10397          then this is what we want as well.  */
10398       gdb_assert (die->tag != DW_TAG_partial_unit);
10399     }
10400   decode_mapping = (die->tag != DW_TAG_partial_unit);
10401   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
10402                       decode_mapping);
10403
10404 }
10405
10406 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
10407
10408 static void
10409 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
10410 {
10411   struct objfile *objfile = dwarf2_per_objfile->objfile;
10412   struct gdbarch *gdbarch = get_objfile_arch (objfile);
10413   CORE_ADDR lowpc = ((CORE_ADDR) -1);
10414   CORE_ADDR highpc = ((CORE_ADDR) 0);
10415   struct attribute *attr;
10416   struct die_info *child_die;
10417   CORE_ADDR baseaddr;
10418
10419   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
10420
10421   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
10422
10423   /* If we didn't find a lowpc, set it to highpc to avoid complaints
10424      from finish_block.  */
10425   if (lowpc == ((CORE_ADDR) -1))
10426     lowpc = highpc;
10427   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
10428
10429   file_and_directory fnd = find_file_and_directory (die, cu);
10430
10431   prepare_one_comp_unit (cu, die, cu->language);
10432
10433   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
10434      standardised yet.  As a workaround for the language detection we fall
10435      back to the DW_AT_producer string.  */
10436   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
10437     cu->language = language_opencl;
10438
10439   /* Similar hack for Go.  */
10440   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
10441     set_cu_language (DW_LANG_Go, cu);
10442
10443   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
10444
10445   /* Decode line number information if present.  We do this before
10446      processing child DIEs, so that the line header table is available
10447      for DW_AT_decl_file.  */
10448   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
10449
10450   /* Process all dies in compilation unit.  */
10451   if (die->child != NULL)
10452     {
10453       child_die = die->child;
10454       while (child_die && child_die->tag)
10455         {
10456           process_die (child_die, cu);
10457           child_die = sibling_die (child_die);
10458         }
10459     }
10460
10461   /* Decode macro information, if present.  Dwarf 2 macro information
10462      refers to information in the line number info statement program
10463      header, so we can only read it if we've read the header
10464      successfully.  */
10465   attr = dwarf2_attr (die, DW_AT_macros, cu);
10466   if (attr == NULL)
10467     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
10468   if (attr && cu->line_header)
10469     {
10470       if (dwarf2_attr (die, DW_AT_macro_info, cu))
10471         complaint (&symfile_complaints,
10472                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
10473
10474       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
10475     }
10476   else
10477     {
10478       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
10479       if (attr && cu->line_header)
10480         {
10481           unsigned int macro_offset = DW_UNSND (attr);
10482
10483           dwarf_decode_macros (cu, macro_offset, 0);
10484         }
10485     }
10486 }
10487
10488 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
10489    Create the set of symtabs used by this TU, or if this TU is sharing
10490    symtabs with another TU and the symtabs have already been created
10491    then restore those symtabs in the line header.
10492    We don't need the pc/line-number mapping for type units.  */
10493
10494 static void
10495 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
10496 {
10497   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
10498   struct type_unit_group *tu_group;
10499   int first_time;
10500   struct attribute *attr;
10501   unsigned int i;
10502   struct signatured_type *sig_type;
10503
10504   gdb_assert (per_cu->is_debug_types);
10505   sig_type = (struct signatured_type *) per_cu;
10506
10507   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
10508
10509   /* If we're using .gdb_index (includes -readnow) then
10510      per_cu->type_unit_group may not have been set up yet.  */
10511   if (sig_type->type_unit_group == NULL)
10512     sig_type->type_unit_group = get_type_unit_group (cu, attr);
10513   tu_group = sig_type->type_unit_group;
10514
10515   /* If we've already processed this stmt_list there's no real need to
10516      do it again, we could fake it and just recreate the part we need
10517      (file name,index -> symtab mapping).  If data shows this optimization
10518      is useful we can do it then.  */
10519   first_time = tu_group->compunit_symtab == NULL;
10520
10521   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
10522      debug info.  */
10523   line_header_up lh;
10524   if (attr != NULL)
10525     {
10526       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
10527       lh = dwarf_decode_line_header (line_offset, cu);
10528     }
10529   if (lh == NULL)
10530     {
10531       if (first_time)
10532         dwarf2_start_symtab (cu, "", NULL, 0);
10533       else
10534         {
10535           gdb_assert (tu_group->symtabs == NULL);
10536           restart_symtab (tu_group->compunit_symtab, "", 0);
10537         }
10538       return;
10539     }
10540
10541   cu->line_header = lh.release ();
10542   cu->line_header_die_owner = die;
10543
10544   if (first_time)
10545     {
10546       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
10547
10548       /* Note: We don't assign tu_group->compunit_symtab yet because we're
10549          still initializing it, and our caller (a few levels up)
10550          process_full_type_unit still needs to know if this is the first
10551          time.  */
10552
10553       tu_group->num_symtabs = cu->line_header->file_names.size ();
10554       tu_group->symtabs = XNEWVEC (struct symtab *,
10555                                    cu->line_header->file_names.size ());
10556
10557       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10558         {
10559           file_entry &fe = cu->line_header->file_names[i];
10560
10561           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
10562
10563           if (current_subfile->symtab == NULL)
10564             {
10565               /* NOTE: start_subfile will recognize when it's been
10566                  passed a file it has already seen.  So we can't
10567                  assume there's a simple mapping from
10568                  cu->line_header->file_names to subfiles, plus
10569                  cu->line_header->file_names may contain dups.  */
10570               current_subfile->symtab
10571                 = allocate_symtab (cust, current_subfile->name);
10572             }
10573
10574           fe.symtab = current_subfile->symtab;
10575           tu_group->symtabs[i] = fe.symtab;
10576         }
10577     }
10578   else
10579     {
10580       restart_symtab (tu_group->compunit_symtab, "", 0);
10581
10582       for (i = 0; i < cu->line_header->file_names.size (); ++i)
10583         {
10584           file_entry &fe = cu->line_header->file_names[i];
10585
10586           fe.symtab = tu_group->symtabs[i];
10587         }
10588     }
10589
10590   /* The main symtab is allocated last.  Type units don't have DW_AT_name
10591      so they don't have a "real" (so to speak) symtab anyway.
10592      There is later code that will assign the main symtab to all symbols
10593      that don't have one.  We need to handle the case of a symbol with a
10594      missing symtab (DW_AT_decl_file) anyway.  */
10595 }
10596
10597 /* Process DW_TAG_type_unit.
10598    For TUs we want to skip the first top level sibling if it's not the
10599    actual type being defined by this TU.  In this case the first top
10600    level sibling is there to provide context only.  */
10601
10602 static void
10603 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
10604 {
10605   struct die_info *child_die;
10606
10607   prepare_one_comp_unit (cu, die, language_minimal);
10608
10609   /* Initialize (or reinitialize) the machinery for building symtabs.
10610      We do this before processing child DIEs, so that the line header table
10611      is available for DW_AT_decl_file.  */
10612   setup_type_unit_groups (die, cu);
10613
10614   if (die->child != NULL)
10615     {
10616       child_die = die->child;
10617       while (child_die && child_die->tag)
10618         {
10619           process_die (child_die, cu);
10620           child_die = sibling_die (child_die);
10621         }
10622     }
10623 }
10624 \f
10625 /* DWO/DWP files.
10626
10627    http://gcc.gnu.org/wiki/DebugFission
10628    http://gcc.gnu.org/wiki/DebugFissionDWP
10629
10630    To simplify handling of both DWO files ("object" files with the DWARF info)
10631    and DWP files (a file with the DWOs packaged up into one file), we treat
10632    DWP files as having a collection of virtual DWO files.  */
10633
10634 static hashval_t
10635 hash_dwo_file (const void *item)
10636 {
10637   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10638   hashval_t hash;
10639
10640   hash = htab_hash_string (dwo_file->dwo_name);
10641   if (dwo_file->comp_dir != NULL)
10642     hash += htab_hash_string (dwo_file->comp_dir);
10643   return hash;
10644 }
10645
10646 static int
10647 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10648 {
10649   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10650   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10651
10652   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10653     return 0;
10654   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10655     return lhs->comp_dir == rhs->comp_dir;
10656   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10657 }
10658
10659 /* Allocate a hash table for DWO files.  */
10660
10661 static htab_t
10662 allocate_dwo_file_hash_table (void)
10663 {
10664   struct objfile *objfile = dwarf2_per_objfile->objfile;
10665
10666   return htab_create_alloc_ex (41,
10667                                hash_dwo_file,
10668                                eq_dwo_file,
10669                                NULL,
10670                                &objfile->objfile_obstack,
10671                                hashtab_obstack_allocate,
10672                                dummy_obstack_deallocate);
10673 }
10674
10675 /* Lookup DWO file DWO_NAME.  */
10676
10677 static void **
10678 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10679 {
10680   struct dwo_file find_entry;
10681   void **slot;
10682
10683   if (dwarf2_per_objfile->dwo_files == NULL)
10684     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10685
10686   memset (&find_entry, 0, sizeof (find_entry));
10687   find_entry.dwo_name = dwo_name;
10688   find_entry.comp_dir = comp_dir;
10689   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10690
10691   return slot;
10692 }
10693
10694 static hashval_t
10695 hash_dwo_unit (const void *item)
10696 {
10697   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10698
10699   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10700   return dwo_unit->signature;
10701 }
10702
10703 static int
10704 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10705 {
10706   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10707   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10708
10709   /* The signature is assumed to be unique within the DWO file.
10710      So while object file CU dwo_id's always have the value zero,
10711      that's OK, assuming each object file DWO file has only one CU,
10712      and that's the rule for now.  */
10713   return lhs->signature == rhs->signature;
10714 }
10715
10716 /* Allocate a hash table for DWO CUs,TUs.
10717    There is one of these tables for each of CUs,TUs for each DWO file.  */
10718
10719 static htab_t
10720 allocate_dwo_unit_table (struct objfile *objfile)
10721 {
10722   /* Start out with a pretty small number.
10723      Generally DWO files contain only one CU and maybe some TUs.  */
10724   return htab_create_alloc_ex (3,
10725                                hash_dwo_unit,
10726                                eq_dwo_unit,
10727                                NULL,
10728                                &objfile->objfile_obstack,
10729                                hashtab_obstack_allocate,
10730                                dummy_obstack_deallocate);
10731 }
10732
10733 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10734
10735 struct create_dwo_cu_data
10736 {
10737   struct dwo_file *dwo_file;
10738   struct dwo_unit dwo_unit;
10739 };
10740
10741 /* die_reader_func for create_dwo_cu.  */
10742
10743 static void
10744 create_dwo_cu_reader (const struct die_reader_specs *reader,
10745                       const gdb_byte *info_ptr,
10746                       struct die_info *comp_unit_die,
10747                       int has_children,
10748                       void *datap)
10749 {
10750   struct dwarf2_cu *cu = reader->cu;
10751   sect_offset sect_off = cu->per_cu->sect_off;
10752   struct dwarf2_section_info *section = cu->per_cu->section;
10753   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10754   struct dwo_file *dwo_file = data->dwo_file;
10755   struct dwo_unit *dwo_unit = &data->dwo_unit;
10756   struct attribute *attr;
10757
10758   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10759   if (attr == NULL)
10760     {
10761       complaint (&symfile_complaints,
10762                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10763                    " its dwo_id [in module %s]"),
10764                  to_underlying (sect_off), dwo_file->dwo_name);
10765       return;
10766     }
10767
10768   dwo_unit->dwo_file = dwo_file;
10769   dwo_unit->signature = DW_UNSND (attr);
10770   dwo_unit->section = section;
10771   dwo_unit->sect_off = sect_off;
10772   dwo_unit->length = cu->per_cu->length;
10773
10774   if (dwarf_read_debug)
10775     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10776                         to_underlying (sect_off),
10777                         hex_string (dwo_unit->signature));
10778 }
10779
10780 /* Create the dwo_units for the CUs in a DWO_FILE.
10781    Note: This function processes DWO files only, not DWP files.  */
10782
10783 static void
10784 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10785                        htab_t &cus_htab)
10786 {
10787   struct objfile *objfile = dwarf2_per_objfile->objfile;
10788   const gdb_byte *info_ptr, *end_ptr;
10789
10790   dwarf2_read_section (objfile, &section);
10791   info_ptr = section.buffer;
10792
10793   if (info_ptr == NULL)
10794     return;
10795
10796   if (dwarf_read_debug)
10797     {
10798       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10799                           get_section_name (&section),
10800                           get_section_file_name (&section));
10801     }
10802
10803   end_ptr = info_ptr + section.size;
10804   while (info_ptr < end_ptr)
10805     {
10806       struct dwarf2_per_cu_data per_cu;
10807       struct create_dwo_cu_data create_dwo_cu_data;
10808       struct dwo_unit *dwo_unit;
10809       void **slot;
10810       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10811
10812       memset (&create_dwo_cu_data.dwo_unit, 0,
10813               sizeof (create_dwo_cu_data.dwo_unit));
10814       memset (&per_cu, 0, sizeof (per_cu));
10815       per_cu.objfile = objfile;
10816       per_cu.is_debug_types = 0;
10817       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10818       per_cu.section = &section;
10819       create_dwo_cu_data.dwo_file = &dwo_file;
10820
10821       init_cutu_and_read_dies_no_follow (
10822           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10823       info_ptr += per_cu.length;
10824
10825       // If the unit could not be parsed, skip it.
10826       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10827         continue;
10828
10829       if (cus_htab == NULL)
10830         cus_htab = allocate_dwo_unit_table (objfile);
10831
10832       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10833       *dwo_unit = create_dwo_cu_data.dwo_unit;
10834       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10835       gdb_assert (slot != NULL);
10836       if (*slot != NULL)
10837         {
10838           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10839           sect_offset dup_sect_off = dup_cu->sect_off;
10840
10841           complaint (&symfile_complaints,
10842                      _("debug cu entry at offset 0x%x is duplicate to"
10843                        " the entry at offset 0x%x, signature %s"),
10844                      to_underlying (sect_off), to_underlying (dup_sect_off),
10845                      hex_string (dwo_unit->signature));
10846         }
10847       *slot = (void *)dwo_unit;
10848     }
10849 }
10850
10851 /* DWP file .debug_{cu,tu}_index section format:
10852    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10853
10854    DWP Version 1:
10855
10856    Both index sections have the same format, and serve to map a 64-bit
10857    signature to a set of section numbers.  Each section begins with a header,
10858    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10859    indexes, and a pool of 32-bit section numbers.  The index sections will be
10860    aligned at 8-byte boundaries in the file.
10861
10862    The index section header consists of:
10863
10864     V, 32 bit version number
10865     -, 32 bits unused
10866     N, 32 bit number of compilation units or type units in the index
10867     M, 32 bit number of slots in the hash table
10868
10869    Numbers are recorded using the byte order of the application binary.
10870
10871    The hash table begins at offset 16 in the section, and consists of an array
10872    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10873    order of the application binary).  Unused slots in the hash table are 0.
10874    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10875
10876    The parallel table begins immediately after the hash table
10877    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10878    array of 32-bit indexes (using the byte order of the application binary),
10879    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10880    table contains a 32-bit index into the pool of section numbers.  For unused
10881    hash table slots, the corresponding entry in the parallel table will be 0.
10882
10883    The pool of section numbers begins immediately following the hash table
10884    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10885    section numbers consists of an array of 32-bit words (using the byte order
10886    of the application binary).  Each item in the array is indexed starting
10887    from 0.  The hash table entry provides the index of the first section
10888    number in the set.  Additional section numbers in the set follow, and the
10889    set is terminated by a 0 entry (section number 0 is not used in ELF).
10890
10891    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10892    section must be the first entry in the set, and the .debug_abbrev.dwo must
10893    be the second entry. Other members of the set may follow in any order.
10894
10895    ---
10896
10897    DWP Version 2:
10898
10899    DWP Version 2 combines all the .debug_info, etc. sections into one,
10900    and the entries in the index tables are now offsets into these sections.
10901    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10902    section.
10903
10904    Index Section Contents:
10905     Header
10906     Hash Table of Signatures   dwp_hash_table.hash_table
10907     Parallel Table of Indices  dwp_hash_table.unit_table
10908     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10909     Table of Section Sizes     dwp_hash_table.v2.sizes
10910
10911    The index section header consists of:
10912
10913     V, 32 bit version number
10914     L, 32 bit number of columns in the table of section offsets
10915     N, 32 bit number of compilation units or type units in the index
10916     M, 32 bit number of slots in the hash table
10917
10918    Numbers are recorded using the byte order of the application binary.
10919
10920    The hash table has the same format as version 1.
10921    The parallel table of indices has the same format as version 1,
10922    except that the entries are origin-1 indices into the table of sections
10923    offsets and the table of section sizes.
10924
10925    The table of offsets begins immediately following the parallel table
10926    (at offset 16 + 12 * M from the beginning of the section).  The table is
10927    a two-dimensional array of 32-bit words (using the byte order of the
10928    application binary), with L columns and N+1 rows, in row-major order.
10929    Each row in the array is indexed starting from 0.  The first row provides
10930    a key to the remaining rows: each column in this row provides an identifier
10931    for a debug section, and the offsets in the same column of subsequent rows
10932    refer to that section.  The section identifiers are:
10933
10934     DW_SECT_INFO         1  .debug_info.dwo
10935     DW_SECT_TYPES        2  .debug_types.dwo
10936     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10937     DW_SECT_LINE         4  .debug_line.dwo
10938     DW_SECT_LOC          5  .debug_loc.dwo
10939     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10940     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10941     DW_SECT_MACRO        8  .debug_macro.dwo
10942
10943    The offsets provided by the CU and TU index sections are the base offsets
10944    for the contributions made by each CU or TU to the corresponding section
10945    in the package file.  Each CU and TU header contains an abbrev_offset
10946    field, used to find the abbreviations table for that CU or TU within the
10947    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10948    be interpreted as relative to the base offset given in the index section.
10949    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10950    should be interpreted as relative to the base offset for .debug_line.dwo,
10951    and offsets into other debug sections obtained from DWARF attributes should
10952    also be interpreted as relative to the corresponding base offset.
10953
10954    The table of sizes begins immediately following the table of offsets.
10955    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10956    with L columns and N rows, in row-major order.  Each row in the array is
10957    indexed starting from 1 (row 0 is shared by the two tables).
10958
10959    ---
10960
10961    Hash table lookup is handled the same in version 1 and 2:
10962
10963    We assume that N and M will not exceed 2^32 - 1.
10964    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10965
10966    Given a 64-bit compilation unit signature or a type signature S, an entry
10967    in the hash table is located as follows:
10968
10969    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10970       the low-order k bits all set to 1.
10971
10972    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10973
10974    3) If the hash table entry at index H matches the signature, use that
10975       entry.  If the hash table entry at index H is unused (all zeroes),
10976       terminate the search: the signature is not present in the table.
10977
10978    4) Let H = (H + H') modulo M. Repeat at Step 3.
10979
10980    Because M > N and H' and M are relatively prime, the search is guaranteed
10981    to stop at an unused slot or find the match.  */
10982
10983 /* Create a hash table to map DWO IDs to their CU/TU entry in
10984    .debug_{info,types}.dwo in DWP_FILE.
10985    Returns NULL if there isn't one.
10986    Note: This function processes DWP files only, not DWO files.  */
10987
10988 static struct dwp_hash_table *
10989 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10990 {
10991   struct objfile *objfile = dwarf2_per_objfile->objfile;
10992   bfd *dbfd = dwp_file->dbfd;
10993   const gdb_byte *index_ptr, *index_end;
10994   struct dwarf2_section_info *index;
10995   uint32_t version, nr_columns, nr_units, nr_slots;
10996   struct dwp_hash_table *htab;
10997
10998   if (is_debug_types)
10999     index = &dwp_file->sections.tu_index;
11000   else
11001     index = &dwp_file->sections.cu_index;
11002
11003   if (dwarf2_section_empty_p (index))
11004     return NULL;
11005   dwarf2_read_section (objfile, index);
11006
11007   index_ptr = index->buffer;
11008   index_end = index_ptr + index->size;
11009
11010   version = read_4_bytes (dbfd, index_ptr);
11011   index_ptr += 4;
11012   if (version == 2)
11013     nr_columns = read_4_bytes (dbfd, index_ptr);
11014   else
11015     nr_columns = 0;
11016   index_ptr += 4;
11017   nr_units = read_4_bytes (dbfd, index_ptr);
11018   index_ptr += 4;
11019   nr_slots = read_4_bytes (dbfd, index_ptr);
11020   index_ptr += 4;
11021
11022   if (version != 1 && version != 2)
11023     {
11024       error (_("Dwarf Error: unsupported DWP file version (%s)"
11025                " [in module %s]"),
11026              pulongest (version), dwp_file->name);
11027     }
11028   if (nr_slots != (nr_slots & -nr_slots))
11029     {
11030       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
11031                " is not power of 2 [in module %s]"),
11032              pulongest (nr_slots), dwp_file->name);
11033     }
11034
11035   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
11036   htab->version = version;
11037   htab->nr_columns = nr_columns;
11038   htab->nr_units = nr_units;
11039   htab->nr_slots = nr_slots;
11040   htab->hash_table = index_ptr;
11041   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
11042
11043   /* Exit early if the table is empty.  */
11044   if (nr_slots == 0 || nr_units == 0
11045       || (version == 2 && nr_columns == 0))
11046     {
11047       /* All must be zero.  */
11048       if (nr_slots != 0 || nr_units != 0
11049           || (version == 2 && nr_columns != 0))
11050         {
11051           complaint (&symfile_complaints,
11052                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
11053                        " all zero [in modules %s]"),
11054                      dwp_file->name);
11055         }
11056       return htab;
11057     }
11058
11059   if (version == 1)
11060     {
11061       htab->section_pool.v1.indices =
11062         htab->unit_table + sizeof (uint32_t) * nr_slots;
11063       /* It's harder to decide whether the section is too small in v1.
11064          V1 is deprecated anyway so we punt.  */
11065     }
11066   else
11067     {
11068       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
11069       int *ids = htab->section_pool.v2.section_ids;
11070       /* Reverse map for error checking.  */
11071       int ids_seen[DW_SECT_MAX + 1];
11072       int i;
11073
11074       if (nr_columns < 2)
11075         {
11076           error (_("Dwarf Error: bad DWP hash table, too few columns"
11077                    " in section table [in module %s]"),
11078                  dwp_file->name);
11079         }
11080       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
11081         {
11082           error (_("Dwarf Error: bad DWP hash table, too many columns"
11083                    " in section table [in module %s]"),
11084                  dwp_file->name);
11085         }
11086       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11087       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
11088       for (i = 0; i < nr_columns; ++i)
11089         {
11090           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
11091
11092           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
11093             {
11094               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
11095                        " in section table [in module %s]"),
11096                      id, dwp_file->name);
11097             }
11098           if (ids_seen[id] != -1)
11099             {
11100               error (_("Dwarf Error: bad DWP hash table, duplicate section"
11101                        " id %d in section table [in module %s]"),
11102                      id, dwp_file->name);
11103             }
11104           ids_seen[id] = i;
11105           ids[i] = id;
11106         }
11107       /* Must have exactly one info or types section.  */
11108       if (((ids_seen[DW_SECT_INFO] != -1)
11109            + (ids_seen[DW_SECT_TYPES] != -1))
11110           != 1)
11111         {
11112           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
11113                    " DWO info/types section [in module %s]"),
11114                  dwp_file->name);
11115         }
11116       /* Must have an abbrev section.  */
11117       if (ids_seen[DW_SECT_ABBREV] == -1)
11118         {
11119           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
11120                    " section [in module %s]"),
11121                  dwp_file->name);
11122         }
11123       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
11124       htab->section_pool.v2.sizes =
11125         htab->section_pool.v2.offsets + (sizeof (uint32_t)
11126                                          * nr_units * nr_columns);
11127       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
11128                                           * nr_units * nr_columns))
11129           > index_end)
11130         {
11131           error (_("Dwarf Error: DWP index section is corrupt (too small)"
11132                    " [in module %s]"),
11133                  dwp_file->name);
11134         }
11135     }
11136
11137   return htab;
11138 }
11139
11140 /* Update SECTIONS with the data from SECTP.
11141
11142    This function is like the other "locate" section routines that are
11143    passed to bfd_map_over_sections, but in this context the sections to
11144    read comes from the DWP V1 hash table, not the full ELF section table.
11145
11146    The result is non-zero for success, or zero if an error was found.  */
11147
11148 static int
11149 locate_v1_virtual_dwo_sections (asection *sectp,
11150                                 struct virtual_v1_dwo_sections *sections)
11151 {
11152   const struct dwop_section_names *names = &dwop_section_names;
11153
11154   if (section_is_p (sectp->name, &names->abbrev_dwo))
11155     {
11156       /* There can be only one.  */
11157       if (sections->abbrev.s.section != NULL)
11158         return 0;
11159       sections->abbrev.s.section = sectp;
11160       sections->abbrev.size = bfd_get_section_size (sectp);
11161     }
11162   else if (section_is_p (sectp->name, &names->info_dwo)
11163            || section_is_p (sectp->name, &names->types_dwo))
11164     {
11165       /* There can be only one.  */
11166       if (sections->info_or_types.s.section != NULL)
11167         return 0;
11168       sections->info_or_types.s.section = sectp;
11169       sections->info_or_types.size = bfd_get_section_size (sectp);
11170     }
11171   else if (section_is_p (sectp->name, &names->line_dwo))
11172     {
11173       /* There can be only one.  */
11174       if (sections->line.s.section != NULL)
11175         return 0;
11176       sections->line.s.section = sectp;
11177       sections->line.size = bfd_get_section_size (sectp);
11178     }
11179   else if (section_is_p (sectp->name, &names->loc_dwo))
11180     {
11181       /* There can be only one.  */
11182       if (sections->loc.s.section != NULL)
11183         return 0;
11184       sections->loc.s.section = sectp;
11185       sections->loc.size = bfd_get_section_size (sectp);
11186     }
11187   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11188     {
11189       /* There can be only one.  */
11190       if (sections->macinfo.s.section != NULL)
11191         return 0;
11192       sections->macinfo.s.section = sectp;
11193       sections->macinfo.size = bfd_get_section_size (sectp);
11194     }
11195   else if (section_is_p (sectp->name, &names->macro_dwo))
11196     {
11197       /* There can be only one.  */
11198       if (sections->macro.s.section != NULL)
11199         return 0;
11200       sections->macro.s.section = sectp;
11201       sections->macro.size = bfd_get_section_size (sectp);
11202     }
11203   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11204     {
11205       /* There can be only one.  */
11206       if (sections->str_offsets.s.section != NULL)
11207         return 0;
11208       sections->str_offsets.s.section = sectp;
11209       sections->str_offsets.size = bfd_get_section_size (sectp);
11210     }
11211   else
11212     {
11213       /* No other kind of section is valid.  */
11214       return 0;
11215     }
11216
11217   return 1;
11218 }
11219
11220 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11221    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11222    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11223    This is for DWP version 1 files.  */
11224
11225 static struct dwo_unit *
11226 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
11227                            uint32_t unit_index,
11228                            const char *comp_dir,
11229                            ULONGEST signature, int is_debug_types)
11230 {
11231   struct objfile *objfile = dwarf2_per_objfile->objfile;
11232   const struct dwp_hash_table *dwp_htab =
11233     is_debug_types ? dwp_file->tus : dwp_file->cus;
11234   bfd *dbfd = dwp_file->dbfd;
11235   const char *kind = is_debug_types ? "TU" : "CU";
11236   struct dwo_file *dwo_file;
11237   struct dwo_unit *dwo_unit;
11238   struct virtual_v1_dwo_sections sections;
11239   void **dwo_file_slot;
11240   int i;
11241
11242   gdb_assert (dwp_file->version == 1);
11243
11244   if (dwarf_read_debug)
11245     {
11246       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
11247                           kind,
11248                           pulongest (unit_index), hex_string (signature),
11249                           dwp_file->name);
11250     }
11251
11252   /* Fetch the sections of this DWO unit.
11253      Put a limit on the number of sections we look for so that bad data
11254      doesn't cause us to loop forever.  */
11255
11256 #define MAX_NR_V1_DWO_SECTIONS \
11257   (1 /* .debug_info or .debug_types */ \
11258    + 1 /* .debug_abbrev */ \
11259    + 1 /* .debug_line */ \
11260    + 1 /* .debug_loc */ \
11261    + 1 /* .debug_str_offsets */ \
11262    + 1 /* .debug_macro or .debug_macinfo */ \
11263    + 1 /* trailing zero */)
11264
11265   memset (&sections, 0, sizeof (sections));
11266
11267   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
11268     {
11269       asection *sectp;
11270       uint32_t section_nr =
11271         read_4_bytes (dbfd,
11272                       dwp_htab->section_pool.v1.indices
11273                       + (unit_index + i) * sizeof (uint32_t));
11274
11275       if (section_nr == 0)
11276         break;
11277       if (section_nr >= dwp_file->num_sections)
11278         {
11279           error (_("Dwarf Error: bad DWP hash table, section number too large"
11280                    " [in module %s]"),
11281                  dwp_file->name);
11282         }
11283
11284       sectp = dwp_file->elf_sections[section_nr];
11285       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
11286         {
11287           error (_("Dwarf Error: bad DWP hash table, invalid section found"
11288                    " [in module %s]"),
11289                  dwp_file->name);
11290         }
11291     }
11292
11293   if (i < 2
11294       || dwarf2_section_empty_p (&sections.info_or_types)
11295       || dwarf2_section_empty_p (&sections.abbrev))
11296     {
11297       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
11298                " [in module %s]"),
11299              dwp_file->name);
11300     }
11301   if (i == MAX_NR_V1_DWO_SECTIONS)
11302     {
11303       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
11304                " [in module %s]"),
11305              dwp_file->name);
11306     }
11307
11308   /* It's easier for the rest of the code if we fake a struct dwo_file and
11309      have dwo_unit "live" in that.  At least for now.
11310
11311      The DWP file can be made up of a random collection of CUs and TUs.
11312      However, for each CU + set of TUs that came from the same original DWO
11313      file, we can combine them back into a virtual DWO file to save space
11314      (fewer struct dwo_file objects to allocate).  Remember that for really
11315      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11316
11317   std::string virtual_dwo_name =
11318     string_printf ("virtual-dwo/%d-%d-%d-%d",
11319                    get_section_id (&sections.abbrev),
11320                    get_section_id (&sections.line),
11321                    get_section_id (&sections.loc),
11322                    get_section_id (&sections.str_offsets));
11323   /* Can we use an existing virtual DWO file?  */
11324   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11325   /* Create one if necessary.  */
11326   if (*dwo_file_slot == NULL)
11327     {
11328       if (dwarf_read_debug)
11329         {
11330           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11331                               virtual_dwo_name.c_str ());
11332         }
11333       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11334       dwo_file->dwo_name
11335         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11336                                         virtual_dwo_name.c_str (),
11337                                         virtual_dwo_name.size ());
11338       dwo_file->comp_dir = comp_dir;
11339       dwo_file->sections.abbrev = sections.abbrev;
11340       dwo_file->sections.line = sections.line;
11341       dwo_file->sections.loc = sections.loc;
11342       dwo_file->sections.macinfo = sections.macinfo;
11343       dwo_file->sections.macro = sections.macro;
11344       dwo_file->sections.str_offsets = sections.str_offsets;
11345       /* The "str" section is global to the entire DWP file.  */
11346       dwo_file->sections.str = dwp_file->sections.str;
11347       /* The info or types section is assigned below to dwo_unit,
11348          there's no need to record it in dwo_file.
11349          Also, we can't simply record type sections in dwo_file because
11350          we record a pointer into the vector in dwo_unit.  As we collect more
11351          types we'll grow the vector and eventually have to reallocate space
11352          for it, invalidating all copies of pointers into the previous
11353          contents.  */
11354       *dwo_file_slot = dwo_file;
11355     }
11356   else
11357     {
11358       if (dwarf_read_debug)
11359         {
11360           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11361                               virtual_dwo_name.c_str ());
11362         }
11363       dwo_file = (struct dwo_file *) *dwo_file_slot;
11364     }
11365
11366   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11367   dwo_unit->dwo_file = dwo_file;
11368   dwo_unit->signature = signature;
11369   dwo_unit->section =
11370     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11371   *dwo_unit->section = sections.info_or_types;
11372   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11373
11374   return dwo_unit;
11375 }
11376
11377 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
11378    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
11379    piece within that section used by a TU/CU, return a virtual section
11380    of just that piece.  */
11381
11382 static struct dwarf2_section_info
11383 create_dwp_v2_section (struct dwarf2_section_info *section,
11384                        bfd_size_type offset, bfd_size_type size)
11385 {
11386   struct dwarf2_section_info result;
11387   asection *sectp;
11388
11389   gdb_assert (section != NULL);
11390   gdb_assert (!section->is_virtual);
11391
11392   memset (&result, 0, sizeof (result));
11393   result.s.containing_section = section;
11394   result.is_virtual = 1;
11395
11396   if (size == 0)
11397     return result;
11398
11399   sectp = get_section_bfd_section (section);
11400
11401   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
11402      bounds of the real section.  This is a pretty-rare event, so just
11403      flag an error (easier) instead of a warning and trying to cope.  */
11404   if (sectp == NULL
11405       || offset + size > bfd_get_section_size (sectp))
11406     {
11407       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
11408                " in section %s [in module %s]"),
11409              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
11410              objfile_name (dwarf2_per_objfile->objfile));
11411     }
11412
11413   result.virtual_offset = offset;
11414   result.size = size;
11415   return result;
11416 }
11417
11418 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
11419    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
11420    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
11421    This is for DWP version 2 files.  */
11422
11423 static struct dwo_unit *
11424 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
11425                            uint32_t unit_index,
11426                            const char *comp_dir,
11427                            ULONGEST signature, int is_debug_types)
11428 {
11429   struct objfile *objfile = dwarf2_per_objfile->objfile;
11430   const struct dwp_hash_table *dwp_htab =
11431     is_debug_types ? dwp_file->tus : dwp_file->cus;
11432   bfd *dbfd = dwp_file->dbfd;
11433   const char *kind = is_debug_types ? "TU" : "CU";
11434   struct dwo_file *dwo_file;
11435   struct dwo_unit *dwo_unit;
11436   struct virtual_v2_dwo_sections sections;
11437   void **dwo_file_slot;
11438   int i;
11439
11440   gdb_assert (dwp_file->version == 2);
11441
11442   if (dwarf_read_debug)
11443     {
11444       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
11445                           kind,
11446                           pulongest (unit_index), hex_string (signature),
11447                           dwp_file->name);
11448     }
11449
11450   /* Fetch the section offsets of this DWO unit.  */
11451
11452   memset (&sections, 0, sizeof (sections));
11453
11454   for (i = 0; i < dwp_htab->nr_columns; ++i)
11455     {
11456       uint32_t offset = read_4_bytes (dbfd,
11457                                       dwp_htab->section_pool.v2.offsets
11458                                       + (((unit_index - 1) * dwp_htab->nr_columns
11459                                           + i)
11460                                          * sizeof (uint32_t)));
11461       uint32_t size = read_4_bytes (dbfd,
11462                                     dwp_htab->section_pool.v2.sizes
11463                                     + (((unit_index - 1) * dwp_htab->nr_columns
11464                                         + i)
11465                                        * sizeof (uint32_t)));
11466
11467       switch (dwp_htab->section_pool.v2.section_ids[i])
11468         {
11469         case DW_SECT_INFO:
11470         case DW_SECT_TYPES:
11471           sections.info_or_types_offset = offset;
11472           sections.info_or_types_size = size;
11473           break;
11474         case DW_SECT_ABBREV:
11475           sections.abbrev_offset = offset;
11476           sections.abbrev_size = size;
11477           break;
11478         case DW_SECT_LINE:
11479           sections.line_offset = offset;
11480           sections.line_size = size;
11481           break;
11482         case DW_SECT_LOC:
11483           sections.loc_offset = offset;
11484           sections.loc_size = size;
11485           break;
11486         case DW_SECT_STR_OFFSETS:
11487           sections.str_offsets_offset = offset;
11488           sections.str_offsets_size = size;
11489           break;
11490         case DW_SECT_MACINFO:
11491           sections.macinfo_offset = offset;
11492           sections.macinfo_size = size;
11493           break;
11494         case DW_SECT_MACRO:
11495           sections.macro_offset = offset;
11496           sections.macro_size = size;
11497           break;
11498         }
11499     }
11500
11501   /* It's easier for the rest of the code if we fake a struct dwo_file and
11502      have dwo_unit "live" in that.  At least for now.
11503
11504      The DWP file can be made up of a random collection of CUs and TUs.
11505      However, for each CU + set of TUs that came from the same original DWO
11506      file, we can combine them back into a virtual DWO file to save space
11507      (fewer struct dwo_file objects to allocate).  Remember that for really
11508      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
11509
11510   std::string virtual_dwo_name =
11511     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
11512                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
11513                    (long) (sections.line_size ? sections.line_offset : 0),
11514                    (long) (sections.loc_size ? sections.loc_offset : 0),
11515                    (long) (sections.str_offsets_size
11516                            ? sections.str_offsets_offset : 0));
11517   /* Can we use an existing virtual DWO file?  */
11518   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
11519   /* Create one if necessary.  */
11520   if (*dwo_file_slot == NULL)
11521     {
11522       if (dwarf_read_debug)
11523         {
11524           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
11525                               virtual_dwo_name.c_str ());
11526         }
11527       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11528       dwo_file->dwo_name
11529         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
11530                                         virtual_dwo_name.c_str (),
11531                                         virtual_dwo_name.size ());
11532       dwo_file->comp_dir = comp_dir;
11533       dwo_file->sections.abbrev =
11534         create_dwp_v2_section (&dwp_file->sections.abbrev,
11535                                sections.abbrev_offset, sections.abbrev_size);
11536       dwo_file->sections.line =
11537         create_dwp_v2_section (&dwp_file->sections.line,
11538                                sections.line_offset, sections.line_size);
11539       dwo_file->sections.loc =
11540         create_dwp_v2_section (&dwp_file->sections.loc,
11541                                sections.loc_offset, sections.loc_size);
11542       dwo_file->sections.macinfo =
11543         create_dwp_v2_section (&dwp_file->sections.macinfo,
11544                                sections.macinfo_offset, sections.macinfo_size);
11545       dwo_file->sections.macro =
11546         create_dwp_v2_section (&dwp_file->sections.macro,
11547                                sections.macro_offset, sections.macro_size);
11548       dwo_file->sections.str_offsets =
11549         create_dwp_v2_section (&dwp_file->sections.str_offsets,
11550                                sections.str_offsets_offset,
11551                                sections.str_offsets_size);
11552       /* The "str" section is global to the entire DWP file.  */
11553       dwo_file->sections.str = dwp_file->sections.str;
11554       /* The info or types section is assigned below to dwo_unit,
11555          there's no need to record it in dwo_file.
11556          Also, we can't simply record type sections in dwo_file because
11557          we record a pointer into the vector in dwo_unit.  As we collect more
11558          types we'll grow the vector and eventually have to reallocate space
11559          for it, invalidating all copies of pointers into the previous
11560          contents.  */
11561       *dwo_file_slot = dwo_file;
11562     }
11563   else
11564     {
11565       if (dwarf_read_debug)
11566         {
11567           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
11568                               virtual_dwo_name.c_str ());
11569         }
11570       dwo_file = (struct dwo_file *) *dwo_file_slot;
11571     }
11572
11573   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
11574   dwo_unit->dwo_file = dwo_file;
11575   dwo_unit->signature = signature;
11576   dwo_unit->section =
11577     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
11578   *dwo_unit->section = create_dwp_v2_section (is_debug_types
11579                                               ? &dwp_file->sections.types
11580                                               : &dwp_file->sections.info,
11581                                               sections.info_or_types_offset,
11582                                               sections.info_or_types_size);
11583   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
11584
11585   return dwo_unit;
11586 }
11587
11588 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
11589    Returns NULL if the signature isn't found.  */
11590
11591 static struct dwo_unit *
11592 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
11593                         ULONGEST signature, int is_debug_types)
11594 {
11595   const struct dwp_hash_table *dwp_htab =
11596     is_debug_types ? dwp_file->tus : dwp_file->cus;
11597   bfd *dbfd = dwp_file->dbfd;
11598   uint32_t mask = dwp_htab->nr_slots - 1;
11599   uint32_t hash = signature & mask;
11600   uint32_t hash2 = ((signature >> 32) & mask) | 1;
11601   unsigned int i;
11602   void **slot;
11603   struct dwo_unit find_dwo_cu;
11604
11605   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
11606   find_dwo_cu.signature = signature;
11607   slot = htab_find_slot (is_debug_types
11608                          ? dwp_file->loaded_tus
11609                          : dwp_file->loaded_cus,
11610                          &find_dwo_cu, INSERT);
11611
11612   if (*slot != NULL)
11613     return (struct dwo_unit *) *slot;
11614
11615   /* Use a for loop so that we don't loop forever on bad debug info.  */
11616   for (i = 0; i < dwp_htab->nr_slots; ++i)
11617     {
11618       ULONGEST signature_in_table;
11619
11620       signature_in_table =
11621         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11622       if (signature_in_table == signature)
11623         {
11624           uint32_t unit_index =
11625             read_4_bytes (dbfd,
11626                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11627
11628           if (dwp_file->version == 1)
11629             {
11630               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11631                                                  comp_dir, signature,
11632                                                  is_debug_types);
11633             }
11634           else
11635             {
11636               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11637                                                  comp_dir, signature,
11638                                                  is_debug_types);
11639             }
11640           return (struct dwo_unit *) *slot;
11641         }
11642       if (signature_in_table == 0)
11643         return NULL;
11644       hash = (hash + hash2) & mask;
11645     }
11646
11647   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11648            " [in module %s]"),
11649          dwp_file->name);
11650 }
11651
11652 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11653    Open the file specified by FILE_NAME and hand it off to BFD for
11654    preliminary analysis.  Return a newly initialized bfd *, which
11655    includes a canonicalized copy of FILE_NAME.
11656    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11657    SEARCH_CWD is true if the current directory is to be searched.
11658    It will be searched before debug-file-directory.
11659    If successful, the file is added to the bfd include table of the
11660    objfile's bfd (see gdb_bfd_record_inclusion).
11661    If unable to find/open the file, return NULL.
11662    NOTE: This function is derived from symfile_bfd_open.  */
11663
11664 static gdb_bfd_ref_ptr
11665 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11666 {
11667   int desc, flags;
11668   char *absolute_name;
11669   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11670      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11671      to debug_file_directory.  */
11672   char *search_path;
11673   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11674
11675   if (search_cwd)
11676     {
11677       if (*debug_file_directory != '\0')
11678         search_path = concat (".", dirname_separator_string,
11679                               debug_file_directory, (char *) NULL);
11680       else
11681         search_path = xstrdup (".");
11682     }
11683   else
11684     search_path = xstrdup (debug_file_directory);
11685
11686   flags = OPF_RETURN_REALPATH;
11687   if (is_dwp)
11688     flags |= OPF_SEARCH_IN_PATH;
11689   desc = openp (search_path, flags, file_name,
11690                 O_RDONLY | O_BINARY, &absolute_name);
11691   xfree (search_path);
11692   if (desc < 0)
11693     return NULL;
11694
11695   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11696   xfree (absolute_name);
11697   if (sym_bfd == NULL)
11698     return NULL;
11699   bfd_set_cacheable (sym_bfd.get (), 1);
11700
11701   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11702     return NULL;
11703
11704   /* Success.  Record the bfd as having been included by the objfile's bfd.
11705      This is important because things like demangled_names_hash lives in the
11706      objfile's per_bfd space and may have references to things like symbol
11707      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11708   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11709
11710   return sym_bfd;
11711 }
11712
11713 /* Try to open DWO file FILE_NAME.
11714    COMP_DIR is the DW_AT_comp_dir attribute.
11715    The result is the bfd handle of the file.
11716    If there is a problem finding or opening the file, return NULL.
11717    Upon success, the canonicalized path of the file is stored in the bfd,
11718    same as symfile_bfd_open.  */
11719
11720 static gdb_bfd_ref_ptr
11721 open_dwo_file (const char *file_name, const char *comp_dir)
11722 {
11723   if (IS_ABSOLUTE_PATH (file_name))
11724     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11725
11726   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11727
11728   if (comp_dir != NULL)
11729     {
11730       char *path_to_try = concat (comp_dir, SLASH_STRING,
11731                                   file_name, (char *) NULL);
11732
11733       /* NOTE: If comp_dir is a relative path, this will also try the
11734          search path, which seems useful.  */
11735       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11736                                                 1 /*search_cwd*/));
11737       xfree (path_to_try);
11738       if (abfd != NULL)
11739         return abfd;
11740     }
11741
11742   /* That didn't work, try debug-file-directory, which, despite its name,
11743      is a list of paths.  */
11744
11745   if (*debug_file_directory == '\0')
11746     return NULL;
11747
11748   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11749 }
11750
11751 /* This function is mapped across the sections and remembers the offset and
11752    size of each of the DWO debugging sections we are interested in.  */
11753
11754 static void
11755 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11756 {
11757   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11758   const struct dwop_section_names *names = &dwop_section_names;
11759
11760   if (section_is_p (sectp->name, &names->abbrev_dwo))
11761     {
11762       dwo_sections->abbrev.s.section = sectp;
11763       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11764     }
11765   else if (section_is_p (sectp->name, &names->info_dwo))
11766     {
11767       dwo_sections->info.s.section = sectp;
11768       dwo_sections->info.size = bfd_get_section_size (sectp);
11769     }
11770   else if (section_is_p (sectp->name, &names->line_dwo))
11771     {
11772       dwo_sections->line.s.section = sectp;
11773       dwo_sections->line.size = bfd_get_section_size (sectp);
11774     }
11775   else if (section_is_p (sectp->name, &names->loc_dwo))
11776     {
11777       dwo_sections->loc.s.section = sectp;
11778       dwo_sections->loc.size = bfd_get_section_size (sectp);
11779     }
11780   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11781     {
11782       dwo_sections->macinfo.s.section = sectp;
11783       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11784     }
11785   else if (section_is_p (sectp->name, &names->macro_dwo))
11786     {
11787       dwo_sections->macro.s.section = sectp;
11788       dwo_sections->macro.size = bfd_get_section_size (sectp);
11789     }
11790   else if (section_is_p (sectp->name, &names->str_dwo))
11791     {
11792       dwo_sections->str.s.section = sectp;
11793       dwo_sections->str.size = bfd_get_section_size (sectp);
11794     }
11795   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11796     {
11797       dwo_sections->str_offsets.s.section = sectp;
11798       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11799     }
11800   else if (section_is_p (sectp->name, &names->types_dwo))
11801     {
11802       struct dwarf2_section_info type_section;
11803
11804       memset (&type_section, 0, sizeof (type_section));
11805       type_section.s.section = sectp;
11806       type_section.size = bfd_get_section_size (sectp);
11807       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11808                      &type_section);
11809     }
11810 }
11811
11812 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11813    by PER_CU.  This is for the non-DWP case.
11814    The result is NULL if DWO_NAME can't be found.  */
11815
11816 static struct dwo_file *
11817 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11818                         const char *dwo_name, const char *comp_dir)
11819 {
11820   struct objfile *objfile = dwarf2_per_objfile->objfile;
11821   struct dwo_file *dwo_file;
11822   struct cleanup *cleanups;
11823
11824   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11825   if (dbfd == NULL)
11826     {
11827       if (dwarf_read_debug)
11828         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11829       return NULL;
11830     }
11831   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11832   dwo_file->dwo_name = dwo_name;
11833   dwo_file->comp_dir = comp_dir;
11834   dwo_file->dbfd = dbfd.release ();
11835
11836   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11837
11838   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11839                          &dwo_file->sections);
11840
11841   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11842
11843   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11844                                  dwo_file->tus);
11845
11846   discard_cleanups (cleanups);
11847
11848   if (dwarf_read_debug)
11849     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11850
11851   return dwo_file;
11852 }
11853
11854 /* This function is mapped across the sections and remembers the offset and
11855    size of each of the DWP debugging sections common to version 1 and 2 that
11856    we are interested in.  */
11857
11858 static void
11859 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11860                                    void *dwp_file_ptr)
11861 {
11862   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11863   const struct dwop_section_names *names = &dwop_section_names;
11864   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11865
11866   /* Record the ELF section number for later lookup: this is what the
11867      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11868   gdb_assert (elf_section_nr < dwp_file->num_sections);
11869   dwp_file->elf_sections[elf_section_nr] = sectp;
11870
11871   /* Look for specific sections that we need.  */
11872   if (section_is_p (sectp->name, &names->str_dwo))
11873     {
11874       dwp_file->sections.str.s.section = sectp;
11875       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11876     }
11877   else if (section_is_p (sectp->name, &names->cu_index))
11878     {
11879       dwp_file->sections.cu_index.s.section = sectp;
11880       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11881     }
11882   else if (section_is_p (sectp->name, &names->tu_index))
11883     {
11884       dwp_file->sections.tu_index.s.section = sectp;
11885       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11886     }
11887 }
11888
11889 /* This function is mapped across the sections and remembers the offset and
11890    size of each of the DWP version 2 debugging sections that we are interested
11891    in.  This is split into a separate function because we don't know if we
11892    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11893
11894 static void
11895 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11896 {
11897   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11898   const struct dwop_section_names *names = &dwop_section_names;
11899   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11900
11901   /* Record the ELF section number for later lookup: this is what the
11902      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11903   gdb_assert (elf_section_nr < dwp_file->num_sections);
11904   dwp_file->elf_sections[elf_section_nr] = sectp;
11905
11906   /* Look for specific sections that we need.  */
11907   if (section_is_p (sectp->name, &names->abbrev_dwo))
11908     {
11909       dwp_file->sections.abbrev.s.section = sectp;
11910       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11911     }
11912   else if (section_is_p (sectp->name, &names->info_dwo))
11913     {
11914       dwp_file->sections.info.s.section = sectp;
11915       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11916     }
11917   else if (section_is_p (sectp->name, &names->line_dwo))
11918     {
11919       dwp_file->sections.line.s.section = sectp;
11920       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11921     }
11922   else if (section_is_p (sectp->name, &names->loc_dwo))
11923     {
11924       dwp_file->sections.loc.s.section = sectp;
11925       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11926     }
11927   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11928     {
11929       dwp_file->sections.macinfo.s.section = sectp;
11930       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11931     }
11932   else if (section_is_p (sectp->name, &names->macro_dwo))
11933     {
11934       dwp_file->sections.macro.s.section = sectp;
11935       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11936     }
11937   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11938     {
11939       dwp_file->sections.str_offsets.s.section = sectp;
11940       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11941     }
11942   else if (section_is_p (sectp->name, &names->types_dwo))
11943     {
11944       dwp_file->sections.types.s.section = sectp;
11945       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11946     }
11947 }
11948
11949 /* Hash function for dwp_file loaded CUs/TUs.  */
11950
11951 static hashval_t
11952 hash_dwp_loaded_cutus (const void *item)
11953 {
11954   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11955
11956   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11957   return dwo_unit->signature;
11958 }
11959
11960 /* Equality function for dwp_file loaded CUs/TUs.  */
11961
11962 static int
11963 eq_dwp_loaded_cutus (const void *a, const void *b)
11964 {
11965   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11966   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11967
11968   return dua->signature == dub->signature;
11969 }
11970
11971 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11972
11973 static htab_t
11974 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11975 {
11976   return htab_create_alloc_ex (3,
11977                                hash_dwp_loaded_cutus,
11978                                eq_dwp_loaded_cutus,
11979                                NULL,
11980                                &objfile->objfile_obstack,
11981                                hashtab_obstack_allocate,
11982                                dummy_obstack_deallocate);
11983 }
11984
11985 /* Try to open DWP file FILE_NAME.
11986    The result is the bfd handle of the file.
11987    If there is a problem finding or opening the file, return NULL.
11988    Upon success, the canonicalized path of the file is stored in the bfd,
11989    same as symfile_bfd_open.  */
11990
11991 static gdb_bfd_ref_ptr
11992 open_dwp_file (const char *file_name)
11993 {
11994   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11995                                             1 /*search_cwd*/));
11996   if (abfd != NULL)
11997     return abfd;
11998
11999   /* Work around upstream bug 15652.
12000      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
12001      [Whether that's a "bug" is debatable, but it is getting in our way.]
12002      We have no real idea where the dwp file is, because gdb's realpath-ing
12003      of the executable's path may have discarded the needed info.
12004      [IWBN if the dwp file name was recorded in the executable, akin to
12005      .gnu_debuglink, but that doesn't exist yet.]
12006      Strip the directory from FILE_NAME and search again.  */
12007   if (*debug_file_directory != '\0')
12008     {
12009       /* Don't implicitly search the current directory here.
12010          If the user wants to search "." to handle this case,
12011          it must be added to debug-file-directory.  */
12012       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
12013                                  0 /*search_cwd*/);
12014     }
12015
12016   return NULL;
12017 }
12018
12019 /* Initialize the use of the DWP file for the current objfile.
12020    By convention the name of the DWP file is ${objfile}.dwp.
12021    The result is NULL if it can't be found.  */
12022
12023 static struct dwp_file *
12024 open_and_init_dwp_file (void)
12025 {
12026   struct objfile *objfile = dwarf2_per_objfile->objfile;
12027   struct dwp_file *dwp_file;
12028
12029   /* Try to find first .dwp for the binary file before any symbolic links
12030      resolving.  */
12031
12032   /* If the objfile is a debug file, find the name of the real binary
12033      file and get the name of dwp file from there.  */
12034   std::string dwp_name;
12035   if (objfile->separate_debug_objfile_backlink != NULL)
12036     {
12037       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
12038       const char *backlink_basename = lbasename (backlink->original_name);
12039
12040       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
12041     }
12042   else
12043     dwp_name = objfile->original_name;
12044
12045   dwp_name += ".dwp";
12046
12047   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
12048   if (dbfd == NULL
12049       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
12050     {
12051       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
12052       dwp_name = objfile_name (objfile);
12053       dwp_name += ".dwp";
12054       dbfd = open_dwp_file (dwp_name.c_str ());
12055     }
12056
12057   if (dbfd == NULL)
12058     {
12059       if (dwarf_read_debug)
12060         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
12061       return NULL;
12062     }
12063   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
12064   dwp_file->name = bfd_get_filename (dbfd.get ());
12065   dwp_file->dbfd = dbfd.release ();
12066
12067   /* +1: section 0 is unused */
12068   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
12069   dwp_file->elf_sections =
12070     OBSTACK_CALLOC (&objfile->objfile_obstack,
12071                     dwp_file->num_sections, asection *);
12072
12073   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
12074                          dwp_file);
12075
12076   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
12077
12078   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
12079
12080   /* The DWP file version is stored in the hash table.  Oh well.  */
12081   if (dwp_file->cus && dwp_file->tus
12082       && dwp_file->cus->version != dwp_file->tus->version)
12083     {
12084       /* Technically speaking, we should try to limp along, but this is
12085          pretty bizarre.  We use pulongest here because that's the established
12086          portability solution (e.g, we cannot use %u for uint32_t).  */
12087       error (_("Dwarf Error: DWP file CU version %s doesn't match"
12088                " TU version %s [in DWP file %s]"),
12089              pulongest (dwp_file->cus->version),
12090              pulongest (dwp_file->tus->version), dwp_name.c_str ());
12091     }
12092
12093   if (dwp_file->cus)
12094     dwp_file->version = dwp_file->cus->version;
12095   else if (dwp_file->tus)
12096     dwp_file->version = dwp_file->tus->version;
12097   else
12098     dwp_file->version = 2;
12099
12100   if (dwp_file->version == 2)
12101     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
12102                            dwp_file);
12103
12104   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
12105   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
12106
12107   if (dwarf_read_debug)
12108     {
12109       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
12110       fprintf_unfiltered (gdb_stdlog,
12111                           "    %s CUs, %s TUs\n",
12112                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
12113                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
12114     }
12115
12116   return dwp_file;
12117 }
12118
12119 /* Wrapper around open_and_init_dwp_file, only open it once.  */
12120
12121 static struct dwp_file *
12122 get_dwp_file (void)
12123 {
12124   if (! dwarf2_per_objfile->dwp_checked)
12125     {
12126       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
12127       dwarf2_per_objfile->dwp_checked = 1;
12128     }
12129   return dwarf2_per_objfile->dwp_file;
12130 }
12131
12132 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
12133    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
12134    or in the DWP file for the objfile, referenced by THIS_UNIT.
12135    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
12136    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
12137
12138    This is called, for example, when wanting to read a variable with a
12139    complex location.  Therefore we don't want to do file i/o for every call.
12140    Therefore we don't want to look for a DWO file on every call.
12141    Therefore we first see if we've already seen SIGNATURE in a DWP file,
12142    then we check if we've already seen DWO_NAME, and only THEN do we check
12143    for a DWO file.
12144
12145    The result is a pointer to the dwo_unit object or NULL if we didn't find it
12146    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
12147
12148 static struct dwo_unit *
12149 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
12150                  const char *dwo_name, const char *comp_dir,
12151                  ULONGEST signature, int is_debug_types)
12152 {
12153   struct objfile *objfile = dwarf2_per_objfile->objfile;
12154   const char *kind = is_debug_types ? "TU" : "CU";
12155   void **dwo_file_slot;
12156   struct dwo_file *dwo_file;
12157   struct dwp_file *dwp_file;
12158
12159   /* First see if there's a DWP file.
12160      If we have a DWP file but didn't find the DWO inside it, don't
12161      look for the original DWO file.  It makes gdb behave differently
12162      depending on whether one is debugging in the build tree.  */
12163
12164   dwp_file = get_dwp_file ();
12165   if (dwp_file != NULL)
12166     {
12167       const struct dwp_hash_table *dwp_htab =
12168         is_debug_types ? dwp_file->tus : dwp_file->cus;
12169
12170       if (dwp_htab != NULL)
12171         {
12172           struct dwo_unit *dwo_cutu =
12173             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
12174                                     signature, is_debug_types);
12175
12176           if (dwo_cutu != NULL)
12177             {
12178               if (dwarf_read_debug)
12179                 {
12180                   fprintf_unfiltered (gdb_stdlog,
12181                                       "Virtual DWO %s %s found: @%s\n",
12182                                       kind, hex_string (signature),
12183                                       host_address_to_string (dwo_cutu));
12184                 }
12185               return dwo_cutu;
12186             }
12187         }
12188     }
12189   else
12190     {
12191       /* No DWP file, look for the DWO file.  */
12192
12193       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
12194       if (*dwo_file_slot == NULL)
12195         {
12196           /* Read in the file and build a table of the CUs/TUs it contains.  */
12197           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
12198         }
12199       /* NOTE: This will be NULL if unable to open the file.  */
12200       dwo_file = (struct dwo_file *) *dwo_file_slot;
12201
12202       if (dwo_file != NULL)
12203         {
12204           struct dwo_unit *dwo_cutu = NULL;
12205
12206           if (is_debug_types && dwo_file->tus)
12207             {
12208               struct dwo_unit find_dwo_cutu;
12209
12210               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12211               find_dwo_cutu.signature = signature;
12212               dwo_cutu
12213                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
12214             }
12215           else if (!is_debug_types && dwo_file->cus)
12216             {
12217               struct dwo_unit find_dwo_cutu;
12218
12219               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
12220               find_dwo_cutu.signature = signature;
12221               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
12222                                                        &find_dwo_cutu);
12223             }
12224
12225           if (dwo_cutu != NULL)
12226             {
12227               if (dwarf_read_debug)
12228                 {
12229                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
12230                                       kind, dwo_name, hex_string (signature),
12231                                       host_address_to_string (dwo_cutu));
12232                 }
12233               return dwo_cutu;
12234             }
12235         }
12236     }
12237
12238   /* We didn't find it.  This could mean a dwo_id mismatch, or
12239      someone deleted the DWO/DWP file, or the search path isn't set up
12240      correctly to find the file.  */
12241
12242   if (dwarf_read_debug)
12243     {
12244       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
12245                           kind, dwo_name, hex_string (signature));
12246     }
12247
12248   /* This is a warning and not a complaint because it can be caused by
12249      pilot error (e.g., user accidentally deleting the DWO).  */
12250   {
12251     /* Print the name of the DWP file if we looked there, helps the user
12252        better diagnose the problem.  */
12253     std::string dwp_text;
12254
12255     if (dwp_file != NULL)
12256       dwp_text = string_printf (" [in DWP file %s]",
12257                                 lbasename (dwp_file->name));
12258
12259     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
12260                " [in module %s]"),
12261              kind, dwo_name, hex_string (signature),
12262              dwp_text.c_str (),
12263              this_unit->is_debug_types ? "TU" : "CU",
12264              to_underlying (this_unit->sect_off), objfile_name (objfile));
12265   }
12266   return NULL;
12267 }
12268
12269 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
12270    See lookup_dwo_cutu_unit for details.  */
12271
12272 static struct dwo_unit *
12273 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
12274                       const char *dwo_name, const char *comp_dir,
12275                       ULONGEST signature)
12276 {
12277   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
12278 }
12279
12280 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
12281    See lookup_dwo_cutu_unit for details.  */
12282
12283 static struct dwo_unit *
12284 lookup_dwo_type_unit (struct signatured_type *this_tu,
12285                       const char *dwo_name, const char *comp_dir)
12286 {
12287   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
12288 }
12289
12290 /* Traversal function for queue_and_load_all_dwo_tus.  */
12291
12292 static int
12293 queue_and_load_dwo_tu (void **slot, void *info)
12294 {
12295   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
12296   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
12297   ULONGEST signature = dwo_unit->signature;
12298   struct signatured_type *sig_type =
12299     lookup_dwo_signatured_type (per_cu->cu, signature);
12300
12301   if (sig_type != NULL)
12302     {
12303       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
12304
12305       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
12306          a real dependency of PER_CU on SIG_TYPE.  That is detected later
12307          while processing PER_CU.  */
12308       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
12309         load_full_type_unit (sig_cu);
12310       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
12311     }
12312
12313   return 1;
12314 }
12315
12316 /* Queue all TUs contained in the DWO of PER_CU to be read in.
12317    The DWO may have the only definition of the type, though it may not be
12318    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
12319    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
12320
12321 static void
12322 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
12323 {
12324   struct dwo_unit *dwo_unit;
12325   struct dwo_file *dwo_file;
12326
12327   gdb_assert (!per_cu->is_debug_types);
12328   gdb_assert (get_dwp_file () == NULL);
12329   gdb_assert (per_cu->cu != NULL);
12330
12331   dwo_unit = per_cu->cu->dwo_unit;
12332   gdb_assert (dwo_unit != NULL);
12333
12334   dwo_file = dwo_unit->dwo_file;
12335   if (dwo_file->tus != NULL)
12336     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
12337 }
12338
12339 /* Free all resources associated with DWO_FILE.
12340    Close the DWO file and munmap the sections.
12341    All memory should be on the objfile obstack.  */
12342
12343 static void
12344 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
12345 {
12346
12347   /* Note: dbfd is NULL for virtual DWO files.  */
12348   gdb_bfd_unref (dwo_file->dbfd);
12349
12350   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
12351 }
12352
12353 /* Wrapper for free_dwo_file for use in cleanups.  */
12354
12355 static void
12356 free_dwo_file_cleanup (void *arg)
12357 {
12358   struct dwo_file *dwo_file = (struct dwo_file *) arg;
12359   struct objfile *objfile = dwarf2_per_objfile->objfile;
12360
12361   free_dwo_file (dwo_file, objfile);
12362 }
12363
12364 /* Traversal function for free_dwo_files.  */
12365
12366 static int
12367 free_dwo_file_from_slot (void **slot, void *info)
12368 {
12369   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
12370   struct objfile *objfile = (struct objfile *) info;
12371
12372   free_dwo_file (dwo_file, objfile);
12373
12374   return 1;
12375 }
12376
12377 /* Free all resources associated with DWO_FILES.  */
12378
12379 static void
12380 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
12381 {
12382   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
12383 }
12384 \f
12385 /* Read in various DIEs.  */
12386
12387 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
12388    Inherit only the children of the DW_AT_abstract_origin DIE not being
12389    already referenced by DW_AT_abstract_origin from the children of the
12390    current DIE.  */
12391
12392 static void
12393 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
12394 {
12395   struct die_info *child_die;
12396   sect_offset *offsetp;
12397   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
12398   struct die_info *origin_die;
12399   /* Iterator of the ORIGIN_DIE children.  */
12400   struct die_info *origin_child_die;
12401   struct attribute *attr;
12402   struct dwarf2_cu *origin_cu;
12403   struct pending **origin_previous_list_in_scope;
12404
12405   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12406   if (!attr)
12407     return;
12408
12409   /* Note that following die references may follow to a die in a
12410      different cu.  */
12411
12412   origin_cu = cu;
12413   origin_die = follow_die_ref (die, attr, &origin_cu);
12414
12415   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
12416      symbols in.  */
12417   origin_previous_list_in_scope = origin_cu->list_in_scope;
12418   origin_cu->list_in_scope = cu->list_in_scope;
12419
12420   if (die->tag != origin_die->tag
12421       && !(die->tag == DW_TAG_inlined_subroutine
12422            && origin_die->tag == DW_TAG_subprogram))
12423     complaint (&symfile_complaints,
12424                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
12425                to_underlying (die->sect_off),
12426                to_underlying (origin_die->sect_off));
12427
12428   std::vector<sect_offset> offsets;
12429
12430   for (child_die = die->child;
12431        child_die && child_die->tag;
12432        child_die = sibling_die (child_die))
12433     {
12434       struct die_info *child_origin_die;
12435       struct dwarf2_cu *child_origin_cu;
12436
12437       /* We are trying to process concrete instance entries:
12438          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
12439          it's not relevant to our analysis here. i.e. detecting DIEs that are
12440          present in the abstract instance but not referenced in the concrete
12441          one.  */
12442       if (child_die->tag == DW_TAG_call_site
12443           || child_die->tag == DW_TAG_GNU_call_site)
12444         continue;
12445
12446       /* For each CHILD_DIE, find the corresponding child of
12447          ORIGIN_DIE.  If there is more than one layer of
12448          DW_AT_abstract_origin, follow them all; there shouldn't be,
12449          but GCC versions at least through 4.4 generate this (GCC PR
12450          40573).  */
12451       child_origin_die = child_die;
12452       child_origin_cu = cu;
12453       while (1)
12454         {
12455           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
12456                               child_origin_cu);
12457           if (attr == NULL)
12458             break;
12459           child_origin_die = follow_die_ref (child_origin_die, attr,
12460                                              &child_origin_cu);
12461         }
12462
12463       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
12464          counterpart may exist.  */
12465       if (child_origin_die != child_die)
12466         {
12467           if (child_die->tag != child_origin_die->tag
12468               && !(child_die->tag == DW_TAG_inlined_subroutine
12469                    && child_origin_die->tag == DW_TAG_subprogram))
12470             complaint (&symfile_complaints,
12471                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12472                          "different tags"),
12473                        to_underlying (child_die->sect_off),
12474                        to_underlying (child_origin_die->sect_off));
12475           if (child_origin_die->parent != origin_die)
12476             complaint (&symfile_complaints,
12477                        _("Child DIE 0x%x and its abstract origin 0x%x have "
12478                          "different parents"),
12479                        to_underlying (child_die->sect_off),
12480                        to_underlying (child_origin_die->sect_off));
12481           else
12482             offsets.push_back (child_origin_die->sect_off);
12483         }
12484     }
12485   std::sort (offsets.begin (), offsets.end ());
12486   sect_offset *offsets_end = offsets.data () + offsets.size ();
12487   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
12488     if (offsetp[-1] == *offsetp)
12489       complaint (&symfile_complaints,
12490                  _("Multiple children of DIE 0x%x refer "
12491                    "to DIE 0x%x as their abstract origin"),
12492                  to_underlying (die->sect_off), to_underlying (*offsetp));
12493
12494   offsetp = offsets.data ();
12495   origin_child_die = origin_die->child;
12496   while (origin_child_die && origin_child_die->tag)
12497     {
12498       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
12499       while (offsetp < offsets_end
12500              && *offsetp < origin_child_die->sect_off)
12501         offsetp++;
12502       if (offsetp >= offsets_end
12503           || *offsetp > origin_child_die->sect_off)
12504         {
12505           /* Found that ORIGIN_CHILD_DIE is really not referenced.
12506              Check whether we're already processing ORIGIN_CHILD_DIE.
12507              This can happen with mutually referenced abstract_origins.
12508              PR 16581.  */
12509           if (!origin_child_die->in_process)
12510             process_die (origin_child_die, origin_cu);
12511         }
12512       origin_child_die = sibling_die (origin_child_die);
12513     }
12514   origin_cu->list_in_scope = origin_previous_list_in_scope;
12515 }
12516
12517 static void
12518 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
12519 {
12520   struct objfile *objfile = cu->objfile;
12521   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12522   struct context_stack *newobj;
12523   CORE_ADDR lowpc;
12524   CORE_ADDR highpc;
12525   struct die_info *child_die;
12526   struct attribute *attr, *call_line, *call_file;
12527   const char *name;
12528   CORE_ADDR baseaddr;
12529   struct block *block;
12530   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
12531   std::vector<struct symbol *> template_args;
12532   struct template_symbol *templ_func = NULL;
12533
12534   if (inlined_func)
12535     {
12536       /* If we do not have call site information, we can't show the
12537          caller of this inlined function.  That's too confusing, so
12538          only use the scope for local variables.  */
12539       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
12540       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
12541       if (call_line == NULL || call_file == NULL)
12542         {
12543           read_lexical_block_scope (die, cu);
12544           return;
12545         }
12546     }
12547
12548   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12549
12550   name = dwarf2_name (die, cu);
12551
12552   /* Ignore functions with missing or empty names.  These are actually
12553      illegal according to the DWARF standard.  */
12554   if (name == NULL)
12555     {
12556       complaint (&symfile_complaints,
12557                  _("missing name for subprogram DIE at %d"),
12558                  to_underlying (die->sect_off));
12559       return;
12560     }
12561
12562   /* Ignore functions with missing or invalid low and high pc attributes.  */
12563   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
12564       <= PC_BOUNDS_INVALID)
12565     {
12566       attr = dwarf2_attr (die, DW_AT_external, cu);
12567       if (!attr || !DW_UNSND (attr))
12568         complaint (&symfile_complaints,
12569                    _("cannot get low and high bounds "
12570                      "for subprogram DIE at %d"),
12571                    to_underlying (die->sect_off));
12572       return;
12573     }
12574
12575   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12576   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12577
12578   /* If we have any template arguments, then we must allocate a
12579      different sort of symbol.  */
12580   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
12581     {
12582       if (child_die->tag == DW_TAG_template_type_param
12583           || child_die->tag == DW_TAG_template_value_param)
12584         {
12585           templ_func = allocate_template_symbol (objfile);
12586           templ_func->subclass = SYMBOL_TEMPLATE;
12587           break;
12588         }
12589     }
12590
12591   newobj = push_context (0, lowpc);
12592   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
12593                                (struct symbol *) templ_func);
12594
12595   /* If there is a location expression for DW_AT_frame_base, record
12596      it.  */
12597   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
12598   if (attr)
12599     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
12600
12601   /* If there is a location for the static link, record it.  */
12602   newobj->static_link = NULL;
12603   attr = dwarf2_attr (die, DW_AT_static_link, cu);
12604   if (attr)
12605     {
12606       newobj->static_link
12607         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
12608       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12609     }
12610
12611   cu->list_in_scope = &local_symbols;
12612
12613   if (die->child != NULL)
12614     {
12615       child_die = die->child;
12616       while (child_die && child_die->tag)
12617         {
12618           if (child_die->tag == DW_TAG_template_type_param
12619               || child_die->tag == DW_TAG_template_value_param)
12620             {
12621               struct symbol *arg = new_symbol (child_die, NULL, cu);
12622
12623               if (arg != NULL)
12624                 template_args.push_back (arg);
12625             }
12626           else
12627             process_die (child_die, cu);
12628           child_die = sibling_die (child_die);
12629         }
12630     }
12631
12632   inherit_abstract_dies (die, cu);
12633
12634   /* If we have a DW_AT_specification, we might need to import using
12635      directives from the context of the specification DIE.  See the
12636      comment in determine_prefix.  */
12637   if (cu->language == language_cplus
12638       && dwarf2_attr (die, DW_AT_specification, cu))
12639     {
12640       struct dwarf2_cu *spec_cu = cu;
12641       struct die_info *spec_die = die_specification (die, &spec_cu);
12642
12643       while (spec_die)
12644         {
12645           child_die = spec_die->child;
12646           while (child_die && child_die->tag)
12647             {
12648               if (child_die->tag == DW_TAG_imported_module)
12649                 process_die (child_die, spec_cu);
12650               child_die = sibling_die (child_die);
12651             }
12652
12653           /* In some cases, GCC generates specification DIEs that
12654              themselves contain DW_AT_specification attributes.  */
12655           spec_die = die_specification (spec_die, &spec_cu);
12656         }
12657     }
12658
12659   newobj = pop_context ();
12660   /* Make a block for the local symbols within.  */
12661   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12662                         newobj->static_link, lowpc, highpc);
12663
12664   /* For C++, set the block's scope.  */
12665   if ((cu->language == language_cplus
12666        || cu->language == language_fortran
12667        || cu->language == language_d
12668        || cu->language == language_rust)
12669       && cu->processing_has_namespace_info)
12670     block_set_scope (block, determine_prefix (die, cu),
12671                      &objfile->objfile_obstack);
12672
12673   /* If we have address ranges, record them.  */
12674   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12675
12676   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12677
12678   /* Attach template arguments to function.  */
12679   if (!template_args.empty ())
12680     {
12681       gdb_assert (templ_func != NULL);
12682
12683       templ_func->n_template_arguments = template_args.size ();
12684       templ_func->template_arguments
12685         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12686                      templ_func->n_template_arguments);
12687       memcpy (templ_func->template_arguments,
12688               template_args.data (),
12689               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12690     }
12691
12692   /* In C++, we can have functions nested inside functions (e.g., when
12693      a function declares a class that has methods).  This means that
12694      when we finish processing a function scope, we may need to go
12695      back to building a containing block's symbol lists.  */
12696   local_symbols = newobj->locals;
12697   local_using_directives = newobj->local_using_directives;
12698
12699   /* If we've finished processing a top-level function, subsequent
12700      symbols go in the file symbol list.  */
12701   if (outermost_context_p ())
12702     cu->list_in_scope = &file_symbols;
12703 }
12704
12705 /* Process all the DIES contained within a lexical block scope.  Start
12706    a new scope, process the dies, and then close the scope.  */
12707
12708 static void
12709 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12710 {
12711   struct objfile *objfile = cu->objfile;
12712   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12713   struct context_stack *newobj;
12714   CORE_ADDR lowpc, highpc;
12715   struct die_info *child_die;
12716   CORE_ADDR baseaddr;
12717
12718   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12719
12720   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12721   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12722      as multiple lexical blocks?  Handling children in a sane way would
12723      be nasty.  Might be easier to properly extend generic blocks to
12724      describe ranges.  */
12725   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12726     {
12727     case PC_BOUNDS_NOT_PRESENT:
12728       /* DW_TAG_lexical_block has no attributes, process its children as if
12729          there was no wrapping by that DW_TAG_lexical_block.
12730          GCC does no longer produces such DWARF since GCC r224161.  */
12731       for (child_die = die->child;
12732            child_die != NULL && child_die->tag;
12733            child_die = sibling_die (child_die))
12734         process_die (child_die, cu);
12735       return;
12736     case PC_BOUNDS_INVALID:
12737       return;
12738     }
12739   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12740   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12741
12742   push_context (0, lowpc);
12743   if (die->child != NULL)
12744     {
12745       child_die = die->child;
12746       while (child_die && child_die->tag)
12747         {
12748           process_die (child_die, cu);
12749           child_die = sibling_die (child_die);
12750         }
12751     }
12752   inherit_abstract_dies (die, cu);
12753   newobj = pop_context ();
12754
12755   if (local_symbols != NULL || local_using_directives != NULL)
12756     {
12757       struct block *block
12758         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12759                         newobj->start_addr, highpc);
12760
12761       /* Note that recording ranges after traversing children, as we
12762          do here, means that recording a parent's ranges entails
12763          walking across all its children's ranges as they appear in
12764          the address map, which is quadratic behavior.
12765
12766          It would be nicer to record the parent's ranges before
12767          traversing its children, simply overriding whatever you find
12768          there.  But since we don't even decide whether to create a
12769          block until after we've traversed its children, that's hard
12770          to do.  */
12771       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12772     }
12773   local_symbols = newobj->locals;
12774   local_using_directives = newobj->local_using_directives;
12775 }
12776
12777 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12778
12779 static void
12780 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12781 {
12782   struct objfile *objfile = cu->objfile;
12783   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12784   CORE_ADDR pc, baseaddr;
12785   struct attribute *attr;
12786   struct call_site *call_site, call_site_local;
12787   void **slot;
12788   int nparams;
12789   struct die_info *child_die;
12790
12791   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12792
12793   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12794   if (attr == NULL)
12795     {
12796       /* This was a pre-DWARF-5 GNU extension alias
12797          for DW_AT_call_return_pc.  */
12798       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12799     }
12800   if (!attr)
12801     {
12802       complaint (&symfile_complaints,
12803                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12804                    "DIE 0x%x [in module %s]"),
12805                  to_underlying (die->sect_off), objfile_name (objfile));
12806       return;
12807     }
12808   pc = attr_value_as_address (attr) + baseaddr;
12809   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12810
12811   if (cu->call_site_htab == NULL)
12812     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12813                                                NULL, &objfile->objfile_obstack,
12814                                                hashtab_obstack_allocate, NULL);
12815   call_site_local.pc = pc;
12816   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12817   if (*slot != NULL)
12818     {
12819       complaint (&symfile_complaints,
12820                  _("Duplicate PC %s for DW_TAG_call_site "
12821                    "DIE 0x%x [in module %s]"),
12822                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12823                  objfile_name (objfile));
12824       return;
12825     }
12826
12827   /* Count parameters at the caller.  */
12828
12829   nparams = 0;
12830   for (child_die = die->child; child_die && child_die->tag;
12831        child_die = sibling_die (child_die))
12832     {
12833       if (child_die->tag != DW_TAG_call_site_parameter
12834           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12835         {
12836           complaint (&symfile_complaints,
12837                      _("Tag %d is not DW_TAG_call_site_parameter in "
12838                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12839                      child_die->tag, to_underlying (child_die->sect_off),
12840                      objfile_name (objfile));
12841           continue;
12842         }
12843
12844       nparams++;
12845     }
12846
12847   call_site
12848     = ((struct call_site *)
12849        obstack_alloc (&objfile->objfile_obstack,
12850                       sizeof (*call_site)
12851                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12852   *slot = call_site;
12853   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12854   call_site->pc = pc;
12855
12856   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12857       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12858     {
12859       struct die_info *func_die;
12860
12861       /* Skip also over DW_TAG_inlined_subroutine.  */
12862       for (func_die = die->parent;
12863            func_die && func_die->tag != DW_TAG_subprogram
12864            && func_die->tag != DW_TAG_subroutine_type;
12865            func_die = func_die->parent);
12866
12867       /* DW_AT_call_all_calls is a superset
12868          of DW_AT_call_all_tail_calls.  */
12869       if (func_die
12870           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12871           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12872           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12873           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12874         {
12875           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12876              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12877              both the initial caller containing the real return address PC and
12878              the final callee containing the current PC of a chain of tail
12879              calls do not need to have the tail call list complete.  But any
12880              function candidate for a virtual tail call frame searched via
12881              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12882              determined unambiguously.  */
12883         }
12884       else
12885         {
12886           struct type *func_type = NULL;
12887
12888           if (func_die)
12889             func_type = get_die_type (func_die, cu);
12890           if (func_type != NULL)
12891             {
12892               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12893
12894               /* Enlist this call site to the function.  */
12895               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12896               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12897             }
12898           else
12899             complaint (&symfile_complaints,
12900                        _("Cannot find function owning DW_TAG_call_site "
12901                          "DIE 0x%x [in module %s]"),
12902                        to_underlying (die->sect_off), objfile_name (objfile));
12903         }
12904     }
12905
12906   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12907   if (attr == NULL)
12908     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12909   if (attr == NULL)
12910     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12911   if (attr == NULL)
12912     {
12913       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12914       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12915     }
12916   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12917   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12918     /* Keep NULL DWARF_BLOCK.  */;
12919   else if (attr_form_is_block (attr))
12920     {
12921       struct dwarf2_locexpr_baton *dlbaton;
12922
12923       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12924       dlbaton->data = DW_BLOCK (attr)->data;
12925       dlbaton->size = DW_BLOCK (attr)->size;
12926       dlbaton->per_cu = cu->per_cu;
12927
12928       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12929     }
12930   else if (attr_form_is_ref (attr))
12931     {
12932       struct dwarf2_cu *target_cu = cu;
12933       struct die_info *target_die;
12934
12935       target_die = follow_die_ref (die, attr, &target_cu);
12936       gdb_assert (target_cu->objfile == objfile);
12937       if (die_is_declaration (target_die, target_cu))
12938         {
12939           const char *target_physname;
12940
12941           /* Prefer the mangled name; otherwise compute the demangled one.  */
12942           target_physname = dw2_linkage_name (target_die, target_cu);
12943           if (target_physname == NULL)
12944             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12945           if (target_physname == NULL)
12946             complaint (&symfile_complaints,
12947                        _("DW_AT_call_target target DIE has invalid "
12948                          "physname, for referencing DIE 0x%x [in module %s]"),
12949                        to_underlying (die->sect_off), objfile_name (objfile));
12950           else
12951             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12952         }
12953       else
12954         {
12955           CORE_ADDR lowpc;
12956
12957           /* DW_AT_entry_pc should be preferred.  */
12958           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12959               <= PC_BOUNDS_INVALID)
12960             complaint (&symfile_complaints,
12961                        _("DW_AT_call_target target DIE has invalid "
12962                          "low pc, for referencing DIE 0x%x [in module %s]"),
12963                        to_underlying (die->sect_off), objfile_name (objfile));
12964           else
12965             {
12966               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12967               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12968             }
12969         }
12970     }
12971   else
12972     complaint (&symfile_complaints,
12973                _("DW_TAG_call_site DW_AT_call_target is neither "
12974                  "block nor reference, for DIE 0x%x [in module %s]"),
12975                to_underlying (die->sect_off), objfile_name (objfile));
12976
12977   call_site->per_cu = cu->per_cu;
12978
12979   for (child_die = die->child;
12980        child_die && child_die->tag;
12981        child_die = sibling_die (child_die))
12982     {
12983       struct call_site_parameter *parameter;
12984       struct attribute *loc, *origin;
12985
12986       if (child_die->tag != DW_TAG_call_site_parameter
12987           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12988         {
12989           /* Already printed the complaint above.  */
12990           continue;
12991         }
12992
12993       gdb_assert (call_site->parameter_count < nparams);
12994       parameter = &call_site->parameter[call_site->parameter_count];
12995
12996       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12997          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12998          register is contained in DW_AT_call_value.  */
12999
13000       loc = dwarf2_attr (child_die, DW_AT_location, cu);
13001       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
13002       if (origin == NULL)
13003         {
13004           /* This was a pre-DWARF-5 GNU extension alias
13005              for DW_AT_call_parameter.  */
13006           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
13007         }
13008       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
13009         {
13010           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
13011
13012           sect_offset sect_off
13013             = (sect_offset) dwarf2_get_ref_die_offset (origin);
13014           if (!offset_in_cu_p (&cu->header, sect_off))
13015             {
13016               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
13017                  binding can be done only inside one CU.  Such referenced DIE
13018                  therefore cannot be even moved to DW_TAG_partial_unit.  */
13019               complaint (&symfile_complaints,
13020                          _("DW_AT_call_parameter offset is not in CU for "
13021                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13022                          to_underlying (child_die->sect_off),
13023                          objfile_name (objfile));
13024               continue;
13025             }
13026           parameter->u.param_cu_off
13027             = (cu_offset) (sect_off - cu->header.sect_off);
13028         }
13029       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
13030         {
13031           complaint (&symfile_complaints,
13032                      _("No DW_FORM_block* DW_AT_location for "
13033                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13034                      to_underlying (child_die->sect_off), objfile_name (objfile));
13035           continue;
13036         }
13037       else
13038         {
13039           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
13040             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
13041           if (parameter->u.dwarf_reg != -1)
13042             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
13043           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
13044                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
13045                                              &parameter->u.fb_offset))
13046             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
13047           else
13048             {
13049               complaint (&symfile_complaints,
13050                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
13051                            "for DW_FORM_block* DW_AT_location is supported for "
13052                            "DW_TAG_call_site child DIE 0x%x "
13053                            "[in module %s]"),
13054                          to_underlying (child_die->sect_off),
13055                          objfile_name (objfile));
13056               continue;
13057             }
13058         }
13059
13060       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
13061       if (attr == NULL)
13062         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
13063       if (!attr_form_is_block (attr))
13064         {
13065           complaint (&symfile_complaints,
13066                      _("No DW_FORM_block* DW_AT_call_value for "
13067                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13068                      to_underlying (child_die->sect_off),
13069                      objfile_name (objfile));
13070           continue;
13071         }
13072       parameter->value = DW_BLOCK (attr)->data;
13073       parameter->value_size = DW_BLOCK (attr)->size;
13074
13075       /* Parameters are not pre-cleared by memset above.  */
13076       parameter->data_value = NULL;
13077       parameter->data_value_size = 0;
13078       call_site->parameter_count++;
13079
13080       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
13081       if (attr == NULL)
13082         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
13083       if (attr)
13084         {
13085           if (!attr_form_is_block (attr))
13086             complaint (&symfile_complaints,
13087                        _("No DW_FORM_block* DW_AT_call_data_value for "
13088                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
13089                        to_underlying (child_die->sect_off),
13090                        objfile_name (objfile));
13091           else
13092             {
13093               parameter->data_value = DW_BLOCK (attr)->data;
13094               parameter->data_value_size = DW_BLOCK (attr)->size;
13095             }
13096         }
13097     }
13098 }
13099
13100 /* Helper function for read_variable.  If DIE represents a virtual
13101    table, then return the type of the concrete object that is
13102    associated with the virtual table.  Otherwise, return NULL.  */
13103
13104 static struct type *
13105 rust_containing_type (struct die_info *die, struct dwarf2_cu *cu)
13106 {
13107   struct attribute *attr = dwarf2_attr (die, DW_AT_type, cu);
13108   if (attr == NULL)
13109     return NULL;
13110
13111   /* Find the type DIE.  */
13112   struct die_info *type_die = NULL;
13113   struct dwarf2_cu *type_cu = cu;
13114
13115   if (attr_form_is_ref (attr))
13116     type_die = follow_die_ref (die, attr, &type_cu);
13117   if (type_die == NULL)
13118     return NULL;
13119
13120   if (dwarf2_attr (type_die, DW_AT_containing_type, type_cu) == NULL)
13121     return NULL;
13122   return die_containing_type (type_die, type_cu);
13123 }
13124
13125 /* Read a variable (DW_TAG_variable) DIE and create a new symbol.  */
13126
13127 static void
13128 read_variable (struct die_info *die, struct dwarf2_cu *cu)
13129 {
13130   struct rust_vtable_symbol *storage = NULL;
13131
13132   if (cu->language == language_rust)
13133     {
13134       struct type *containing_type = rust_containing_type (die, cu);
13135
13136       if (containing_type != NULL)
13137         {
13138           struct objfile *objfile = cu->objfile;
13139
13140           storage = OBSTACK_ZALLOC (&objfile->objfile_obstack,
13141                                     struct rust_vtable_symbol);
13142           initialize_objfile_symbol (storage);
13143           storage->concrete_type = containing_type;
13144           storage->subclass = SYMBOL_RUST_VTABLE;
13145         }
13146     }
13147
13148   new_symbol_full (die, NULL, cu, storage);
13149 }
13150
13151 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
13152    reading .debug_rnglists.
13153    Callback's type should be:
13154     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13155    Return true if the attributes are present and valid, otherwise,
13156    return false.  */
13157
13158 template <typename Callback>
13159 static bool
13160 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
13161                          Callback &&callback)
13162 {
13163   struct objfile *objfile = cu->objfile;
13164   bfd *obfd = objfile->obfd;
13165   /* Base address selection entry.  */
13166   CORE_ADDR base;
13167   int found_base;
13168   const gdb_byte *buffer;
13169   CORE_ADDR baseaddr;
13170   bool overflow = false;
13171
13172   found_base = cu->base_known;
13173   base = cu->base_address;
13174
13175   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
13176   if (offset >= dwarf2_per_objfile->rnglists.size)
13177     {
13178       complaint (&symfile_complaints,
13179                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13180                  offset);
13181       return false;
13182     }
13183   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
13184
13185   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13186
13187   while (1)
13188     {
13189       /* Initialize it due to a false compiler warning.  */
13190       CORE_ADDR range_beginning = 0, range_end = 0;
13191       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
13192                                  + dwarf2_per_objfile->rnglists.size);
13193       unsigned int bytes_read;
13194
13195       if (buffer == buf_end)
13196         {
13197           overflow = true;
13198           break;
13199         }
13200       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
13201       switch (rlet)
13202         {
13203         case DW_RLE_end_of_list:
13204           break;
13205         case DW_RLE_base_address:
13206           if (buffer + cu->header.addr_size > buf_end)
13207             {
13208               overflow = true;
13209               break;
13210             }
13211           base = read_address (obfd, buffer, cu, &bytes_read);
13212           found_base = 1;
13213           buffer += bytes_read;
13214           break;
13215         case DW_RLE_start_length:
13216           if (buffer + cu->header.addr_size > buf_end)
13217             {
13218               overflow = true;
13219               break;
13220             }
13221           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13222           buffer += bytes_read;
13223           range_end = (range_beginning
13224                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
13225           buffer += bytes_read;
13226           if (buffer > buf_end)
13227             {
13228               overflow = true;
13229               break;
13230             }
13231           break;
13232         case DW_RLE_offset_pair:
13233           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13234           buffer += bytes_read;
13235           if (buffer > buf_end)
13236             {
13237               overflow = true;
13238               break;
13239             }
13240           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
13241           buffer += bytes_read;
13242           if (buffer > buf_end)
13243             {
13244               overflow = true;
13245               break;
13246             }
13247           break;
13248         case DW_RLE_start_end:
13249           if (buffer + 2 * cu->header.addr_size > buf_end)
13250             {
13251               overflow = true;
13252               break;
13253             }
13254           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
13255           buffer += bytes_read;
13256           range_end = read_address (obfd, buffer, cu, &bytes_read);
13257           buffer += bytes_read;
13258           break;
13259         default:
13260           complaint (&symfile_complaints,
13261                      _("Invalid .debug_rnglists data (no base address)"));
13262           return false;
13263         }
13264       if (rlet == DW_RLE_end_of_list || overflow)
13265         break;
13266       if (rlet == DW_RLE_base_address)
13267         continue;
13268
13269       if (!found_base)
13270         {
13271           /* We have no valid base address for the ranges
13272              data.  */
13273           complaint (&symfile_complaints,
13274                      _("Invalid .debug_rnglists data (no base address)"));
13275           return false;
13276         }
13277
13278       if (range_beginning > range_end)
13279         {
13280           /* Inverted range entries are invalid.  */
13281           complaint (&symfile_complaints,
13282                      _("Invalid .debug_rnglists data (inverted range)"));
13283           return false;
13284         }
13285
13286       /* Empty range entries have no effect.  */
13287       if (range_beginning == range_end)
13288         continue;
13289
13290       range_beginning += base;
13291       range_end += base;
13292
13293       /* A not-uncommon case of bad debug info.
13294          Don't pollute the addrmap with bad data.  */
13295       if (range_beginning + baseaddr == 0
13296           && !dwarf2_per_objfile->has_section_at_zero)
13297         {
13298           complaint (&symfile_complaints,
13299                      _(".debug_rnglists entry has start address of zero"
13300                        " [in module %s]"), objfile_name (objfile));
13301           continue;
13302         }
13303
13304       callback (range_beginning, range_end);
13305     }
13306
13307   if (overflow)
13308     {
13309       complaint (&symfile_complaints,
13310                  _("Offset %d is not terminated "
13311                    "for DW_AT_ranges attribute"),
13312                  offset);
13313       return false;
13314     }
13315
13316   return true;
13317 }
13318
13319 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
13320    Callback's type should be:
13321     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
13322    Return 1 if the attributes are present and valid, otherwise, return 0.  */
13323
13324 template <typename Callback>
13325 static int
13326 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
13327                        Callback &&callback)
13328 {
13329   struct objfile *objfile = cu->objfile;
13330   struct comp_unit_head *cu_header = &cu->header;
13331   bfd *obfd = objfile->obfd;
13332   unsigned int addr_size = cu_header->addr_size;
13333   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13334   /* Base address selection entry.  */
13335   CORE_ADDR base;
13336   int found_base;
13337   unsigned int dummy;
13338   const gdb_byte *buffer;
13339   CORE_ADDR baseaddr;
13340
13341   if (cu_header->version >= 5)
13342     return dwarf2_rnglists_process (offset, cu, callback);
13343
13344   found_base = cu->base_known;
13345   base = cu->base_address;
13346
13347   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
13348   if (offset >= dwarf2_per_objfile->ranges.size)
13349     {
13350       complaint (&symfile_complaints,
13351                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
13352                  offset);
13353       return 0;
13354     }
13355   buffer = dwarf2_per_objfile->ranges.buffer + offset;
13356
13357   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
13358
13359   while (1)
13360     {
13361       CORE_ADDR range_beginning, range_end;
13362
13363       range_beginning = read_address (obfd, buffer, cu, &dummy);
13364       buffer += addr_size;
13365       range_end = read_address (obfd, buffer, cu, &dummy);
13366       buffer += addr_size;
13367       offset += 2 * addr_size;
13368
13369       /* An end of list marker is a pair of zero addresses.  */
13370       if (range_beginning == 0 && range_end == 0)
13371         /* Found the end of list entry.  */
13372         break;
13373
13374       /* Each base address selection entry is a pair of 2 values.
13375          The first is the largest possible address, the second is
13376          the base address.  Check for a base address here.  */
13377       if ((range_beginning & mask) == mask)
13378         {
13379           /* If we found the largest possible address, then we already
13380              have the base address in range_end.  */
13381           base = range_end;
13382           found_base = 1;
13383           continue;
13384         }
13385
13386       if (!found_base)
13387         {
13388           /* We have no valid base address for the ranges
13389              data.  */
13390           complaint (&symfile_complaints,
13391                      _("Invalid .debug_ranges data (no base address)"));
13392           return 0;
13393         }
13394
13395       if (range_beginning > range_end)
13396         {
13397           /* Inverted range entries are invalid.  */
13398           complaint (&symfile_complaints,
13399                      _("Invalid .debug_ranges data (inverted range)"));
13400           return 0;
13401         }
13402
13403       /* Empty range entries have no effect.  */
13404       if (range_beginning == range_end)
13405         continue;
13406
13407       range_beginning += base;
13408       range_end += base;
13409
13410       /* A not-uncommon case of bad debug info.
13411          Don't pollute the addrmap with bad data.  */
13412       if (range_beginning + baseaddr == 0
13413           && !dwarf2_per_objfile->has_section_at_zero)
13414         {
13415           complaint (&symfile_complaints,
13416                      _(".debug_ranges entry has start address of zero"
13417                        " [in module %s]"), objfile_name (objfile));
13418           continue;
13419         }
13420
13421       callback (range_beginning, range_end);
13422     }
13423
13424   return 1;
13425 }
13426
13427 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
13428    Return 1 if the attributes are present and valid, otherwise, return 0.
13429    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
13430
13431 static int
13432 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
13433                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
13434                     struct partial_symtab *ranges_pst)
13435 {
13436   struct objfile *objfile = cu->objfile;
13437   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13438   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
13439                                        SECT_OFF_TEXT (objfile));
13440   int low_set = 0;
13441   CORE_ADDR low = 0;
13442   CORE_ADDR high = 0;
13443   int retval;
13444
13445   retval = dwarf2_ranges_process (offset, cu,
13446     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
13447     {
13448       if (ranges_pst != NULL)
13449         {
13450           CORE_ADDR lowpc;
13451           CORE_ADDR highpc;
13452
13453           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13454                                               range_beginning + baseaddr);
13455           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
13456                                                range_end + baseaddr);
13457           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
13458                              ranges_pst);
13459         }
13460
13461       /* FIXME: This is recording everything as a low-high
13462          segment of consecutive addresses.  We should have a
13463          data structure for discontiguous block ranges
13464          instead.  */
13465       if (! low_set)
13466         {
13467           low = range_beginning;
13468           high = range_end;
13469           low_set = 1;
13470         }
13471       else
13472         {
13473           if (range_beginning < low)
13474             low = range_beginning;
13475           if (range_end > high)
13476             high = range_end;
13477         }
13478     });
13479   if (!retval)
13480     return 0;
13481
13482   if (! low_set)
13483     /* If the first entry is an end-of-list marker, the range
13484        describes an empty scope, i.e. no instructions.  */
13485     return 0;
13486
13487   if (low_return)
13488     *low_return = low;
13489   if (high_return)
13490     *high_return = high;
13491   return 1;
13492 }
13493
13494 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
13495    definition for the return value.  *LOWPC and *HIGHPC are set iff
13496    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
13497
13498 static enum pc_bounds_kind
13499 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
13500                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
13501                       struct partial_symtab *pst)
13502 {
13503   struct attribute *attr;
13504   struct attribute *attr_high;
13505   CORE_ADDR low = 0;
13506   CORE_ADDR high = 0;
13507   enum pc_bounds_kind ret;
13508
13509   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13510   if (attr_high)
13511     {
13512       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13513       if (attr)
13514         {
13515           low = attr_value_as_address (attr);
13516           high = attr_value_as_address (attr_high);
13517           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13518             high += low;
13519         }
13520       else
13521         /* Found high w/o low attribute.  */
13522         return PC_BOUNDS_INVALID;
13523
13524       /* Found consecutive range of addresses.  */
13525       ret = PC_BOUNDS_HIGH_LOW;
13526     }
13527   else
13528     {
13529       attr = dwarf2_attr (die, DW_AT_ranges, cu);
13530       if (attr != NULL)
13531         {
13532           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13533              We take advantage of the fact that DW_AT_ranges does not appear
13534              in DW_TAG_compile_unit of DWO files.  */
13535           int need_ranges_base = die->tag != DW_TAG_compile_unit;
13536           unsigned int ranges_offset = (DW_UNSND (attr)
13537                                         + (need_ranges_base
13538                                            ? cu->ranges_base
13539                                            : 0));
13540
13541           /* Value of the DW_AT_ranges attribute is the offset in the
13542              .debug_ranges section.  */
13543           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
13544             return PC_BOUNDS_INVALID;
13545           /* Found discontinuous range of addresses.  */
13546           ret = PC_BOUNDS_RANGES;
13547         }
13548       else
13549         return PC_BOUNDS_NOT_PRESENT;
13550     }
13551
13552   /* read_partial_die has also the strict LOW < HIGH requirement.  */
13553   if (high <= low)
13554     return PC_BOUNDS_INVALID;
13555
13556   /* When using the GNU linker, .gnu.linkonce. sections are used to
13557      eliminate duplicate copies of functions and vtables and such.
13558      The linker will arbitrarily choose one and discard the others.
13559      The AT_*_pc values for such functions refer to local labels in
13560      these sections.  If the section from that file was discarded, the
13561      labels are not in the output, so the relocs get a value of 0.
13562      If this is a discarded function, mark the pc bounds as invalid,
13563      so that GDB will ignore it.  */
13564   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
13565     return PC_BOUNDS_INVALID;
13566
13567   *lowpc = low;
13568   if (highpc)
13569     *highpc = high;
13570   return ret;
13571 }
13572
13573 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
13574    its low and high PC addresses.  Do nothing if these addresses could not
13575    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
13576    and HIGHPC to the high address if greater than HIGHPC.  */
13577
13578 static void
13579 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
13580                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
13581                                  struct dwarf2_cu *cu)
13582 {
13583   CORE_ADDR low, high;
13584   struct die_info *child = die->child;
13585
13586   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
13587     {
13588       *lowpc = std::min (*lowpc, low);
13589       *highpc = std::max (*highpc, high);
13590     }
13591
13592   /* If the language does not allow nested subprograms (either inside
13593      subprograms or lexical blocks), we're done.  */
13594   if (cu->language != language_ada)
13595     return;
13596
13597   /* Check all the children of the given DIE.  If it contains nested
13598      subprograms, then check their pc bounds.  Likewise, we need to
13599      check lexical blocks as well, as they may also contain subprogram
13600      definitions.  */
13601   while (child && child->tag)
13602     {
13603       if (child->tag == DW_TAG_subprogram
13604           || child->tag == DW_TAG_lexical_block)
13605         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
13606       child = sibling_die (child);
13607     }
13608 }
13609
13610 /* Get the low and high pc's represented by the scope DIE, and store
13611    them in *LOWPC and *HIGHPC.  If the correct values can't be
13612    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
13613
13614 static void
13615 get_scope_pc_bounds (struct die_info *die,
13616                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
13617                      struct dwarf2_cu *cu)
13618 {
13619   CORE_ADDR best_low = (CORE_ADDR) -1;
13620   CORE_ADDR best_high = (CORE_ADDR) 0;
13621   CORE_ADDR current_low, current_high;
13622
13623   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
13624       >= PC_BOUNDS_RANGES)
13625     {
13626       best_low = current_low;
13627       best_high = current_high;
13628     }
13629   else
13630     {
13631       struct die_info *child = die->child;
13632
13633       while (child && child->tag)
13634         {
13635           switch (child->tag) {
13636           case DW_TAG_subprogram:
13637             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
13638             break;
13639           case DW_TAG_namespace:
13640           case DW_TAG_module:
13641             /* FIXME: carlton/2004-01-16: Should we do this for
13642                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
13643                that current GCC's always emit the DIEs corresponding
13644                to definitions of methods of classes as children of a
13645                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
13646                the DIEs giving the declarations, which could be
13647                anywhere).  But I don't see any reason why the
13648                standards says that they have to be there.  */
13649             get_scope_pc_bounds (child, &current_low, &current_high, cu);
13650
13651             if (current_low != ((CORE_ADDR) -1))
13652               {
13653                 best_low = std::min (best_low, current_low);
13654                 best_high = std::max (best_high, current_high);
13655               }
13656             break;
13657           default:
13658             /* Ignore.  */
13659             break;
13660           }
13661
13662           child = sibling_die (child);
13663         }
13664     }
13665
13666   *lowpc = best_low;
13667   *highpc = best_high;
13668 }
13669
13670 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13671    in DIE.  */
13672
13673 static void
13674 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13675                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13676 {
13677   struct objfile *objfile = cu->objfile;
13678   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13679   struct attribute *attr;
13680   struct attribute *attr_high;
13681
13682   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13683   if (attr_high)
13684     {
13685       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13686       if (attr)
13687         {
13688           CORE_ADDR low = attr_value_as_address (attr);
13689           CORE_ADDR high = attr_value_as_address (attr_high);
13690
13691           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13692             high += low;
13693
13694           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13695           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13696           record_block_range (block, low, high - 1);
13697         }
13698     }
13699
13700   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13701   if (attr)
13702     {
13703       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13704          We take advantage of the fact that DW_AT_ranges does not appear
13705          in DW_TAG_compile_unit of DWO files.  */
13706       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13707
13708       /* The value of the DW_AT_ranges attribute is the offset of the
13709          address range list in the .debug_ranges section.  */
13710       unsigned long offset = (DW_UNSND (attr)
13711                               + (need_ranges_base ? cu->ranges_base : 0));
13712       const gdb_byte *buffer;
13713
13714       /* For some target architectures, but not others, the
13715          read_address function sign-extends the addresses it returns.
13716          To recognize base address selection entries, we need a
13717          mask.  */
13718       unsigned int addr_size = cu->header.addr_size;
13719       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13720
13721       /* The base address, to which the next pair is relative.  Note
13722          that this 'base' is a DWARF concept: most entries in a range
13723          list are relative, to reduce the number of relocs against the
13724          debugging information.  This is separate from this function's
13725          'baseaddr' argument, which GDB uses to relocate debugging
13726          information from a shared library based on the address at
13727          which the library was loaded.  */
13728       CORE_ADDR base = cu->base_address;
13729       int base_known = cu->base_known;
13730
13731       dwarf2_ranges_process (offset, cu,
13732         [&] (CORE_ADDR start, CORE_ADDR end)
13733         {
13734           start += baseaddr;
13735           end += baseaddr;
13736           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13737           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13738           record_block_range (block, start, end - 1);
13739         });
13740     }
13741 }
13742
13743 /* Check whether the producer field indicates either of GCC < 4.6, or the
13744    Intel C/C++ compiler, and cache the result in CU.  */
13745
13746 static void
13747 check_producer (struct dwarf2_cu *cu)
13748 {
13749   int major, minor;
13750
13751   if (cu->producer == NULL)
13752     {
13753       /* For unknown compilers expect their behavior is DWARF version
13754          compliant.
13755
13756          GCC started to support .debug_types sections by -gdwarf-4 since
13757          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13758          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13759          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13760          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13761     }
13762   else if (producer_is_gcc (cu->producer, &major, &minor))
13763     {
13764       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13765       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13766     }
13767   else if (producer_is_icc (cu->producer, &major, &minor))
13768     cu->producer_is_icc_lt_14 = major < 14;
13769   else
13770     {
13771       /* For other non-GCC compilers, expect their behavior is DWARF version
13772          compliant.  */
13773     }
13774
13775   cu->checked_producer = 1;
13776 }
13777
13778 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13779    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13780    during 4.6.0 experimental.  */
13781
13782 static int
13783 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13784 {
13785   if (!cu->checked_producer)
13786     check_producer (cu);
13787
13788   return cu->producer_is_gxx_lt_4_6;
13789 }
13790
13791 /* Return the default accessibility type if it is not overriden by
13792    DW_AT_accessibility.  */
13793
13794 static enum dwarf_access_attribute
13795 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13796 {
13797   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13798     {
13799       /* The default DWARF 2 accessibility for members is public, the default
13800          accessibility for inheritance is private.  */
13801
13802       if (die->tag != DW_TAG_inheritance)
13803         return DW_ACCESS_public;
13804       else
13805         return DW_ACCESS_private;
13806     }
13807   else
13808     {
13809       /* DWARF 3+ defines the default accessibility a different way.  The same
13810          rules apply now for DW_TAG_inheritance as for the members and it only
13811          depends on the container kind.  */
13812
13813       if (die->parent->tag == DW_TAG_class_type)
13814         return DW_ACCESS_private;
13815       else
13816         return DW_ACCESS_public;
13817     }
13818 }
13819
13820 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13821    offset.  If the attribute was not found return 0, otherwise return
13822    1.  If it was found but could not properly be handled, set *OFFSET
13823    to 0.  */
13824
13825 static int
13826 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13827                              LONGEST *offset)
13828 {
13829   struct attribute *attr;
13830
13831   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13832   if (attr != NULL)
13833     {
13834       *offset = 0;
13835
13836       /* Note that we do not check for a section offset first here.
13837          This is because DW_AT_data_member_location is new in DWARF 4,
13838          so if we see it, we can assume that a constant form is really
13839          a constant and not a section offset.  */
13840       if (attr_form_is_constant (attr))
13841         *offset = dwarf2_get_attr_constant_value (attr, 0);
13842       else if (attr_form_is_section_offset (attr))
13843         dwarf2_complex_location_expr_complaint ();
13844       else if (attr_form_is_block (attr))
13845         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13846       else
13847         dwarf2_complex_location_expr_complaint ();
13848
13849       return 1;
13850     }
13851
13852   return 0;
13853 }
13854
13855 /* Add an aggregate field to the field list.  */
13856
13857 static void
13858 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13859                   struct dwarf2_cu *cu)
13860 {
13861   struct objfile *objfile = cu->objfile;
13862   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13863   struct nextfield *new_field;
13864   struct attribute *attr;
13865   struct field *fp;
13866   const char *fieldname = "";
13867
13868   /* Allocate a new field list entry and link it in.  */
13869   new_field = XNEW (struct nextfield);
13870   make_cleanup (xfree, new_field);
13871   memset (new_field, 0, sizeof (struct nextfield));
13872
13873   if (die->tag == DW_TAG_inheritance)
13874     {
13875       new_field->next = fip->baseclasses;
13876       fip->baseclasses = new_field;
13877     }
13878   else
13879     {
13880       new_field->next = fip->fields;
13881       fip->fields = new_field;
13882     }
13883   fip->nfields++;
13884
13885   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13886   if (attr)
13887     new_field->accessibility = DW_UNSND (attr);
13888   else
13889     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13890   if (new_field->accessibility != DW_ACCESS_public)
13891     fip->non_public_fields = 1;
13892
13893   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13894   if (attr)
13895     new_field->virtuality = DW_UNSND (attr);
13896   else
13897     new_field->virtuality = DW_VIRTUALITY_none;
13898
13899   fp = &new_field->field;
13900
13901   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13902     {
13903       LONGEST offset;
13904
13905       /* Data member other than a C++ static data member.  */
13906
13907       /* Get type of field.  */
13908       fp->type = die_type (die, cu);
13909
13910       SET_FIELD_BITPOS (*fp, 0);
13911
13912       /* Get bit size of field (zero if none).  */
13913       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13914       if (attr)
13915         {
13916           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13917         }
13918       else
13919         {
13920           FIELD_BITSIZE (*fp) = 0;
13921         }
13922
13923       /* Get bit offset of field.  */
13924       if (handle_data_member_location (die, cu, &offset))
13925         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13926       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13927       if (attr)
13928         {
13929           if (gdbarch_bits_big_endian (gdbarch))
13930             {
13931               /* For big endian bits, the DW_AT_bit_offset gives the
13932                  additional bit offset from the MSB of the containing
13933                  anonymous object to the MSB of the field.  We don't
13934                  have to do anything special since we don't need to
13935                  know the size of the anonymous object.  */
13936               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13937             }
13938           else
13939             {
13940               /* For little endian bits, compute the bit offset to the
13941                  MSB of the anonymous object, subtract off the number of
13942                  bits from the MSB of the field to the MSB of the
13943                  object, and then subtract off the number of bits of
13944                  the field itself.  The result is the bit offset of
13945                  the LSB of the field.  */
13946               int anonymous_size;
13947               int bit_offset = DW_UNSND (attr);
13948
13949               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13950               if (attr)
13951                 {
13952                   /* The size of the anonymous object containing
13953                      the bit field is explicit, so use the
13954                      indicated size (in bytes).  */
13955                   anonymous_size = DW_UNSND (attr);
13956                 }
13957               else
13958                 {
13959                   /* The size of the anonymous object containing
13960                      the bit field must be inferred from the type
13961                      attribute of the data member containing the
13962                      bit field.  */
13963                   anonymous_size = TYPE_LENGTH (fp->type);
13964                 }
13965               SET_FIELD_BITPOS (*fp,
13966                                 (FIELD_BITPOS (*fp)
13967                                  + anonymous_size * bits_per_byte
13968                                  - bit_offset - FIELD_BITSIZE (*fp)));
13969             }
13970         }
13971       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13972       if (attr != NULL)
13973         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13974                                 + dwarf2_get_attr_constant_value (attr, 0)));
13975
13976       /* Get name of field.  */
13977       fieldname = dwarf2_name (die, cu);
13978       if (fieldname == NULL)
13979         fieldname = "";
13980
13981       /* The name is already allocated along with this objfile, so we don't
13982          need to duplicate it for the type.  */
13983       fp->name = fieldname;
13984
13985       /* Change accessibility for artificial fields (e.g. virtual table
13986          pointer or virtual base class pointer) to private.  */
13987       if (dwarf2_attr (die, DW_AT_artificial, cu))
13988         {
13989           FIELD_ARTIFICIAL (*fp) = 1;
13990           new_field->accessibility = DW_ACCESS_private;
13991           fip->non_public_fields = 1;
13992         }
13993     }
13994   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13995     {
13996       /* C++ static member.  */
13997
13998       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13999          is a declaration, but all versions of G++ as of this writing
14000          (so through at least 3.2.1) incorrectly generate
14001          DW_TAG_variable tags.  */
14002
14003       const char *physname;
14004
14005       /* Get name of field.  */
14006       fieldname = dwarf2_name (die, cu);
14007       if (fieldname == NULL)
14008         return;
14009
14010       attr = dwarf2_attr (die, DW_AT_const_value, cu);
14011       if (attr
14012           /* Only create a symbol if this is an external value.
14013              new_symbol checks this and puts the value in the global symbol
14014              table, which we want.  If it is not external, new_symbol
14015              will try to put the value in cu->list_in_scope which is wrong.  */
14016           && dwarf2_flag_true_p (die, DW_AT_external, cu))
14017         {
14018           /* A static const member, not much different than an enum as far as
14019              we're concerned, except that we can support more types.  */
14020           new_symbol (die, NULL, cu);
14021         }
14022
14023       /* Get physical name.  */
14024       physname = dwarf2_physname (fieldname, die, cu);
14025
14026       /* The name is already allocated along with this objfile, so we don't
14027          need to duplicate it for the type.  */
14028       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
14029       FIELD_TYPE (*fp) = die_type (die, cu);
14030       FIELD_NAME (*fp) = fieldname;
14031     }
14032   else if (die->tag == DW_TAG_inheritance)
14033     {
14034       LONGEST offset;
14035
14036       /* C++ base class field.  */
14037       if (handle_data_member_location (die, cu, &offset))
14038         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
14039       FIELD_BITSIZE (*fp) = 0;
14040       FIELD_TYPE (*fp) = die_type (die, cu);
14041       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
14042       fip->nbaseclasses++;
14043     }
14044 }
14045
14046 /* Can the type given by DIE define another type?  */
14047
14048 static bool
14049 type_can_define_types (const struct die_info *die)
14050 {
14051   switch (die->tag)
14052     {
14053     case DW_TAG_typedef:
14054     case DW_TAG_class_type:
14055     case DW_TAG_structure_type:
14056     case DW_TAG_union_type:
14057     case DW_TAG_enumeration_type:
14058       return true;
14059
14060     default:
14061       return false;
14062     }
14063 }
14064
14065 /* Add a type definition defined in the scope of the FIP's class.  */
14066
14067 static void
14068 dwarf2_add_type_defn (struct field_info *fip, struct die_info *die,
14069                       struct dwarf2_cu *cu)
14070 {
14071   struct decl_field_list *new_field;
14072   struct decl_field *fp;
14073
14074   /* Allocate a new field list entry and link it in.  */
14075   new_field = XCNEW (struct decl_field_list);
14076   make_cleanup (xfree, new_field);
14077
14078   gdb_assert (type_can_define_types (die));
14079
14080   fp = &new_field->field;
14081
14082   /* Get name of field.  NULL is okay here, meaning an anonymous type.  */
14083   fp->name = dwarf2_name (die, cu);
14084   fp->type = read_type_die (die, cu);
14085
14086   /* Save accessibility.  */
14087   enum dwarf_access_attribute accessibility;
14088   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14089   if (attr != NULL)
14090     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14091   else
14092     accessibility = dwarf2_default_access_attribute (die, cu);
14093   switch (accessibility)
14094     {
14095     case DW_ACCESS_public:
14096       /* The assumed value if neither private nor protected.  */
14097       break;
14098     case DW_ACCESS_private:
14099       fp->is_private = 1;
14100       break;
14101     case DW_ACCESS_protected:
14102       fp->is_protected = 1;
14103       break;
14104     default:
14105       complaint (&symfile_complaints,
14106                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
14107     }
14108
14109   if (die->tag == DW_TAG_typedef)
14110     {
14111       new_field->next = fip->typedef_field_list;
14112       fip->typedef_field_list = new_field;
14113       fip->typedef_field_list_count++;
14114     }
14115   else
14116     {
14117       new_field->next = fip->nested_types_list;
14118       fip->nested_types_list = new_field;
14119       fip->nested_types_list_count++;
14120     }
14121 }
14122
14123 /* Create the vector of fields, and attach it to the type.  */
14124
14125 static void
14126 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
14127                               struct dwarf2_cu *cu)
14128 {
14129   int nfields = fip->nfields;
14130
14131   /* Record the field count, allocate space for the array of fields,
14132      and create blank accessibility bitfields if necessary.  */
14133   TYPE_NFIELDS (type) = nfields;
14134   TYPE_FIELDS (type) = (struct field *)
14135     TYPE_ALLOC (type, sizeof (struct field) * nfields);
14136   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
14137
14138   if (fip->non_public_fields && cu->language != language_ada)
14139     {
14140       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14141
14142       TYPE_FIELD_PRIVATE_BITS (type) =
14143         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14144       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
14145
14146       TYPE_FIELD_PROTECTED_BITS (type) =
14147         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14148       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
14149
14150       TYPE_FIELD_IGNORE_BITS (type) =
14151         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
14152       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
14153     }
14154
14155   /* If the type has baseclasses, allocate and clear a bit vector for
14156      TYPE_FIELD_VIRTUAL_BITS.  */
14157   if (fip->nbaseclasses && cu->language != language_ada)
14158     {
14159       int num_bytes = B_BYTES (fip->nbaseclasses);
14160       unsigned char *pointer;
14161
14162       ALLOCATE_CPLUS_STRUCT_TYPE (type);
14163       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
14164       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
14165       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
14166       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
14167     }
14168
14169   /* Copy the saved-up fields into the field vector.  Start from the head of
14170      the list, adding to the tail of the field array, so that they end up in
14171      the same order in the array in which they were added to the list.  */
14172   while (nfields-- > 0)
14173     {
14174       struct nextfield *fieldp;
14175
14176       if (fip->fields)
14177         {
14178           fieldp = fip->fields;
14179           fip->fields = fieldp->next;
14180         }
14181       else
14182         {
14183           fieldp = fip->baseclasses;
14184           fip->baseclasses = fieldp->next;
14185         }
14186
14187       TYPE_FIELD (type, nfields) = fieldp->field;
14188       switch (fieldp->accessibility)
14189         {
14190         case DW_ACCESS_private:
14191           if (cu->language != language_ada)
14192             SET_TYPE_FIELD_PRIVATE (type, nfields);
14193           break;
14194
14195         case DW_ACCESS_protected:
14196           if (cu->language != language_ada)
14197             SET_TYPE_FIELD_PROTECTED (type, nfields);
14198           break;
14199
14200         case DW_ACCESS_public:
14201           break;
14202
14203         default:
14204           /* Unknown accessibility.  Complain and treat it as public.  */
14205           {
14206             complaint (&symfile_complaints, _("unsupported accessibility %d"),
14207                        fieldp->accessibility);
14208           }
14209           break;
14210         }
14211       if (nfields < fip->nbaseclasses)
14212         {
14213           switch (fieldp->virtuality)
14214             {
14215             case DW_VIRTUALITY_virtual:
14216             case DW_VIRTUALITY_pure_virtual:
14217               if (cu->language == language_ada)
14218                 error (_("unexpected virtuality in component of Ada type"));
14219               SET_TYPE_FIELD_VIRTUAL (type, nfields);
14220               break;
14221             }
14222         }
14223     }
14224 }
14225
14226 /* Return true if this member function is a constructor, false
14227    otherwise.  */
14228
14229 static int
14230 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
14231 {
14232   const char *fieldname;
14233   const char *type_name;
14234   int len;
14235
14236   if (die->parent == NULL)
14237     return 0;
14238
14239   if (die->parent->tag != DW_TAG_structure_type
14240       && die->parent->tag != DW_TAG_union_type
14241       && die->parent->tag != DW_TAG_class_type)
14242     return 0;
14243
14244   fieldname = dwarf2_name (die, cu);
14245   type_name = dwarf2_name (die->parent, cu);
14246   if (fieldname == NULL || type_name == NULL)
14247     return 0;
14248
14249   len = strlen (fieldname);
14250   return (strncmp (fieldname, type_name, len) == 0
14251           && (type_name[len] == '\0' || type_name[len] == '<'));
14252 }
14253
14254 /* Add a member function to the proper fieldlist.  */
14255
14256 static void
14257 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
14258                       struct type *type, struct dwarf2_cu *cu)
14259 {
14260   struct objfile *objfile = cu->objfile;
14261   struct attribute *attr;
14262   struct fnfieldlist *flp;
14263   int i;
14264   struct fn_field *fnp;
14265   const char *fieldname;
14266   struct nextfnfield *new_fnfield;
14267   struct type *this_type;
14268   enum dwarf_access_attribute accessibility;
14269
14270   if (cu->language == language_ada)
14271     error (_("unexpected member function in Ada type"));
14272
14273   /* Get name of member function.  */
14274   fieldname = dwarf2_name (die, cu);
14275   if (fieldname == NULL)
14276     return;
14277
14278   /* Look up member function name in fieldlist.  */
14279   for (i = 0; i < fip->nfnfields; i++)
14280     {
14281       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
14282         break;
14283     }
14284
14285   /* Create new list element if necessary.  */
14286   if (i < fip->nfnfields)
14287     flp = &fip->fnfieldlists[i];
14288   else
14289     {
14290       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
14291         {
14292           fip->fnfieldlists = (struct fnfieldlist *)
14293             xrealloc (fip->fnfieldlists,
14294                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
14295                       * sizeof (struct fnfieldlist));
14296           if (fip->nfnfields == 0)
14297             make_cleanup (free_current_contents, &fip->fnfieldlists);
14298         }
14299       flp = &fip->fnfieldlists[fip->nfnfields];
14300       flp->name = fieldname;
14301       flp->length = 0;
14302       flp->head = NULL;
14303       i = fip->nfnfields++;
14304     }
14305
14306   /* Create a new member function field and chain it to the field list
14307      entry.  */
14308   new_fnfield = XNEW (struct nextfnfield);
14309   make_cleanup (xfree, new_fnfield);
14310   memset (new_fnfield, 0, sizeof (struct nextfnfield));
14311   new_fnfield->next = flp->head;
14312   flp->head = new_fnfield;
14313   flp->length++;
14314
14315   /* Fill in the member function field info.  */
14316   fnp = &new_fnfield->fnfield;
14317
14318   /* Delay processing of the physname until later.  */
14319   if (cu->language == language_cplus)
14320     {
14321       add_to_method_list (type, i, flp->length - 1, fieldname,
14322                           die, cu);
14323     }
14324   else
14325     {
14326       const char *physname = dwarf2_physname (fieldname, die, cu);
14327       fnp->physname = physname ? physname : "";
14328     }
14329
14330   fnp->type = alloc_type (objfile);
14331   this_type = read_type_die (die, cu);
14332   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
14333     {
14334       int nparams = TYPE_NFIELDS (this_type);
14335
14336       /* TYPE is the domain of this method, and THIS_TYPE is the type
14337            of the method itself (TYPE_CODE_METHOD).  */
14338       smash_to_method_type (fnp->type, type,
14339                             TYPE_TARGET_TYPE (this_type),
14340                             TYPE_FIELDS (this_type),
14341                             TYPE_NFIELDS (this_type),
14342                             TYPE_VARARGS (this_type));
14343
14344       /* Handle static member functions.
14345          Dwarf2 has no clean way to discern C++ static and non-static
14346          member functions.  G++ helps GDB by marking the first
14347          parameter for non-static member functions (which is the this
14348          pointer) as artificial.  We obtain this information from
14349          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
14350       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
14351         fnp->voffset = VOFFSET_STATIC;
14352     }
14353   else
14354     complaint (&symfile_complaints, _("member function type missing for '%s'"),
14355                dwarf2_full_name (fieldname, die, cu));
14356
14357   /* Get fcontext from DW_AT_containing_type if present.  */
14358   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14359     fnp->fcontext = die_containing_type (die, cu);
14360
14361   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
14362      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
14363
14364   /* Get accessibility.  */
14365   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
14366   if (attr)
14367     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
14368   else
14369     accessibility = dwarf2_default_access_attribute (die, cu);
14370   switch (accessibility)
14371     {
14372     case DW_ACCESS_private:
14373       fnp->is_private = 1;
14374       break;
14375     case DW_ACCESS_protected:
14376       fnp->is_protected = 1;
14377       break;
14378     }
14379
14380   /* Check for artificial methods.  */
14381   attr = dwarf2_attr (die, DW_AT_artificial, cu);
14382   if (attr && DW_UNSND (attr) != 0)
14383     fnp->is_artificial = 1;
14384
14385   fnp->is_constructor = dwarf2_is_constructor (die, cu);
14386
14387   /* Get index in virtual function table if it is a virtual member
14388      function.  For older versions of GCC, this is an offset in the
14389      appropriate virtual table, as specified by DW_AT_containing_type.
14390      For everyone else, it is an expression to be evaluated relative
14391      to the object address.  */
14392
14393   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
14394   if (attr)
14395     {
14396       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
14397         {
14398           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
14399             {
14400               /* Old-style GCC.  */
14401               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
14402             }
14403           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
14404                    || (DW_BLOCK (attr)->size > 1
14405                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
14406                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
14407             {
14408               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
14409               if ((fnp->voffset % cu->header.addr_size) != 0)
14410                 dwarf2_complex_location_expr_complaint ();
14411               else
14412                 fnp->voffset /= cu->header.addr_size;
14413               fnp->voffset += 2;
14414             }
14415           else
14416             dwarf2_complex_location_expr_complaint ();
14417
14418           if (!fnp->fcontext)
14419             {
14420               /* If there is no `this' field and no DW_AT_containing_type,
14421                  we cannot actually find a base class context for the
14422                  vtable!  */
14423               if (TYPE_NFIELDS (this_type) == 0
14424                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
14425                 {
14426                   complaint (&symfile_complaints,
14427                              _("cannot determine context for virtual member "
14428                                "function \"%s\" (offset %d)"),
14429                              fieldname, to_underlying (die->sect_off));
14430                 }
14431               else
14432                 {
14433                   fnp->fcontext
14434                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
14435                 }
14436             }
14437         }
14438       else if (attr_form_is_section_offset (attr))
14439         {
14440           dwarf2_complex_location_expr_complaint ();
14441         }
14442       else
14443         {
14444           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
14445                                                  fieldname);
14446         }
14447     }
14448   else
14449     {
14450       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
14451       if (attr && DW_UNSND (attr))
14452         {
14453           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
14454           complaint (&symfile_complaints,
14455                      _("Member function \"%s\" (offset %d) is virtual "
14456                        "but the vtable offset is not specified"),
14457                      fieldname, to_underlying (die->sect_off));
14458           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14459           TYPE_CPLUS_DYNAMIC (type) = 1;
14460         }
14461     }
14462 }
14463
14464 /* Create the vector of member function fields, and attach it to the type.  */
14465
14466 static void
14467 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
14468                                  struct dwarf2_cu *cu)
14469 {
14470   struct fnfieldlist *flp;
14471   int i;
14472
14473   if (cu->language == language_ada)
14474     error (_("unexpected member functions in Ada type"));
14475
14476   ALLOCATE_CPLUS_STRUCT_TYPE (type);
14477   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
14478     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
14479
14480   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
14481     {
14482       struct nextfnfield *nfp = flp->head;
14483       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
14484       int k;
14485
14486       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
14487       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
14488       fn_flp->fn_fields = (struct fn_field *)
14489         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
14490       for (k = flp->length; (k--, nfp); nfp = nfp->next)
14491         fn_flp->fn_fields[k] = nfp->fnfield;
14492     }
14493
14494   TYPE_NFN_FIELDS (type) = fip->nfnfields;
14495 }
14496
14497 /* Returns non-zero if NAME is the name of a vtable member in CU's
14498    language, zero otherwise.  */
14499 static int
14500 is_vtable_name (const char *name, struct dwarf2_cu *cu)
14501 {
14502   static const char vptr[] = "_vptr";
14503
14504   /* Look for the C++ form of the vtable.  */
14505   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
14506     return 1;
14507
14508   return 0;
14509 }
14510
14511 /* GCC outputs unnamed structures that are really pointers to member
14512    functions, with the ABI-specified layout.  If TYPE describes
14513    such a structure, smash it into a member function type.
14514
14515    GCC shouldn't do this; it should just output pointer to member DIEs.
14516    This is GCC PR debug/28767.  */
14517
14518 static void
14519 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
14520 {
14521   struct type *pfn_type, *self_type, *new_type;
14522
14523   /* Check for a structure with no name and two children.  */
14524   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
14525     return;
14526
14527   /* Check for __pfn and __delta members.  */
14528   if (TYPE_FIELD_NAME (type, 0) == NULL
14529       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
14530       || TYPE_FIELD_NAME (type, 1) == NULL
14531       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
14532     return;
14533
14534   /* Find the type of the method.  */
14535   pfn_type = TYPE_FIELD_TYPE (type, 0);
14536   if (pfn_type == NULL
14537       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
14538       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
14539     return;
14540
14541   /* Look for the "this" argument.  */
14542   pfn_type = TYPE_TARGET_TYPE (pfn_type);
14543   if (TYPE_NFIELDS (pfn_type) == 0
14544       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
14545       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
14546     return;
14547
14548   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
14549   new_type = alloc_type (objfile);
14550   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
14551                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
14552                         TYPE_VARARGS (pfn_type));
14553   smash_to_methodptr_type (type, new_type);
14554 }
14555
14556
14557 /* Called when we find the DIE that starts a structure or union scope
14558    (definition) to create a type for the structure or union.  Fill in
14559    the type's name and general properties; the members will not be
14560    processed until process_structure_scope.  A symbol table entry for
14561    the type will also not be done until process_structure_scope (assuming
14562    the type has a name).
14563
14564    NOTE: we need to call these functions regardless of whether or not the
14565    DIE has a DW_AT_name attribute, since it might be an anonymous
14566    structure or union.  This gets the type entered into our set of
14567    user defined types.  */
14568
14569 static struct type *
14570 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
14571 {
14572   struct objfile *objfile = cu->objfile;
14573   struct type *type;
14574   struct attribute *attr;
14575   const char *name;
14576
14577   /* If the definition of this type lives in .debug_types, read that type.
14578      Don't follow DW_AT_specification though, that will take us back up
14579      the chain and we want to go down.  */
14580   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14581   if (attr)
14582     {
14583       type = get_DW_AT_signature_type (die, attr, cu);
14584
14585       /* The type's CU may not be the same as CU.
14586          Ensure TYPE is recorded with CU in die_type_hash.  */
14587       return set_die_type (die, type, cu);
14588     }
14589
14590   type = alloc_type (objfile);
14591   INIT_CPLUS_SPECIFIC (type);
14592
14593   name = dwarf2_name (die, cu);
14594   if (name != NULL)
14595     {
14596       if (cu->language == language_cplus
14597           || cu->language == language_d
14598           || cu->language == language_rust)
14599         {
14600           const char *full_name = dwarf2_full_name (name, die, cu);
14601
14602           /* dwarf2_full_name might have already finished building the DIE's
14603              type.  If so, there is no need to continue.  */
14604           if (get_die_type (die, cu) != NULL)
14605             return get_die_type (die, cu);
14606
14607           TYPE_TAG_NAME (type) = full_name;
14608           if (die->tag == DW_TAG_structure_type
14609               || die->tag == DW_TAG_class_type)
14610             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14611         }
14612       else
14613         {
14614           /* The name is already allocated along with this objfile, so
14615              we don't need to duplicate it for the type.  */
14616           TYPE_TAG_NAME (type) = name;
14617           if (die->tag == DW_TAG_class_type)
14618             TYPE_NAME (type) = TYPE_TAG_NAME (type);
14619         }
14620     }
14621
14622   if (die->tag == DW_TAG_structure_type)
14623     {
14624       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14625     }
14626   else if (die->tag == DW_TAG_union_type)
14627     {
14628       TYPE_CODE (type) = TYPE_CODE_UNION;
14629     }
14630   else
14631     {
14632       TYPE_CODE (type) = TYPE_CODE_STRUCT;
14633     }
14634
14635   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
14636     TYPE_DECLARED_CLASS (type) = 1;
14637
14638   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14639   if (attr)
14640     {
14641       if (attr_form_is_constant (attr))
14642         TYPE_LENGTH (type) = DW_UNSND (attr);
14643       else
14644         {
14645           /* For the moment, dynamic type sizes are not supported
14646              by GDB's struct type.  The actual size is determined
14647              on-demand when resolving the type of a given object,
14648              so set the type's length to zero for now.  Otherwise,
14649              we record an expression as the length, and that expression
14650              could lead to a very large value, which could eventually
14651              lead to us trying to allocate that much memory when creating
14652              a value of that type.  */
14653           TYPE_LENGTH (type) = 0;
14654         }
14655     }
14656   else
14657     {
14658       TYPE_LENGTH (type) = 0;
14659     }
14660
14661   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
14662     {
14663       /* ICC<14 does not output the required DW_AT_declaration on
14664          incomplete types, but gives them a size of zero.  */
14665       TYPE_STUB (type) = 1;
14666     }
14667   else
14668     TYPE_STUB_SUPPORTED (type) = 1;
14669
14670   if (die_is_declaration (die, cu))
14671     TYPE_STUB (type) = 1;
14672   else if (attr == NULL && die->child == NULL
14673            && producer_is_realview (cu->producer))
14674     /* RealView does not output the required DW_AT_declaration
14675        on incomplete types.  */
14676     TYPE_STUB (type) = 1;
14677
14678   /* We need to add the type field to the die immediately so we don't
14679      infinitely recurse when dealing with pointers to the structure
14680      type within the structure itself.  */
14681   set_die_type (die, type, cu);
14682
14683   /* set_die_type should be already done.  */
14684   set_descriptive_type (type, die, cu);
14685
14686   return type;
14687 }
14688
14689 /* Finish creating a structure or union type, including filling in
14690    its members and creating a symbol for it.  */
14691
14692 static void
14693 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14694 {
14695   struct objfile *objfile = cu->objfile;
14696   struct die_info *child_die;
14697   struct type *type;
14698
14699   type = get_die_type (die, cu);
14700   if (type == NULL)
14701     type = read_structure_type (die, cu);
14702
14703   if (die->child != NULL && ! die_is_declaration (die, cu))
14704     {
14705       struct field_info fi;
14706       std::vector<struct symbol *> template_args;
14707       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14708
14709       memset (&fi, 0, sizeof (struct field_info));
14710
14711       child_die = die->child;
14712
14713       while (child_die && child_die->tag)
14714         {
14715           if (child_die->tag == DW_TAG_member
14716               || child_die->tag == DW_TAG_variable)
14717             {
14718               /* NOTE: carlton/2002-11-05: A C++ static data member
14719                  should be a DW_TAG_member that is a declaration, but
14720                  all versions of G++ as of this writing (so through at
14721                  least 3.2.1) incorrectly generate DW_TAG_variable
14722                  tags for them instead.  */
14723               dwarf2_add_field (&fi, child_die, cu);
14724             }
14725           else if (child_die->tag == DW_TAG_subprogram)
14726             {
14727               /* Rust doesn't have member functions in the C++ sense.
14728                  However, it does emit ordinary functions as children
14729                  of a struct DIE.  */
14730               if (cu->language == language_rust)
14731                 read_func_scope (child_die, cu);
14732               else
14733                 {
14734                   /* C++ member function.  */
14735                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14736                 }
14737             }
14738           else if (child_die->tag == DW_TAG_inheritance)
14739             {
14740               /* C++ base class field.  */
14741               dwarf2_add_field (&fi, child_die, cu);
14742             }
14743           else if (type_can_define_types (child_die))
14744             dwarf2_add_type_defn (&fi, child_die, cu);
14745           else if (child_die->tag == DW_TAG_template_type_param
14746                    || child_die->tag == DW_TAG_template_value_param)
14747             {
14748               struct symbol *arg = new_symbol (child_die, NULL, cu);
14749
14750               if (arg != NULL)
14751                 template_args.push_back (arg);
14752             }
14753
14754           child_die = sibling_die (child_die);
14755         }
14756
14757       /* Attach template arguments to type.  */
14758       if (!template_args.empty ())
14759         {
14760           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14761           TYPE_N_TEMPLATE_ARGUMENTS (type) = template_args.size ();
14762           TYPE_TEMPLATE_ARGUMENTS (type)
14763             = XOBNEWVEC (&objfile->objfile_obstack,
14764                          struct symbol *,
14765                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14766           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14767                   template_args.data (),
14768                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14769                    * sizeof (struct symbol *)));
14770         }
14771
14772       /* Attach fields and member functions to the type.  */
14773       if (fi.nfields)
14774         dwarf2_attach_fields_to_type (&fi, type, cu);
14775       if (fi.nfnfields)
14776         {
14777           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14778
14779           /* Get the type which refers to the base class (possibly this
14780              class itself) which contains the vtable pointer for the current
14781              class from the DW_AT_containing_type attribute.  This use of
14782              DW_AT_containing_type is a GNU extension.  */
14783
14784           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14785             {
14786               struct type *t = die_containing_type (die, cu);
14787
14788               set_type_vptr_basetype (type, t);
14789               if (type == t)
14790                 {
14791                   int i;
14792
14793                   /* Our own class provides vtbl ptr.  */
14794                   for (i = TYPE_NFIELDS (t) - 1;
14795                        i >= TYPE_N_BASECLASSES (t);
14796                        --i)
14797                     {
14798                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14799
14800                       if (is_vtable_name (fieldname, cu))
14801                         {
14802                           set_type_vptr_fieldno (type, i);
14803                           break;
14804                         }
14805                     }
14806
14807                   /* Complain if virtual function table field not found.  */
14808                   if (i < TYPE_N_BASECLASSES (t))
14809                     complaint (&symfile_complaints,
14810                                _("virtual function table pointer "
14811                                  "not found when defining class '%s'"),
14812                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14813                                "");
14814                 }
14815               else
14816                 {
14817                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14818                 }
14819             }
14820           else if (cu->producer
14821                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14822             {
14823               /* The IBM XLC compiler does not provide direct indication
14824                  of the containing type, but the vtable pointer is
14825                  always named __vfp.  */
14826
14827               int i;
14828
14829               for (i = TYPE_NFIELDS (type) - 1;
14830                    i >= TYPE_N_BASECLASSES (type);
14831                    --i)
14832                 {
14833                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14834                     {
14835                       set_type_vptr_fieldno (type, i);
14836                       set_type_vptr_basetype (type, type);
14837                       break;
14838                     }
14839                 }
14840             }
14841         }
14842
14843       /* Copy fi.typedef_field_list linked list elements content into the
14844          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14845       if (fi.typedef_field_list)
14846         {
14847           int i = fi.typedef_field_list_count;
14848
14849           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14850           TYPE_TYPEDEF_FIELD_ARRAY (type)
14851             = ((struct decl_field *)
14852                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14853           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14854
14855           /* Reverse the list order to keep the debug info elements order.  */
14856           while (--i >= 0)
14857             {
14858               struct decl_field *dest, *src;
14859
14860               dest = &TYPE_TYPEDEF_FIELD (type, i);
14861               src = &fi.typedef_field_list->field;
14862               fi.typedef_field_list = fi.typedef_field_list->next;
14863               *dest = *src;
14864             }
14865         }
14866
14867       /* Copy fi.nested_types_list linked list elements content into the
14868          allocated array TYPE_NESTED_TYPES_ARRAY (type).  */
14869       if (fi.nested_types_list != NULL && cu->language != language_ada)
14870         {
14871           int i = fi.nested_types_list_count;
14872
14873           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14874           TYPE_NESTED_TYPES_ARRAY (type)
14875             = ((struct decl_field *)
14876                TYPE_ALLOC (type, sizeof (struct decl_field) * i));
14877           TYPE_NESTED_TYPES_COUNT (type) = i;
14878
14879           /* Reverse the list order to keep the debug info elements order.  */
14880           while (--i >= 0)
14881             {
14882               struct decl_field *dest, *src;
14883
14884               dest = &TYPE_NESTED_TYPES_FIELD (type, i);
14885               src = &fi.nested_types_list->field;
14886               fi.nested_types_list = fi.nested_types_list->next;
14887               *dest = *src;
14888             }
14889         }
14890
14891       do_cleanups (back_to);
14892     }
14893
14894   quirk_gcc_member_function_pointer (type, objfile);
14895
14896   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14897      snapshots) has been known to create a die giving a declaration
14898      for a class that has, as a child, a die giving a definition for a
14899      nested class.  So we have to process our children even if the
14900      current die is a declaration.  Normally, of course, a declaration
14901      won't have any children at all.  */
14902
14903   child_die = die->child;
14904
14905   while (child_die != NULL && child_die->tag)
14906     {
14907       if (child_die->tag == DW_TAG_member
14908           || child_die->tag == DW_TAG_variable
14909           || child_die->tag == DW_TAG_inheritance
14910           || child_die->tag == DW_TAG_template_value_param
14911           || child_die->tag == DW_TAG_template_type_param)
14912         {
14913           /* Do nothing.  */
14914         }
14915       else
14916         process_die (child_die, cu);
14917
14918       child_die = sibling_die (child_die);
14919     }
14920
14921   /* Do not consider external references.  According to the DWARF standard,
14922      these DIEs are identified by the fact that they have no byte_size
14923      attribute, and a declaration attribute.  */
14924   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14925       || !die_is_declaration (die, cu))
14926     new_symbol (die, type, cu);
14927 }
14928
14929 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14930    update TYPE using some information only available in DIE's children.  */
14931
14932 static void
14933 update_enumeration_type_from_children (struct die_info *die,
14934                                        struct type *type,
14935                                        struct dwarf2_cu *cu)
14936 {
14937   struct die_info *child_die;
14938   int unsigned_enum = 1;
14939   int flag_enum = 1;
14940   ULONGEST mask = 0;
14941
14942   auto_obstack obstack;
14943
14944   for (child_die = die->child;
14945        child_die != NULL && child_die->tag;
14946        child_die = sibling_die (child_die))
14947     {
14948       struct attribute *attr;
14949       LONGEST value;
14950       const gdb_byte *bytes;
14951       struct dwarf2_locexpr_baton *baton;
14952       const char *name;
14953
14954       if (child_die->tag != DW_TAG_enumerator)
14955         continue;
14956
14957       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14958       if (attr == NULL)
14959         continue;
14960
14961       name = dwarf2_name (child_die, cu);
14962       if (name == NULL)
14963         name = "<anonymous enumerator>";
14964
14965       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14966                                &value, &bytes, &baton);
14967       if (value < 0)
14968         {
14969           unsigned_enum = 0;
14970           flag_enum = 0;
14971         }
14972       else if ((mask & value) != 0)
14973         flag_enum = 0;
14974       else
14975         mask |= value;
14976
14977       /* If we already know that the enum type is neither unsigned, nor
14978          a flag type, no need to look at the rest of the enumerates.  */
14979       if (!unsigned_enum && !flag_enum)
14980         break;
14981     }
14982
14983   if (unsigned_enum)
14984     TYPE_UNSIGNED (type) = 1;
14985   if (flag_enum)
14986     TYPE_FLAG_ENUM (type) = 1;
14987 }
14988
14989 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14990    complete the type's fields yet, or create any symbols.  */
14991
14992 static struct type *
14993 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14994 {
14995   struct objfile *objfile = cu->objfile;
14996   struct type *type;
14997   struct attribute *attr;
14998   const char *name;
14999
15000   /* If the definition of this type lives in .debug_types, read that type.
15001      Don't follow DW_AT_specification though, that will take us back up
15002      the chain and we want to go down.  */
15003   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
15004   if (attr)
15005     {
15006       type = get_DW_AT_signature_type (die, attr, cu);
15007
15008       /* The type's CU may not be the same as CU.
15009          Ensure TYPE is recorded with CU in die_type_hash.  */
15010       return set_die_type (die, type, cu);
15011     }
15012
15013   type = alloc_type (objfile);
15014
15015   TYPE_CODE (type) = TYPE_CODE_ENUM;
15016   name = dwarf2_full_name (NULL, die, cu);
15017   if (name != NULL)
15018     TYPE_TAG_NAME (type) = name;
15019
15020   attr = dwarf2_attr (die, DW_AT_type, cu);
15021   if (attr != NULL)
15022     {
15023       struct type *underlying_type = die_type (die, cu);
15024
15025       TYPE_TARGET_TYPE (type) = underlying_type;
15026     }
15027
15028   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15029   if (attr)
15030     {
15031       TYPE_LENGTH (type) = DW_UNSND (attr);
15032     }
15033   else
15034     {
15035       TYPE_LENGTH (type) = 0;
15036     }
15037
15038   /* The enumeration DIE can be incomplete.  In Ada, any type can be
15039      declared as private in the package spec, and then defined only
15040      inside the package body.  Such types are known as Taft Amendment
15041      Types.  When another package uses such a type, an incomplete DIE
15042      may be generated by the compiler.  */
15043   if (die_is_declaration (die, cu))
15044     TYPE_STUB (type) = 1;
15045
15046   /* Finish the creation of this type by using the enum's children.
15047      We must call this even when the underlying type has been provided
15048      so that we can determine if we're looking at a "flag" enum.  */
15049   update_enumeration_type_from_children (die, type, cu);
15050
15051   /* If this type has an underlying type that is not a stub, then we
15052      may use its attributes.  We always use the "unsigned" attribute
15053      in this situation, because ordinarily we guess whether the type
15054      is unsigned -- but the guess can be wrong and the underlying type
15055      can tell us the reality.  However, we defer to a local size
15056      attribute if one exists, because this lets the compiler override
15057      the underlying type if needed.  */
15058   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
15059     {
15060       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
15061       if (TYPE_LENGTH (type) == 0)
15062         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
15063     }
15064
15065   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
15066
15067   return set_die_type (die, type, cu);
15068 }
15069
15070 /* Given a pointer to a die which begins an enumeration, process all
15071    the dies that define the members of the enumeration, and create the
15072    symbol for the enumeration type.
15073
15074    NOTE: We reverse the order of the element list.  */
15075
15076 static void
15077 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
15078 {
15079   struct type *this_type;
15080
15081   this_type = get_die_type (die, cu);
15082   if (this_type == NULL)
15083     this_type = read_enumeration_type (die, cu);
15084
15085   if (die->child != NULL)
15086     {
15087       struct die_info *child_die;
15088       struct symbol *sym;
15089       struct field *fields = NULL;
15090       int num_fields = 0;
15091       const char *name;
15092
15093       child_die = die->child;
15094       while (child_die && child_die->tag)
15095         {
15096           if (child_die->tag != DW_TAG_enumerator)
15097             {
15098               process_die (child_die, cu);
15099             }
15100           else
15101             {
15102               name = dwarf2_name (child_die, cu);
15103               if (name)
15104                 {
15105                   sym = new_symbol (child_die, this_type, cu);
15106
15107                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
15108                     {
15109                       fields = (struct field *)
15110                         xrealloc (fields,
15111                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
15112                                   * sizeof (struct field));
15113                     }
15114
15115                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
15116                   FIELD_TYPE (fields[num_fields]) = NULL;
15117                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
15118                   FIELD_BITSIZE (fields[num_fields]) = 0;
15119
15120                   num_fields++;
15121                 }
15122             }
15123
15124           child_die = sibling_die (child_die);
15125         }
15126
15127       if (num_fields)
15128         {
15129           TYPE_NFIELDS (this_type) = num_fields;
15130           TYPE_FIELDS (this_type) = (struct field *)
15131             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
15132           memcpy (TYPE_FIELDS (this_type), fields,
15133                   sizeof (struct field) * num_fields);
15134           xfree (fields);
15135         }
15136     }
15137
15138   /* If we are reading an enum from a .debug_types unit, and the enum
15139      is a declaration, and the enum is not the signatured type in the
15140      unit, then we do not want to add a symbol for it.  Adding a
15141      symbol would in some cases obscure the true definition of the
15142      enum, giving users an incomplete type when the definition is
15143      actually available.  Note that we do not want to do this for all
15144      enums which are just declarations, because C++0x allows forward
15145      enum declarations.  */
15146   if (cu->per_cu->is_debug_types
15147       && die_is_declaration (die, cu))
15148     {
15149       struct signatured_type *sig_type;
15150
15151       sig_type = (struct signatured_type *) cu->per_cu;
15152       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
15153       if (sig_type->type_offset_in_section != die->sect_off)
15154         return;
15155     }
15156
15157   new_symbol (die, this_type, cu);
15158 }
15159
15160 /* Extract all information from a DW_TAG_array_type DIE and put it in
15161    the DIE's type field.  For now, this only handles one dimensional
15162    arrays.  */
15163
15164 static struct type *
15165 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
15166 {
15167   struct objfile *objfile = cu->objfile;
15168   struct die_info *child_die;
15169   struct type *type;
15170   struct type *element_type, *range_type, *index_type;
15171   struct attribute *attr;
15172   const char *name;
15173   unsigned int bit_stride = 0;
15174
15175   element_type = die_type (die, cu);
15176
15177   /* The die_type call above may have already set the type for this DIE.  */
15178   type = get_die_type (die, cu);
15179   if (type)
15180     return type;
15181
15182   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
15183   if (attr != NULL)
15184     bit_stride = DW_UNSND (attr) * 8;
15185
15186   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
15187   if (attr != NULL)
15188     bit_stride = DW_UNSND (attr);
15189
15190   /* Irix 6.2 native cc creates array types without children for
15191      arrays with unspecified length.  */
15192   if (die->child == NULL)
15193     {
15194       index_type = objfile_type (objfile)->builtin_int;
15195       range_type = create_static_range_type (NULL, index_type, 0, -1);
15196       type = create_array_type_with_stride (NULL, element_type, range_type,
15197                                             bit_stride);
15198       return set_die_type (die, type, cu);
15199     }
15200
15201   std::vector<struct type *> range_types;
15202   child_die = die->child;
15203   while (child_die && child_die->tag)
15204     {
15205       if (child_die->tag == DW_TAG_subrange_type)
15206         {
15207           struct type *child_type = read_type_die (child_die, cu);
15208
15209           if (child_type != NULL)
15210             {
15211               /* The range type was succesfully read.  Save it for the
15212                  array type creation.  */
15213               range_types.push_back (child_type);
15214             }
15215         }
15216       child_die = sibling_die (child_die);
15217     }
15218
15219   /* Dwarf2 dimensions are output from left to right, create the
15220      necessary array types in backwards order.  */
15221
15222   type = element_type;
15223
15224   if (read_array_order (die, cu) == DW_ORD_col_major)
15225     {
15226       int i = 0;
15227
15228       while (i < range_types.size ())
15229         type = create_array_type_with_stride (NULL, type, range_types[i++],
15230                                               bit_stride);
15231     }
15232   else
15233     {
15234       size_t ndim = range_types.size ();
15235       while (ndim-- > 0)
15236         type = create_array_type_with_stride (NULL, type, range_types[ndim],
15237                                               bit_stride);
15238     }
15239
15240   /* Understand Dwarf2 support for vector types (like they occur on
15241      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
15242      array type.  This is not part of the Dwarf2/3 standard yet, but a
15243      custom vendor extension.  The main difference between a regular
15244      array and the vector variant is that vectors are passed by value
15245      to functions.  */
15246   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
15247   if (attr)
15248     make_vector_type (type);
15249
15250   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
15251      implementation may choose to implement triple vectors using this
15252      attribute.  */
15253   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15254   if (attr)
15255     {
15256       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
15257         TYPE_LENGTH (type) = DW_UNSND (attr);
15258       else
15259         complaint (&symfile_complaints,
15260                    _("DW_AT_byte_size for array type smaller "
15261                      "than the total size of elements"));
15262     }
15263
15264   name = dwarf2_name (die, cu);
15265   if (name)
15266     TYPE_NAME (type) = name;
15267
15268   /* Install the type in the die.  */
15269   set_die_type (die, type, cu);
15270
15271   /* set_die_type should be already done.  */
15272   set_descriptive_type (type, die, cu);
15273
15274   return type;
15275 }
15276
15277 static enum dwarf_array_dim_ordering
15278 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
15279 {
15280   struct attribute *attr;
15281
15282   attr = dwarf2_attr (die, DW_AT_ordering, cu);
15283
15284   if (attr)
15285     return (enum dwarf_array_dim_ordering) DW_SND (attr);
15286
15287   /* GNU F77 is a special case, as at 08/2004 array type info is the
15288      opposite order to the dwarf2 specification, but data is still
15289      laid out as per normal fortran.
15290
15291      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
15292      version checking.  */
15293
15294   if (cu->language == language_fortran
15295       && cu->producer && strstr (cu->producer, "GNU F77"))
15296     {
15297       return DW_ORD_row_major;
15298     }
15299
15300   switch (cu->language_defn->la_array_ordering)
15301     {
15302     case array_column_major:
15303       return DW_ORD_col_major;
15304     case array_row_major:
15305     default:
15306       return DW_ORD_row_major;
15307     };
15308 }
15309
15310 /* Extract all information from a DW_TAG_set_type DIE and put it in
15311    the DIE's type field.  */
15312
15313 static struct type *
15314 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
15315 {
15316   struct type *domain_type, *set_type;
15317   struct attribute *attr;
15318
15319   domain_type = die_type (die, cu);
15320
15321   /* The die_type call above may have already set the type for this DIE.  */
15322   set_type = get_die_type (die, cu);
15323   if (set_type)
15324     return set_type;
15325
15326   set_type = create_set_type (NULL, domain_type);
15327
15328   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15329   if (attr)
15330     TYPE_LENGTH (set_type) = DW_UNSND (attr);
15331
15332   return set_die_type (die, set_type, cu);
15333 }
15334
15335 /* A helper for read_common_block that creates a locexpr baton.
15336    SYM is the symbol which we are marking as computed.
15337    COMMON_DIE is the DIE for the common block.
15338    COMMON_LOC is the location expression attribute for the common
15339    block itself.
15340    MEMBER_LOC is the location expression attribute for the particular
15341    member of the common block that we are processing.
15342    CU is the CU from which the above come.  */
15343
15344 static void
15345 mark_common_block_symbol_computed (struct symbol *sym,
15346                                    struct die_info *common_die,
15347                                    struct attribute *common_loc,
15348                                    struct attribute *member_loc,
15349                                    struct dwarf2_cu *cu)
15350 {
15351   struct objfile *objfile = dwarf2_per_objfile->objfile;
15352   struct dwarf2_locexpr_baton *baton;
15353   gdb_byte *ptr;
15354   unsigned int cu_off;
15355   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
15356   LONGEST offset = 0;
15357
15358   gdb_assert (common_loc && member_loc);
15359   gdb_assert (attr_form_is_block (common_loc));
15360   gdb_assert (attr_form_is_block (member_loc)
15361               || attr_form_is_constant (member_loc));
15362
15363   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
15364   baton->per_cu = cu->per_cu;
15365   gdb_assert (baton->per_cu);
15366
15367   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
15368
15369   if (attr_form_is_constant (member_loc))
15370     {
15371       offset = dwarf2_get_attr_constant_value (member_loc, 0);
15372       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
15373     }
15374   else
15375     baton->size += DW_BLOCK (member_loc)->size;
15376
15377   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
15378   baton->data = ptr;
15379
15380   *ptr++ = DW_OP_call4;
15381   cu_off = common_die->sect_off - cu->per_cu->sect_off;
15382   store_unsigned_integer (ptr, 4, byte_order, cu_off);
15383   ptr += 4;
15384
15385   if (attr_form_is_constant (member_loc))
15386     {
15387       *ptr++ = DW_OP_addr;
15388       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
15389       ptr += cu->header.addr_size;
15390     }
15391   else
15392     {
15393       /* We have to copy the data here, because DW_OP_call4 will only
15394          use a DW_AT_location attribute.  */
15395       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
15396       ptr += DW_BLOCK (member_loc)->size;
15397     }
15398
15399   *ptr++ = DW_OP_plus;
15400   gdb_assert (ptr - baton->data == baton->size);
15401
15402   SYMBOL_LOCATION_BATON (sym) = baton;
15403   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
15404 }
15405
15406 /* Create appropriate locally-scoped variables for all the
15407    DW_TAG_common_block entries.  Also create a struct common_block
15408    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
15409    is used to sepate the common blocks name namespace from regular
15410    variable names.  */
15411
15412 static void
15413 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
15414 {
15415   struct attribute *attr;
15416
15417   attr = dwarf2_attr (die, DW_AT_location, cu);
15418   if (attr)
15419     {
15420       /* Support the .debug_loc offsets.  */
15421       if (attr_form_is_block (attr))
15422         {
15423           /* Ok.  */
15424         }
15425       else if (attr_form_is_section_offset (attr))
15426         {
15427           dwarf2_complex_location_expr_complaint ();
15428           attr = NULL;
15429         }
15430       else
15431         {
15432           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15433                                                  "common block member");
15434           attr = NULL;
15435         }
15436     }
15437
15438   if (die->child != NULL)
15439     {
15440       struct objfile *objfile = cu->objfile;
15441       struct die_info *child_die;
15442       size_t n_entries = 0, size;
15443       struct common_block *common_block;
15444       struct symbol *sym;
15445
15446       for (child_die = die->child;
15447            child_die && child_die->tag;
15448            child_die = sibling_die (child_die))
15449         ++n_entries;
15450
15451       size = (sizeof (struct common_block)
15452               + (n_entries - 1) * sizeof (struct symbol *));
15453       common_block
15454         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
15455                                                  size);
15456       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
15457       common_block->n_entries = 0;
15458
15459       for (child_die = die->child;
15460            child_die && child_die->tag;
15461            child_die = sibling_die (child_die))
15462         {
15463           /* Create the symbol in the DW_TAG_common_block block in the current
15464              symbol scope.  */
15465           sym = new_symbol (child_die, NULL, cu);
15466           if (sym != NULL)
15467             {
15468               struct attribute *member_loc;
15469
15470               common_block->contents[common_block->n_entries++] = sym;
15471
15472               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
15473                                         cu);
15474               if (member_loc)
15475                 {
15476                   /* GDB has handled this for a long time, but it is
15477                      not specified by DWARF.  It seems to have been
15478                      emitted by gfortran at least as recently as:
15479                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
15480                   complaint (&symfile_complaints,
15481                              _("Variable in common block has "
15482                                "DW_AT_data_member_location "
15483                                "- DIE at 0x%x [in module %s]"),
15484                              to_underlying (child_die->sect_off),
15485                              objfile_name (cu->objfile));
15486
15487                   if (attr_form_is_section_offset (member_loc))
15488                     dwarf2_complex_location_expr_complaint ();
15489                   else if (attr_form_is_constant (member_loc)
15490                            || attr_form_is_block (member_loc))
15491                     {
15492                       if (attr)
15493                         mark_common_block_symbol_computed (sym, die, attr,
15494                                                            member_loc, cu);
15495                     }
15496                   else
15497                     dwarf2_complex_location_expr_complaint ();
15498                 }
15499             }
15500         }
15501
15502       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
15503       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
15504     }
15505 }
15506
15507 /* Create a type for a C++ namespace.  */
15508
15509 static struct type *
15510 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
15511 {
15512   struct objfile *objfile = cu->objfile;
15513   const char *previous_prefix, *name;
15514   int is_anonymous;
15515   struct type *type;
15516
15517   /* For extensions, reuse the type of the original namespace.  */
15518   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
15519     {
15520       struct die_info *ext_die;
15521       struct dwarf2_cu *ext_cu = cu;
15522
15523       ext_die = dwarf2_extension (die, &ext_cu);
15524       type = read_type_die (ext_die, ext_cu);
15525
15526       /* EXT_CU may not be the same as CU.
15527          Ensure TYPE is recorded with CU in die_type_hash.  */
15528       return set_die_type (die, type, cu);
15529     }
15530
15531   name = namespace_name (die, &is_anonymous, cu);
15532
15533   /* Now build the name of the current namespace.  */
15534
15535   previous_prefix = determine_prefix (die, cu);
15536   if (previous_prefix[0] != '\0')
15537     name = typename_concat (&objfile->objfile_obstack,
15538                             previous_prefix, name, 0, cu);
15539
15540   /* Create the type.  */
15541   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
15542   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15543
15544   return set_die_type (die, type, cu);
15545 }
15546
15547 /* Read a namespace scope.  */
15548
15549 static void
15550 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
15551 {
15552   struct objfile *objfile = cu->objfile;
15553   int is_anonymous;
15554
15555   /* Add a symbol associated to this if we haven't seen the namespace
15556      before.  Also, add a using directive if it's an anonymous
15557      namespace.  */
15558
15559   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
15560     {
15561       struct type *type;
15562
15563       type = read_type_die (die, cu);
15564       new_symbol (die, type, cu);
15565
15566       namespace_name (die, &is_anonymous, cu);
15567       if (is_anonymous)
15568         {
15569           const char *previous_prefix = determine_prefix (die, cu);
15570
15571           std::vector<const char *> excludes;
15572           add_using_directive (using_directives (cu->language),
15573                                previous_prefix, TYPE_NAME (type), NULL,
15574                                NULL, excludes, 0, &objfile->objfile_obstack);
15575         }
15576     }
15577
15578   if (die->child != NULL)
15579     {
15580       struct die_info *child_die = die->child;
15581
15582       while (child_die && child_die->tag)
15583         {
15584           process_die (child_die, cu);
15585           child_die = sibling_die (child_die);
15586         }
15587     }
15588 }
15589
15590 /* Read a Fortran module as type.  This DIE can be only a declaration used for
15591    imported module.  Still we need that type as local Fortran "use ... only"
15592    declaration imports depend on the created type in determine_prefix.  */
15593
15594 static struct type *
15595 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
15596 {
15597   struct objfile *objfile = cu->objfile;
15598   const char *module_name;
15599   struct type *type;
15600
15601   module_name = dwarf2_name (die, cu);
15602   if (!module_name)
15603     complaint (&symfile_complaints,
15604                _("DW_TAG_module has no name, offset 0x%x"),
15605                to_underlying (die->sect_off));
15606   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
15607
15608   /* determine_prefix uses TYPE_TAG_NAME.  */
15609   TYPE_TAG_NAME (type) = TYPE_NAME (type);
15610
15611   return set_die_type (die, type, cu);
15612 }
15613
15614 /* Read a Fortran module.  */
15615
15616 static void
15617 read_module (struct die_info *die, struct dwarf2_cu *cu)
15618 {
15619   struct die_info *child_die = die->child;
15620   struct type *type;
15621
15622   type = read_type_die (die, cu);
15623   new_symbol (die, type, cu);
15624
15625   while (child_die && child_die->tag)
15626     {
15627       process_die (child_die, cu);
15628       child_die = sibling_die (child_die);
15629     }
15630 }
15631
15632 /* Return the name of the namespace represented by DIE.  Set
15633    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
15634    namespace.  */
15635
15636 static const char *
15637 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
15638 {
15639   struct die_info *current_die;
15640   const char *name = NULL;
15641
15642   /* Loop through the extensions until we find a name.  */
15643
15644   for (current_die = die;
15645        current_die != NULL;
15646        current_die = dwarf2_extension (die, &cu))
15647     {
15648       /* We don't use dwarf2_name here so that we can detect the absence
15649          of a name -> anonymous namespace.  */
15650       name = dwarf2_string_attr (die, DW_AT_name, cu);
15651
15652       if (name != NULL)
15653         break;
15654     }
15655
15656   /* Is it an anonymous namespace?  */
15657
15658   *is_anonymous = (name == NULL);
15659   if (*is_anonymous)
15660     name = CP_ANONYMOUS_NAMESPACE_STR;
15661
15662   return name;
15663 }
15664
15665 /* Extract all information from a DW_TAG_pointer_type DIE and add to
15666    the user defined type vector.  */
15667
15668 static struct type *
15669 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
15670 {
15671   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
15672   struct comp_unit_head *cu_header = &cu->header;
15673   struct type *type;
15674   struct attribute *attr_byte_size;
15675   struct attribute *attr_address_class;
15676   int byte_size, addr_class;
15677   struct type *target_type;
15678
15679   target_type = die_type (die, cu);
15680
15681   /* The die_type call above may have already set the type for this DIE.  */
15682   type = get_die_type (die, cu);
15683   if (type)
15684     return type;
15685
15686   type = lookup_pointer_type (target_type);
15687
15688   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
15689   if (attr_byte_size)
15690     byte_size = DW_UNSND (attr_byte_size);
15691   else
15692     byte_size = cu_header->addr_size;
15693
15694   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
15695   if (attr_address_class)
15696     addr_class = DW_UNSND (attr_address_class);
15697   else
15698     addr_class = DW_ADDR_none;
15699
15700   /* If the pointer size or address class is different than the
15701      default, create a type variant marked as such and set the
15702      length accordingly.  */
15703   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15704     {
15705       if (gdbarch_address_class_type_flags_p (gdbarch))
15706         {
15707           int type_flags;
15708
15709           type_flags = gdbarch_address_class_type_flags
15710                          (gdbarch, byte_size, addr_class);
15711           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15712                       == 0);
15713           type = make_type_with_address_space (type, type_flags);
15714         }
15715       else if (TYPE_LENGTH (type) != byte_size)
15716         {
15717           complaint (&symfile_complaints,
15718                      _("invalid pointer size %d"), byte_size);
15719         }
15720       else
15721         {
15722           /* Should we also complain about unhandled address classes?  */
15723         }
15724     }
15725
15726   TYPE_LENGTH (type) = byte_size;
15727   return set_die_type (die, type, cu);
15728 }
15729
15730 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15731    the user defined type vector.  */
15732
15733 static struct type *
15734 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15735 {
15736   struct type *type;
15737   struct type *to_type;
15738   struct type *domain;
15739
15740   to_type = die_type (die, cu);
15741   domain = die_containing_type (die, cu);
15742
15743   /* The calls above may have already set the type for this DIE.  */
15744   type = get_die_type (die, cu);
15745   if (type)
15746     return type;
15747
15748   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15749     type = lookup_methodptr_type (to_type);
15750   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15751     {
15752       struct type *new_type = alloc_type (cu->objfile);
15753
15754       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15755                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15756                             TYPE_VARARGS (to_type));
15757       type = lookup_methodptr_type (new_type);
15758     }
15759   else
15760     type = lookup_memberptr_type (to_type, domain);
15761
15762   return set_die_type (die, type, cu);
15763 }
15764
15765 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15766    the user defined type vector.  */
15767
15768 static struct type *
15769 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15770                           enum type_code refcode)
15771 {
15772   struct comp_unit_head *cu_header = &cu->header;
15773   struct type *type, *target_type;
15774   struct attribute *attr;
15775
15776   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15777
15778   target_type = die_type (die, cu);
15779
15780   /* The die_type call above may have already set the type for this DIE.  */
15781   type = get_die_type (die, cu);
15782   if (type)
15783     return type;
15784
15785   type = lookup_reference_type (target_type, refcode);
15786   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15787   if (attr)
15788     {
15789       TYPE_LENGTH (type) = DW_UNSND (attr);
15790     }
15791   else
15792     {
15793       TYPE_LENGTH (type) = cu_header->addr_size;
15794     }
15795   return set_die_type (die, type, cu);
15796 }
15797
15798 /* Add the given cv-qualifiers to the element type of the array.  GCC
15799    outputs DWARF type qualifiers that apply to an array, not the
15800    element type.  But GDB relies on the array element type to carry
15801    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15802    specification.  */
15803
15804 static struct type *
15805 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15806                    struct type *base_type, int cnst, int voltl)
15807 {
15808   struct type *el_type, *inner_array;
15809
15810   base_type = copy_type (base_type);
15811   inner_array = base_type;
15812
15813   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15814     {
15815       TYPE_TARGET_TYPE (inner_array) =
15816         copy_type (TYPE_TARGET_TYPE (inner_array));
15817       inner_array = TYPE_TARGET_TYPE (inner_array);
15818     }
15819
15820   el_type = TYPE_TARGET_TYPE (inner_array);
15821   cnst |= TYPE_CONST (el_type);
15822   voltl |= TYPE_VOLATILE (el_type);
15823   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15824
15825   return set_die_type (die, base_type, cu);
15826 }
15827
15828 static struct type *
15829 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15830 {
15831   struct type *base_type, *cv_type;
15832
15833   base_type = die_type (die, cu);
15834
15835   /* The die_type call above may have already set the type for this DIE.  */
15836   cv_type = get_die_type (die, cu);
15837   if (cv_type)
15838     return cv_type;
15839
15840   /* In case the const qualifier is applied to an array type, the element type
15841      is so qualified, not the array type (section 6.7.3 of C99).  */
15842   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15843     return add_array_cv_type (die, cu, base_type, 1, 0);
15844
15845   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15846   return set_die_type (die, cv_type, cu);
15847 }
15848
15849 static struct type *
15850 read_tag_volatile_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   /* In case the volatile qualifier is applied to an array type, the
15862      element type is so qualified, not the array type (section 6.7.3
15863      of C99).  */
15864   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15865     return add_array_cv_type (die, cu, base_type, 0, 1);
15866
15867   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15868   return set_die_type (die, cv_type, cu);
15869 }
15870
15871 /* Handle DW_TAG_restrict_type.  */
15872
15873 static struct type *
15874 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15875 {
15876   struct type *base_type, *cv_type;
15877
15878   base_type = die_type (die, cu);
15879
15880   /* The die_type call above may have already set the type for this DIE.  */
15881   cv_type = get_die_type (die, cu);
15882   if (cv_type)
15883     return cv_type;
15884
15885   cv_type = make_restrict_type (base_type);
15886   return set_die_type (die, cv_type, cu);
15887 }
15888
15889 /* Handle DW_TAG_atomic_type.  */
15890
15891 static struct type *
15892 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15893 {
15894   struct type *base_type, *cv_type;
15895
15896   base_type = die_type (die, cu);
15897
15898   /* The die_type call above may have already set the type for this DIE.  */
15899   cv_type = get_die_type (die, cu);
15900   if (cv_type)
15901     return cv_type;
15902
15903   cv_type = make_atomic_type (base_type);
15904   return set_die_type (die, cv_type, cu);
15905 }
15906
15907 /* Extract all information from a DW_TAG_string_type DIE and add to
15908    the user defined type vector.  It isn't really a user defined type,
15909    but it behaves like one, with other DIE's using an AT_user_def_type
15910    attribute to reference it.  */
15911
15912 static struct type *
15913 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15914 {
15915   struct objfile *objfile = cu->objfile;
15916   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15917   struct type *type, *range_type, *index_type, *char_type;
15918   struct attribute *attr;
15919   unsigned int length;
15920
15921   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15922   if (attr)
15923     {
15924       length = DW_UNSND (attr);
15925     }
15926   else
15927     {
15928       /* Check for the DW_AT_byte_size attribute.  */
15929       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15930       if (attr)
15931         {
15932           length = DW_UNSND (attr);
15933         }
15934       else
15935         {
15936           length = 1;
15937         }
15938     }
15939
15940   index_type = objfile_type (objfile)->builtin_int;
15941   range_type = create_static_range_type (NULL, index_type, 1, length);
15942   char_type = language_string_char_type (cu->language_defn, gdbarch);
15943   type = create_string_type (NULL, char_type, range_type);
15944
15945   return set_die_type (die, type, cu);
15946 }
15947
15948 /* Assuming that DIE corresponds to a function, returns nonzero
15949    if the function is prototyped.  */
15950
15951 static int
15952 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15953 {
15954   struct attribute *attr;
15955
15956   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15957   if (attr && (DW_UNSND (attr) != 0))
15958     return 1;
15959
15960   /* The DWARF standard implies that the DW_AT_prototyped attribute
15961      is only meaninful for C, but the concept also extends to other
15962      languages that allow unprototyped functions (Eg: Objective C).
15963      For all other languages, assume that functions are always
15964      prototyped.  */
15965   if (cu->language != language_c
15966       && cu->language != language_objc
15967       && cu->language != language_opencl)
15968     return 1;
15969
15970   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15971      prototyped and unprototyped functions; default to prototyped,
15972      since that is more common in modern code (and RealView warns
15973      about unprototyped functions).  */
15974   if (producer_is_realview (cu->producer))
15975     return 1;
15976
15977   return 0;
15978 }
15979
15980 /* Handle DIES due to C code like:
15981
15982    struct foo
15983    {
15984    int (*funcp)(int a, long l);
15985    int b;
15986    };
15987
15988    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15989
15990 static struct type *
15991 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15992 {
15993   struct objfile *objfile = cu->objfile;
15994   struct type *type;            /* Type that this function returns.  */
15995   struct type *ftype;           /* Function that returns above type.  */
15996   struct attribute *attr;
15997
15998   type = die_type (die, cu);
15999
16000   /* The die_type call above may have already set the type for this DIE.  */
16001   ftype = get_die_type (die, cu);
16002   if (ftype)
16003     return ftype;
16004
16005   ftype = lookup_function_type (type);
16006
16007   if (prototyped_function_p (die, cu))
16008     TYPE_PROTOTYPED (ftype) = 1;
16009
16010   /* Store the calling convention in the type if it's available in
16011      the subroutine die.  Otherwise set the calling convention to
16012      the default value DW_CC_normal.  */
16013   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
16014   if (attr)
16015     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
16016   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
16017     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
16018   else
16019     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
16020
16021   /* Record whether the function returns normally to its caller or not
16022      if the DWARF producer set that information.  */
16023   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
16024   if (attr && (DW_UNSND (attr) != 0))
16025     TYPE_NO_RETURN (ftype) = 1;
16026
16027   /* We need to add the subroutine type to the die immediately so
16028      we don't infinitely recurse when dealing with parameters
16029      declared as the same subroutine type.  */
16030   set_die_type (die, ftype, cu);
16031
16032   if (die->child != NULL)
16033     {
16034       struct type *void_type = objfile_type (objfile)->builtin_void;
16035       struct die_info *child_die;
16036       int nparams, iparams;
16037
16038       /* Count the number of parameters.
16039          FIXME: GDB currently ignores vararg functions, but knows about
16040          vararg member functions.  */
16041       nparams = 0;
16042       child_die = die->child;
16043       while (child_die && child_die->tag)
16044         {
16045           if (child_die->tag == DW_TAG_formal_parameter)
16046             nparams++;
16047           else if (child_die->tag == DW_TAG_unspecified_parameters)
16048             TYPE_VARARGS (ftype) = 1;
16049           child_die = sibling_die (child_die);
16050         }
16051
16052       /* Allocate storage for parameters and fill them in.  */
16053       TYPE_NFIELDS (ftype) = nparams;
16054       TYPE_FIELDS (ftype) = (struct field *)
16055         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
16056
16057       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
16058          even if we error out during the parameters reading below.  */
16059       for (iparams = 0; iparams < nparams; iparams++)
16060         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
16061
16062       iparams = 0;
16063       child_die = die->child;
16064       while (child_die && child_die->tag)
16065         {
16066           if (child_die->tag == DW_TAG_formal_parameter)
16067             {
16068               struct type *arg_type;
16069
16070               /* DWARF version 2 has no clean way to discern C++
16071                  static and non-static member functions.  G++ helps
16072                  GDB by marking the first parameter for non-static
16073                  member functions (which is the this pointer) as
16074                  artificial.  We pass this information to
16075                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
16076
16077                  DWARF version 3 added DW_AT_object_pointer, which GCC
16078                  4.5 does not yet generate.  */
16079               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
16080               if (attr)
16081                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
16082               else
16083                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
16084               arg_type = die_type (child_die, cu);
16085
16086               /* RealView does not mark THIS as const, which the testsuite
16087                  expects.  GCC marks THIS as const in method definitions,
16088                  but not in the class specifications (GCC PR 43053).  */
16089               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
16090                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
16091                 {
16092                   int is_this = 0;
16093                   struct dwarf2_cu *arg_cu = cu;
16094                   const char *name = dwarf2_name (child_die, cu);
16095
16096                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
16097                   if (attr)
16098                     {
16099                       /* If the compiler emits this, use it.  */
16100                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
16101                         is_this = 1;
16102                     }
16103                   else if (name && strcmp (name, "this") == 0)
16104                     /* Function definitions will have the argument names.  */
16105                     is_this = 1;
16106                   else if (name == NULL && iparams == 0)
16107                     /* Declarations may not have the names, so like
16108                        elsewhere in GDB, assume an artificial first
16109                        argument is "this".  */
16110                     is_this = 1;
16111
16112                   if (is_this)
16113                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
16114                                              arg_type, 0);
16115                 }
16116
16117               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
16118               iparams++;
16119             }
16120           child_die = sibling_die (child_die);
16121         }
16122     }
16123
16124   return ftype;
16125 }
16126
16127 static struct type *
16128 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
16129 {
16130   struct objfile *objfile = cu->objfile;
16131   const char *name = NULL;
16132   struct type *this_type, *target_type;
16133
16134   name = dwarf2_full_name (NULL, die, cu);
16135   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
16136   TYPE_TARGET_STUB (this_type) = 1;
16137   set_die_type (die, this_type, cu);
16138   target_type = die_type (die, cu);
16139   if (target_type != this_type)
16140     TYPE_TARGET_TYPE (this_type) = target_type;
16141   else
16142     {
16143       /* Self-referential typedefs are, it seems, not allowed by the DWARF
16144          spec and cause infinite loops in GDB.  */
16145       complaint (&symfile_complaints,
16146                  _("Self-referential DW_TAG_typedef "
16147                    "- DIE at 0x%x [in module %s]"),
16148                  to_underlying (die->sect_off), objfile_name (objfile));
16149       TYPE_TARGET_TYPE (this_type) = NULL;
16150     }
16151   return this_type;
16152 }
16153
16154 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
16155    (which may be different from NAME) to the architecture back-end to allow
16156    it to guess the correct format if necessary.  */
16157
16158 static struct type *
16159 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
16160                         const char *name_hint)
16161 {
16162   struct gdbarch *gdbarch = get_objfile_arch (objfile);
16163   const struct floatformat **format;
16164   struct type *type;
16165
16166   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
16167   if (format)
16168     type = init_float_type (objfile, bits, name, format);
16169   else
16170     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16171
16172   return type;
16173 }
16174
16175 /* Find a representation of a given base type and install
16176    it in the TYPE field of the die.  */
16177
16178 static struct type *
16179 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
16180 {
16181   struct objfile *objfile = cu->objfile;
16182   struct type *type;
16183   struct attribute *attr;
16184   int encoding = 0, bits = 0;
16185   const char *name;
16186
16187   attr = dwarf2_attr (die, DW_AT_encoding, cu);
16188   if (attr)
16189     {
16190       encoding = DW_UNSND (attr);
16191     }
16192   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16193   if (attr)
16194     {
16195       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
16196     }
16197   name = dwarf2_name (die, cu);
16198   if (!name)
16199     {
16200       complaint (&symfile_complaints,
16201                  _("DW_AT_name missing from DW_TAG_base_type"));
16202     }
16203
16204   switch (encoding)
16205     {
16206       case DW_ATE_address:
16207         /* Turn DW_ATE_address into a void * pointer.  */
16208         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
16209         type = init_pointer_type (objfile, bits, name, type);
16210         break;
16211       case DW_ATE_boolean:
16212         type = init_boolean_type (objfile, bits, 1, name);
16213         break;
16214       case DW_ATE_complex_float:
16215         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
16216         type = init_complex_type (objfile, name, type);
16217         break;
16218       case DW_ATE_decimal_float:
16219         type = init_decfloat_type (objfile, bits, name);
16220         break;
16221       case DW_ATE_float:
16222         type = dwarf2_init_float_type (objfile, bits, name, name);
16223         break;
16224       case DW_ATE_signed:
16225         type = init_integer_type (objfile, bits, 0, name);
16226         break;
16227       case DW_ATE_unsigned:
16228         if (cu->language == language_fortran
16229             && name
16230             && startswith (name, "character("))
16231           type = init_character_type (objfile, bits, 1, name);
16232         else
16233           type = init_integer_type (objfile, bits, 1, name);
16234         break;
16235       case DW_ATE_signed_char:
16236         if (cu->language == language_ada || cu->language == language_m2
16237             || cu->language == language_pascal
16238             || cu->language == language_fortran)
16239           type = init_character_type (objfile, bits, 0, name);
16240         else
16241           type = init_integer_type (objfile, bits, 0, name);
16242         break;
16243       case DW_ATE_unsigned_char:
16244         if (cu->language == language_ada || cu->language == language_m2
16245             || cu->language == language_pascal
16246             || cu->language == language_fortran
16247             || cu->language == language_rust)
16248           type = init_character_type (objfile, bits, 1, name);
16249         else
16250           type = init_integer_type (objfile, bits, 1, name);
16251         break;
16252       case DW_ATE_UTF:
16253         {
16254           gdbarch *arch = get_objfile_arch (objfile);
16255
16256           if (bits == 16)
16257             type = builtin_type (arch)->builtin_char16;
16258           else if (bits == 32)
16259             type = builtin_type (arch)->builtin_char32;
16260           else
16261             {
16262               complaint (&symfile_complaints,
16263                          _("unsupported DW_ATE_UTF bit size: '%d'"),
16264                          bits);
16265               type = init_integer_type (objfile, bits, 1, name);
16266             }
16267           return set_die_type (die, type, cu);
16268         }
16269         break;
16270
16271       default:
16272         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
16273                    dwarf_type_encoding_name (encoding));
16274         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
16275         break;
16276     }
16277
16278   if (name && strcmp (name, "char") == 0)
16279     TYPE_NOSIGN (type) = 1;
16280
16281   return set_die_type (die, type, cu);
16282 }
16283
16284 /* Parse dwarf attribute if it's a block, reference or constant and put the
16285    resulting value of the attribute into struct bound_prop.
16286    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
16287
16288 static int
16289 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
16290                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
16291 {
16292   struct dwarf2_property_baton *baton;
16293   struct obstack *obstack = &cu->objfile->objfile_obstack;
16294
16295   if (attr == NULL || prop == NULL)
16296     return 0;
16297
16298   if (attr_form_is_block (attr))
16299     {
16300       baton = XOBNEW (obstack, struct dwarf2_property_baton);
16301       baton->referenced_type = NULL;
16302       baton->locexpr.per_cu = cu->per_cu;
16303       baton->locexpr.size = DW_BLOCK (attr)->size;
16304       baton->locexpr.data = DW_BLOCK (attr)->data;
16305       prop->data.baton = baton;
16306       prop->kind = PROP_LOCEXPR;
16307       gdb_assert (prop->data.baton != NULL);
16308     }
16309   else if (attr_form_is_ref (attr))
16310     {
16311       struct dwarf2_cu *target_cu = cu;
16312       struct die_info *target_die;
16313       struct attribute *target_attr;
16314
16315       target_die = follow_die_ref (die, attr, &target_cu);
16316       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
16317       if (target_attr == NULL)
16318         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
16319                                    target_cu);
16320       if (target_attr == NULL)
16321         return 0;
16322
16323       switch (target_attr->name)
16324         {
16325           case DW_AT_location:
16326             if (attr_form_is_section_offset (target_attr))
16327               {
16328                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16329                 baton->referenced_type = die_type (target_die, target_cu);
16330                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
16331                 prop->data.baton = baton;
16332                 prop->kind = PROP_LOCLIST;
16333                 gdb_assert (prop->data.baton != NULL);
16334               }
16335             else if (attr_form_is_block (target_attr))
16336               {
16337                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
16338                 baton->referenced_type = die_type (target_die, target_cu);
16339                 baton->locexpr.per_cu = cu->per_cu;
16340                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
16341                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
16342                 prop->data.baton = baton;
16343                 prop->kind = PROP_LOCEXPR;
16344                 gdb_assert (prop->data.baton != NULL);
16345               }
16346             else
16347               {
16348                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16349                                                        "dynamic property");
16350                 return 0;
16351               }
16352             break;
16353           case DW_AT_data_member_location:
16354             {
16355               LONGEST offset;
16356
16357               if (!handle_data_member_location (target_die, target_cu,
16358                                                 &offset))
16359                 return 0;
16360
16361               baton = XOBNEW (obstack, struct dwarf2_property_baton);
16362               baton->referenced_type = read_type_die (target_die->parent,
16363                                                       target_cu);
16364               baton->offset_info.offset = offset;
16365               baton->offset_info.type = die_type (target_die, target_cu);
16366               prop->data.baton = baton;
16367               prop->kind = PROP_ADDR_OFFSET;
16368               break;
16369             }
16370         }
16371     }
16372   else if (attr_form_is_constant (attr))
16373     {
16374       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
16375       prop->kind = PROP_CONST;
16376     }
16377   else
16378     {
16379       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
16380                                              dwarf2_name (die, cu));
16381       return 0;
16382     }
16383
16384   return 1;
16385 }
16386
16387 /* Read the given DW_AT_subrange DIE.  */
16388
16389 static struct type *
16390 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
16391 {
16392   struct type *base_type, *orig_base_type;
16393   struct type *range_type;
16394   struct attribute *attr;
16395   struct dynamic_prop low, high;
16396   int low_default_is_valid;
16397   int high_bound_is_count = 0;
16398   const char *name;
16399   LONGEST negative_mask;
16400
16401   orig_base_type = die_type (die, cu);
16402   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
16403      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
16404      creating the range type, but we use the result of check_typedef
16405      when examining properties of the type.  */
16406   base_type = check_typedef (orig_base_type);
16407
16408   /* The die_type call above may have already set the type for this DIE.  */
16409   range_type = get_die_type (die, cu);
16410   if (range_type)
16411     return range_type;
16412
16413   low.kind = PROP_CONST;
16414   high.kind = PROP_CONST;
16415   high.data.const_val = 0;
16416
16417   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
16418      omitting DW_AT_lower_bound.  */
16419   switch (cu->language)
16420     {
16421     case language_c:
16422     case language_cplus:
16423       low.data.const_val = 0;
16424       low_default_is_valid = 1;
16425       break;
16426     case language_fortran:
16427       low.data.const_val = 1;
16428       low_default_is_valid = 1;
16429       break;
16430     case language_d:
16431     case language_objc:
16432     case language_rust:
16433       low.data.const_val = 0;
16434       low_default_is_valid = (cu->header.version >= 4);
16435       break;
16436     case language_ada:
16437     case language_m2:
16438     case language_pascal:
16439       low.data.const_val = 1;
16440       low_default_is_valid = (cu->header.version >= 4);
16441       break;
16442     default:
16443       low.data.const_val = 0;
16444       low_default_is_valid = 0;
16445       break;
16446     }
16447
16448   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
16449   if (attr)
16450     attr_to_dynamic_prop (attr, die, cu, &low);
16451   else if (!low_default_is_valid)
16452     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
16453                                       "- DIE at 0x%x [in module %s]"),
16454                to_underlying (die->sect_off), objfile_name (cu->objfile));
16455
16456   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
16457   if (!attr_to_dynamic_prop (attr, die, cu, &high))
16458     {
16459       attr = dwarf2_attr (die, DW_AT_count, cu);
16460       if (attr_to_dynamic_prop (attr, die, cu, &high))
16461         {
16462           /* If bounds are constant do the final calculation here.  */
16463           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
16464             high.data.const_val = low.data.const_val + high.data.const_val - 1;
16465           else
16466             high_bound_is_count = 1;
16467         }
16468     }
16469
16470   /* Dwarf-2 specifications explicitly allows to create subrange types
16471      without specifying a base type.
16472      In that case, the base type must be set to the type of
16473      the lower bound, upper bound or count, in that order, if any of these
16474      three attributes references an object that has a type.
16475      If no base type is found, the Dwarf-2 specifications say that
16476      a signed integer type of size equal to the size of an address should
16477      be used.
16478      For the following C code: `extern char gdb_int [];'
16479      GCC produces an empty range DIE.
16480      FIXME: muller/2010-05-28: Possible references to object for low bound,
16481      high bound or count are not yet handled by this code.  */
16482   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
16483     {
16484       struct objfile *objfile = cu->objfile;
16485       struct gdbarch *gdbarch = get_objfile_arch (objfile);
16486       int addr_size = gdbarch_addr_bit (gdbarch) /8;
16487       struct type *int_type = objfile_type (objfile)->builtin_int;
16488
16489       /* Test "int", "long int", and "long long int" objfile types,
16490          and select the first one having a size above or equal to the
16491          architecture address size.  */
16492       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16493         base_type = int_type;
16494       else
16495         {
16496           int_type = objfile_type (objfile)->builtin_long;
16497           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16498             base_type = int_type;
16499           else
16500             {
16501               int_type = objfile_type (objfile)->builtin_long_long;
16502               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
16503                 base_type = int_type;
16504             }
16505         }
16506     }
16507
16508   /* Normally, the DWARF producers are expected to use a signed
16509      constant form (Eg. DW_FORM_sdata) to express negative bounds.
16510      But this is unfortunately not always the case, as witnessed
16511      with GCC, for instance, where the ambiguous DW_FORM_dataN form
16512      is used instead.  To work around that ambiguity, we treat
16513      the bounds as signed, and thus sign-extend their values, when
16514      the base type is signed.  */
16515   negative_mask =
16516     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
16517   if (low.kind == PROP_CONST
16518       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
16519     low.data.const_val |= negative_mask;
16520   if (high.kind == PROP_CONST
16521       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
16522     high.data.const_val |= negative_mask;
16523
16524   range_type = create_range_type (NULL, orig_base_type, &low, &high);
16525
16526   if (high_bound_is_count)
16527     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
16528
16529   /* Ada expects an empty array on no boundary attributes.  */
16530   if (attr == NULL && cu->language != language_ada)
16531     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
16532
16533   name = dwarf2_name (die, cu);
16534   if (name)
16535     TYPE_NAME (range_type) = name;
16536
16537   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
16538   if (attr)
16539     TYPE_LENGTH (range_type) = DW_UNSND (attr);
16540
16541   set_die_type (die, range_type, cu);
16542
16543   /* set_die_type should be already done.  */
16544   set_descriptive_type (range_type, die, cu);
16545
16546   return range_type;
16547 }
16548
16549 static struct type *
16550 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
16551 {
16552   struct type *type;
16553
16554   /* For now, we only support the C meaning of an unspecified type: void.  */
16555
16556   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
16557   TYPE_NAME (type) = dwarf2_name (die, cu);
16558
16559   return set_die_type (die, type, cu);
16560 }
16561
16562 /* Read a single die and all its descendents.  Set the die's sibling
16563    field to NULL; set other fields in the die correctly, and set all
16564    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
16565    location of the info_ptr after reading all of those dies.  PARENT
16566    is the parent of the die in question.  */
16567
16568 static struct die_info *
16569 read_die_and_children (const struct die_reader_specs *reader,
16570                        const gdb_byte *info_ptr,
16571                        const gdb_byte **new_info_ptr,
16572                        struct die_info *parent)
16573 {
16574   struct die_info *die;
16575   const gdb_byte *cur_ptr;
16576   int has_children;
16577
16578   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
16579   if (die == NULL)
16580     {
16581       *new_info_ptr = cur_ptr;
16582       return NULL;
16583     }
16584   store_in_ref_table (die, reader->cu);
16585
16586   if (has_children)
16587     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
16588   else
16589     {
16590       die->child = NULL;
16591       *new_info_ptr = cur_ptr;
16592     }
16593
16594   die->sibling = NULL;
16595   die->parent = parent;
16596   return die;
16597 }
16598
16599 /* Read a die, all of its descendents, and all of its siblings; set
16600    all of the fields of all of the dies correctly.  Arguments are as
16601    in read_die_and_children.  */
16602
16603 static struct die_info *
16604 read_die_and_siblings_1 (const struct die_reader_specs *reader,
16605                          const gdb_byte *info_ptr,
16606                          const gdb_byte **new_info_ptr,
16607                          struct die_info *parent)
16608 {
16609   struct die_info *first_die, *last_sibling;
16610   const gdb_byte *cur_ptr;
16611
16612   cur_ptr = info_ptr;
16613   first_die = last_sibling = NULL;
16614
16615   while (1)
16616     {
16617       struct die_info *die
16618         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
16619
16620       if (die == NULL)
16621         {
16622           *new_info_ptr = cur_ptr;
16623           return first_die;
16624         }
16625
16626       if (!first_die)
16627         first_die = die;
16628       else
16629         last_sibling->sibling = die;
16630
16631       last_sibling = die;
16632     }
16633 }
16634
16635 /* Read a die, all of its descendents, and all of its siblings; set
16636    all of the fields of all of the dies correctly.  Arguments are as
16637    in read_die_and_children.
16638    This the main entry point for reading a DIE and all its children.  */
16639
16640 static struct die_info *
16641 read_die_and_siblings (const struct die_reader_specs *reader,
16642                        const gdb_byte *info_ptr,
16643                        const gdb_byte **new_info_ptr,
16644                        struct die_info *parent)
16645 {
16646   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
16647                                                   new_info_ptr, parent);
16648
16649   if (dwarf_die_debug)
16650     {
16651       fprintf_unfiltered (gdb_stdlog,
16652                           "Read die from %s@0x%x of %s:\n",
16653                           get_section_name (reader->die_section),
16654                           (unsigned) (info_ptr - reader->die_section->buffer),
16655                           bfd_get_filename (reader->abfd));
16656       dump_die (die, dwarf_die_debug);
16657     }
16658
16659   return die;
16660 }
16661
16662 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
16663    attributes.
16664    The caller is responsible for filling in the extra attributes
16665    and updating (*DIEP)->num_attrs.
16666    Set DIEP to point to a newly allocated die with its information,
16667    except for its child, sibling, and parent fields.
16668    Set HAS_CHILDREN to tell whether the die has children or not.  */
16669
16670 static const gdb_byte *
16671 read_full_die_1 (const struct die_reader_specs *reader,
16672                  struct die_info **diep, const gdb_byte *info_ptr,
16673                  int *has_children, int num_extra_attrs)
16674 {
16675   unsigned int abbrev_number, bytes_read, i;
16676   struct abbrev_info *abbrev;
16677   struct die_info *die;
16678   struct dwarf2_cu *cu = reader->cu;
16679   bfd *abfd = reader->abfd;
16680
16681   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
16682   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
16683   info_ptr += bytes_read;
16684   if (!abbrev_number)
16685     {
16686       *diep = NULL;
16687       *has_children = 0;
16688       return info_ptr;
16689     }
16690
16691   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
16692   if (!abbrev)
16693     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
16694            abbrev_number,
16695            bfd_get_filename (abfd));
16696
16697   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16698   die->sect_off = sect_off;
16699   die->tag = abbrev->tag;
16700   die->abbrev = abbrev_number;
16701
16702   /* Make the result usable.
16703      The caller needs to update num_attrs after adding the extra
16704      attributes.  */
16705   die->num_attrs = abbrev->num_attrs;
16706
16707   for (i = 0; i < abbrev->num_attrs; ++i)
16708     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16709                                info_ptr);
16710
16711   *diep = die;
16712   *has_children = abbrev->has_children;
16713   return info_ptr;
16714 }
16715
16716 /* Read a die and all its attributes.
16717    Set DIEP to point to a newly allocated die with its information,
16718    except for its child, sibling, and parent fields.
16719    Set HAS_CHILDREN to tell whether the die has children or not.  */
16720
16721 static const gdb_byte *
16722 read_full_die (const struct die_reader_specs *reader,
16723                struct die_info **diep, const gdb_byte *info_ptr,
16724                int *has_children)
16725 {
16726   const gdb_byte *result;
16727
16728   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16729
16730   if (dwarf_die_debug)
16731     {
16732       fprintf_unfiltered (gdb_stdlog,
16733                           "Read die from %s@0x%x of %s:\n",
16734                           get_section_name (reader->die_section),
16735                           (unsigned) (info_ptr - reader->die_section->buffer),
16736                           bfd_get_filename (reader->abfd));
16737       dump_die (*diep, dwarf_die_debug);
16738     }
16739
16740   return result;
16741 }
16742 \f
16743 /* Abbreviation tables.
16744
16745    In DWARF version 2, the description of the debugging information is
16746    stored in a separate .debug_abbrev section.  Before we read any
16747    dies from a section we read in all abbreviations and install them
16748    in a hash table.  */
16749
16750 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16751
16752 static struct abbrev_info *
16753 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16754 {
16755   struct abbrev_info *abbrev;
16756
16757   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16758   memset (abbrev, 0, sizeof (struct abbrev_info));
16759
16760   return abbrev;
16761 }
16762
16763 /* Add an abbreviation to the table.  */
16764
16765 static void
16766 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16767                          unsigned int abbrev_number,
16768                          struct abbrev_info *abbrev)
16769 {
16770   unsigned int hash_number;
16771
16772   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16773   abbrev->next = abbrev_table->abbrevs[hash_number];
16774   abbrev_table->abbrevs[hash_number] = abbrev;
16775 }
16776
16777 /* Look up an abbrev in the table.
16778    Returns NULL if the abbrev is not found.  */
16779
16780 static struct abbrev_info *
16781 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16782                             unsigned int abbrev_number)
16783 {
16784   unsigned int hash_number;
16785   struct abbrev_info *abbrev;
16786
16787   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16788   abbrev = abbrev_table->abbrevs[hash_number];
16789
16790   while (abbrev)
16791     {
16792       if (abbrev->number == abbrev_number)
16793         return abbrev;
16794       abbrev = abbrev->next;
16795     }
16796   return NULL;
16797 }
16798
16799 /* Read in an abbrev table.  */
16800
16801 static struct abbrev_table *
16802 abbrev_table_read_table (struct dwarf2_section_info *section,
16803                          sect_offset sect_off)
16804 {
16805   struct objfile *objfile = dwarf2_per_objfile->objfile;
16806   bfd *abfd = get_section_bfd_owner (section);
16807   struct abbrev_table *abbrev_table;
16808   const gdb_byte *abbrev_ptr;
16809   struct abbrev_info *cur_abbrev;
16810   unsigned int abbrev_number, bytes_read, abbrev_name;
16811   unsigned int abbrev_form;
16812   struct attr_abbrev *cur_attrs;
16813   unsigned int allocated_attrs;
16814
16815   abbrev_table = XNEW (struct abbrev_table);
16816   abbrev_table->sect_off = sect_off;
16817   obstack_init (&abbrev_table->abbrev_obstack);
16818   abbrev_table->abbrevs =
16819     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16820                ABBREV_HASH_SIZE);
16821   memset (abbrev_table->abbrevs, 0,
16822           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16823
16824   dwarf2_read_section (objfile, section);
16825   abbrev_ptr = section->buffer + to_underlying (sect_off);
16826   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16827   abbrev_ptr += bytes_read;
16828
16829   allocated_attrs = ATTR_ALLOC_CHUNK;
16830   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16831
16832   /* Loop until we reach an abbrev number of 0.  */
16833   while (abbrev_number)
16834     {
16835       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16836
16837       /* read in abbrev header */
16838       cur_abbrev->number = abbrev_number;
16839       cur_abbrev->tag
16840         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16841       abbrev_ptr += bytes_read;
16842       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16843       abbrev_ptr += 1;
16844
16845       /* now read in declarations */
16846       for (;;)
16847         {
16848           LONGEST implicit_const;
16849
16850           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16851           abbrev_ptr += bytes_read;
16852           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16853           abbrev_ptr += bytes_read;
16854           if (abbrev_form == DW_FORM_implicit_const)
16855             {
16856               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16857                                                    &bytes_read);
16858               abbrev_ptr += bytes_read;
16859             }
16860           else
16861             {
16862               /* Initialize it due to a false compiler warning.  */
16863               implicit_const = -1;
16864             }
16865
16866           if (abbrev_name == 0)
16867             break;
16868
16869           if (cur_abbrev->num_attrs == allocated_attrs)
16870             {
16871               allocated_attrs += ATTR_ALLOC_CHUNK;
16872               cur_attrs
16873                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16874             }
16875
16876           cur_attrs[cur_abbrev->num_attrs].name
16877             = (enum dwarf_attribute) abbrev_name;
16878           cur_attrs[cur_abbrev->num_attrs].form
16879             = (enum dwarf_form) abbrev_form;
16880           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16881           ++cur_abbrev->num_attrs;
16882         }
16883
16884       cur_abbrev->attrs =
16885         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16886                    cur_abbrev->num_attrs);
16887       memcpy (cur_abbrev->attrs, cur_attrs,
16888               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16889
16890       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16891
16892       /* Get next abbreviation.
16893          Under Irix6 the abbreviations for a compilation unit are not
16894          always properly terminated with an abbrev number of 0.
16895          Exit loop if we encounter an abbreviation which we have
16896          already read (which means we are about to read the abbreviations
16897          for the next compile unit) or if the end of the abbreviation
16898          table is reached.  */
16899       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16900         break;
16901       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16902       abbrev_ptr += bytes_read;
16903       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16904         break;
16905     }
16906
16907   xfree (cur_attrs);
16908   return abbrev_table;
16909 }
16910
16911 /* Free the resources held by ABBREV_TABLE.  */
16912
16913 static void
16914 abbrev_table_free (struct abbrev_table *abbrev_table)
16915 {
16916   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16917   xfree (abbrev_table);
16918 }
16919
16920 /* Same as abbrev_table_free but as a cleanup.
16921    We pass in a pointer to the pointer to the table so that we can
16922    set the pointer to NULL when we're done.  It also simplifies
16923    build_type_psymtabs_1.  */
16924
16925 static void
16926 abbrev_table_free_cleanup (void *table_ptr)
16927 {
16928   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16929
16930   if (*abbrev_table_ptr != NULL)
16931     abbrev_table_free (*abbrev_table_ptr);
16932   *abbrev_table_ptr = NULL;
16933 }
16934
16935 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16936
16937 static void
16938 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16939                      struct dwarf2_section_info *abbrev_section)
16940 {
16941   cu->abbrev_table =
16942     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16943 }
16944
16945 /* Release the memory used by the abbrev table for a compilation unit.  */
16946
16947 static void
16948 dwarf2_free_abbrev_table (void *ptr_to_cu)
16949 {
16950   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16951
16952   if (cu->abbrev_table != NULL)
16953     abbrev_table_free (cu->abbrev_table);
16954   /* Set this to NULL so that we SEGV if we try to read it later,
16955      and also because free_comp_unit verifies this is NULL.  */
16956   cu->abbrev_table = NULL;
16957 }
16958 \f
16959 /* Returns nonzero if TAG represents a type that we might generate a partial
16960    symbol for.  */
16961
16962 static int
16963 is_type_tag_for_partial (int tag)
16964 {
16965   switch (tag)
16966     {
16967 #if 0
16968     /* Some types that would be reasonable to generate partial symbols for,
16969        that we don't at present.  */
16970     case DW_TAG_array_type:
16971     case DW_TAG_file_type:
16972     case DW_TAG_ptr_to_member_type:
16973     case DW_TAG_set_type:
16974     case DW_TAG_string_type:
16975     case DW_TAG_subroutine_type:
16976 #endif
16977     case DW_TAG_base_type:
16978     case DW_TAG_class_type:
16979     case DW_TAG_interface_type:
16980     case DW_TAG_enumeration_type:
16981     case DW_TAG_structure_type:
16982     case DW_TAG_subrange_type:
16983     case DW_TAG_typedef:
16984     case DW_TAG_union_type:
16985       return 1;
16986     default:
16987       return 0;
16988     }
16989 }
16990
16991 /* Load all DIEs that are interesting for partial symbols into memory.  */
16992
16993 static struct partial_die_info *
16994 load_partial_dies (const struct die_reader_specs *reader,
16995                    const gdb_byte *info_ptr, int building_psymtab)
16996 {
16997   struct dwarf2_cu *cu = reader->cu;
16998   struct objfile *objfile = cu->objfile;
16999   struct partial_die_info *part_die;
17000   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
17001   struct abbrev_info *abbrev;
17002   unsigned int bytes_read;
17003   unsigned int load_all = 0;
17004   int nesting_level = 1;
17005
17006   parent_die = NULL;
17007   last_die = NULL;
17008
17009   gdb_assert (cu->per_cu != NULL);
17010   if (cu->per_cu->load_all_dies)
17011     load_all = 1;
17012
17013   cu->partial_dies
17014     = htab_create_alloc_ex (cu->header.length / 12,
17015                             partial_die_hash,
17016                             partial_die_eq,
17017                             NULL,
17018                             &cu->comp_unit_obstack,
17019                             hashtab_obstack_allocate,
17020                             dummy_obstack_deallocate);
17021
17022   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
17023
17024   while (1)
17025     {
17026       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
17027
17028       /* A NULL abbrev means the end of a series of children.  */
17029       if (abbrev == NULL)
17030         {
17031           if (--nesting_level == 0)
17032             {
17033               /* PART_DIE was probably the last thing allocated on the
17034                  comp_unit_obstack, so we could call obstack_free
17035                  here.  We don't do that because the waste is small,
17036                  and will be cleaned up when we're done with this
17037                  compilation unit.  This way, we're also more robust
17038                  against other users of the comp_unit_obstack.  */
17039               return first_die;
17040             }
17041           info_ptr += bytes_read;
17042           last_die = parent_die;
17043           parent_die = parent_die->die_parent;
17044           continue;
17045         }
17046
17047       /* Check for template arguments.  We never save these; if
17048          they're seen, we just mark the parent, and go on our way.  */
17049       if (parent_die != NULL
17050           && cu->language == language_cplus
17051           && (abbrev->tag == DW_TAG_template_type_param
17052               || abbrev->tag == DW_TAG_template_value_param))
17053         {
17054           parent_die->has_template_arguments = 1;
17055
17056           if (!load_all)
17057             {
17058               /* We don't need a partial DIE for the template argument.  */
17059               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17060               continue;
17061             }
17062         }
17063
17064       /* We only recurse into c++ subprograms looking for template arguments.
17065          Skip their other children.  */
17066       if (!load_all
17067           && cu->language == language_cplus
17068           && parent_die != NULL
17069           && parent_die->tag == DW_TAG_subprogram)
17070         {
17071           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17072           continue;
17073         }
17074
17075       /* Check whether this DIE is interesting enough to save.  Normally
17076          we would not be interested in members here, but there may be
17077          later variables referencing them via DW_AT_specification (for
17078          static members).  */
17079       if (!load_all
17080           && !is_type_tag_for_partial (abbrev->tag)
17081           && abbrev->tag != DW_TAG_constant
17082           && abbrev->tag != DW_TAG_enumerator
17083           && abbrev->tag != DW_TAG_subprogram
17084           && abbrev->tag != DW_TAG_lexical_block
17085           && abbrev->tag != DW_TAG_variable
17086           && abbrev->tag != DW_TAG_namespace
17087           && abbrev->tag != DW_TAG_module
17088           && abbrev->tag != DW_TAG_member
17089           && abbrev->tag != DW_TAG_imported_unit
17090           && abbrev->tag != DW_TAG_imported_declaration)
17091         {
17092           /* Otherwise we skip to the next sibling, if any.  */
17093           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
17094           continue;
17095         }
17096
17097       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
17098                                    info_ptr);
17099
17100       /* This two-pass algorithm for processing partial symbols has a
17101          high cost in cache pressure.  Thus, handle some simple cases
17102          here which cover the majority of C partial symbols.  DIEs
17103          which neither have specification tags in them, nor could have
17104          specification tags elsewhere pointing at them, can simply be
17105          processed and discarded.
17106
17107          This segment is also optional; scan_partial_symbols and
17108          add_partial_symbol will handle these DIEs if we chain
17109          them in normally.  When compilers which do not emit large
17110          quantities of duplicate debug information are more common,
17111          this code can probably be removed.  */
17112
17113       /* Any complete simple types at the top level (pretty much all
17114          of them, for a language without namespaces), can be processed
17115          directly.  */
17116       if (parent_die == NULL
17117           && part_die->has_specification == 0
17118           && part_die->is_declaration == 0
17119           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
17120               || part_die->tag == DW_TAG_base_type
17121               || part_die->tag == DW_TAG_subrange_type))
17122         {
17123           if (building_psymtab && part_die->name != NULL)
17124             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17125                                  VAR_DOMAIN, LOC_TYPEDEF,
17126                                  &objfile->static_psymbols,
17127                                  0, cu->language, objfile);
17128           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17129           continue;
17130         }
17131
17132       /* The exception for DW_TAG_typedef with has_children above is
17133          a workaround of GCC PR debug/47510.  In the case of this complaint
17134          type_name_no_tag_or_error will error on such types later.
17135
17136          GDB skipped children of DW_TAG_typedef by the shortcut above and then
17137          it could not find the child DIEs referenced later, this is checked
17138          above.  In correct DWARF DW_TAG_typedef should have no children.  */
17139
17140       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
17141         complaint (&symfile_complaints,
17142                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
17143                      "- DIE at 0x%x [in module %s]"),
17144                    to_underlying (part_die->sect_off), objfile_name (objfile));
17145
17146       /* If we're at the second level, and we're an enumerator, and
17147          our parent has no specification (meaning possibly lives in a
17148          namespace elsewhere), then we can add the partial symbol now
17149          instead of queueing it.  */
17150       if (part_die->tag == DW_TAG_enumerator
17151           && parent_die != NULL
17152           && parent_die->die_parent == NULL
17153           && parent_die->tag == DW_TAG_enumeration_type
17154           && parent_die->has_specification == 0)
17155         {
17156           if (part_die->name == NULL)
17157             complaint (&symfile_complaints,
17158                        _("malformed enumerator DIE ignored"));
17159           else if (building_psymtab)
17160             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
17161                                  VAR_DOMAIN, LOC_CONST,
17162                                  cu->language == language_cplus
17163                                  ? &objfile->global_psymbols
17164                                  : &objfile->static_psymbols,
17165                                  0, cu->language, objfile);
17166
17167           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
17168           continue;
17169         }
17170
17171       /* We'll save this DIE so link it in.  */
17172       part_die->die_parent = parent_die;
17173       part_die->die_sibling = NULL;
17174       part_die->die_child = NULL;
17175
17176       if (last_die && last_die == parent_die)
17177         last_die->die_child = part_die;
17178       else if (last_die)
17179         last_die->die_sibling = part_die;
17180
17181       last_die = part_die;
17182
17183       if (first_die == NULL)
17184         first_die = part_die;
17185
17186       /* Maybe add the DIE to the hash table.  Not all DIEs that we
17187          find interesting need to be in the hash table, because we
17188          also have the parent/sibling/child chains; only those that we
17189          might refer to by offset later during partial symbol reading.
17190
17191          For now this means things that might have be the target of a
17192          DW_AT_specification, DW_AT_abstract_origin, or
17193          DW_AT_extension.  DW_AT_extension will refer only to
17194          namespaces; DW_AT_abstract_origin refers to functions (and
17195          many things under the function DIE, but we do not recurse
17196          into function DIEs during partial symbol reading) and
17197          possibly variables as well; DW_AT_specification refers to
17198          declarations.  Declarations ought to have the DW_AT_declaration
17199          flag.  It happens that GCC forgets to put it in sometimes, but
17200          only for functions, not for types.
17201
17202          Adding more things than necessary to the hash table is harmless
17203          except for the performance cost.  Adding too few will result in
17204          wasted time in find_partial_die, when we reread the compilation
17205          unit with load_all_dies set.  */
17206
17207       if (load_all
17208           || abbrev->tag == DW_TAG_constant
17209           || abbrev->tag == DW_TAG_subprogram
17210           || abbrev->tag == DW_TAG_variable
17211           || abbrev->tag == DW_TAG_namespace
17212           || part_die->is_declaration)
17213         {
17214           void **slot;
17215
17216           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
17217                                            to_underlying (part_die->sect_off),
17218                                            INSERT);
17219           *slot = part_die;
17220         }
17221
17222       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
17223
17224       /* For some DIEs we want to follow their children (if any).  For C
17225          we have no reason to follow the children of structures; for other
17226          languages we have to, so that we can get at method physnames
17227          to infer fully qualified class names, for DW_AT_specification,
17228          and for C++ template arguments.  For C++, we also look one level
17229          inside functions to find template arguments (if the name of the
17230          function does not already contain the template arguments).
17231
17232          For Ada, we need to scan the children of subprograms and lexical
17233          blocks as well because Ada allows the definition of nested
17234          entities that could be interesting for the debugger, such as
17235          nested subprograms for instance.  */
17236       if (last_die->has_children
17237           && (load_all
17238               || last_die->tag == DW_TAG_namespace
17239               || last_die->tag == DW_TAG_module
17240               || last_die->tag == DW_TAG_enumeration_type
17241               || (cu->language == language_cplus
17242                   && last_die->tag == DW_TAG_subprogram
17243                   && (last_die->name == NULL
17244                       || strchr (last_die->name, '<') == NULL))
17245               || (cu->language != language_c
17246                   && (last_die->tag == DW_TAG_class_type
17247                       || last_die->tag == DW_TAG_interface_type
17248                       || last_die->tag == DW_TAG_structure_type
17249                       || last_die->tag == DW_TAG_union_type))
17250               || (cu->language == language_ada
17251                   && (last_die->tag == DW_TAG_subprogram
17252                       || last_die->tag == DW_TAG_lexical_block))))
17253         {
17254           nesting_level++;
17255           parent_die = last_die;
17256           continue;
17257         }
17258
17259       /* Otherwise we skip to the next sibling, if any.  */
17260       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
17261
17262       /* Back to the top, do it again.  */
17263     }
17264 }
17265
17266 /* Read a minimal amount of information into the minimal die structure.  */
17267
17268 static const gdb_byte *
17269 read_partial_die (const struct die_reader_specs *reader,
17270                   struct partial_die_info *part_die,
17271                   struct abbrev_info *abbrev, unsigned int abbrev_len,
17272                   const gdb_byte *info_ptr)
17273 {
17274   struct dwarf2_cu *cu = reader->cu;
17275   struct objfile *objfile = cu->objfile;
17276   const gdb_byte *buffer = reader->buffer;
17277   unsigned int i;
17278   struct attribute attr;
17279   int has_low_pc_attr = 0;
17280   int has_high_pc_attr = 0;
17281   int high_pc_relative = 0;
17282
17283   memset (part_die, 0, sizeof (struct partial_die_info));
17284
17285   part_die->sect_off = (sect_offset) (info_ptr - buffer);
17286
17287   info_ptr += abbrev_len;
17288
17289   if (abbrev == NULL)
17290     return info_ptr;
17291
17292   part_die->tag = abbrev->tag;
17293   part_die->has_children = abbrev->has_children;
17294
17295   for (i = 0; i < abbrev->num_attrs; ++i)
17296     {
17297       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
17298
17299       /* Store the data if it is of an attribute we want to keep in a
17300          partial symbol table.  */
17301       switch (attr.name)
17302         {
17303         case DW_AT_name:
17304           switch (part_die->tag)
17305             {
17306             case DW_TAG_compile_unit:
17307             case DW_TAG_partial_unit:
17308             case DW_TAG_type_unit:
17309               /* Compilation units have a DW_AT_name that is a filename, not
17310                  a source language identifier.  */
17311             case DW_TAG_enumeration_type:
17312             case DW_TAG_enumerator:
17313               /* These tags always have simple identifiers already; no need
17314                  to canonicalize them.  */
17315               part_die->name = DW_STRING (&attr);
17316               break;
17317             default:
17318               part_die->name
17319                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
17320                                             &objfile->per_bfd->storage_obstack);
17321               break;
17322             }
17323           break;
17324         case DW_AT_linkage_name:
17325         case DW_AT_MIPS_linkage_name:
17326           /* Note that both forms of linkage name might appear.  We
17327              assume they will be the same, and we only store the last
17328              one we see.  */
17329           if (cu->language == language_ada)
17330             part_die->name = DW_STRING (&attr);
17331           part_die->linkage_name = DW_STRING (&attr);
17332           break;
17333         case DW_AT_low_pc:
17334           has_low_pc_attr = 1;
17335           part_die->lowpc = attr_value_as_address (&attr);
17336           break;
17337         case DW_AT_high_pc:
17338           has_high_pc_attr = 1;
17339           part_die->highpc = attr_value_as_address (&attr);
17340           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
17341                 high_pc_relative = 1;
17342           break;
17343         case DW_AT_location:
17344           /* Support the .debug_loc offsets.  */
17345           if (attr_form_is_block (&attr))
17346             {
17347                part_die->d.locdesc = DW_BLOCK (&attr);
17348             }
17349           else if (attr_form_is_section_offset (&attr))
17350             {
17351               dwarf2_complex_location_expr_complaint ();
17352             }
17353           else
17354             {
17355               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
17356                                                      "partial symbol information");
17357             }
17358           break;
17359         case DW_AT_external:
17360           part_die->is_external = DW_UNSND (&attr);
17361           break;
17362         case DW_AT_declaration:
17363           part_die->is_declaration = DW_UNSND (&attr);
17364           break;
17365         case DW_AT_type:
17366           part_die->has_type = 1;
17367           break;
17368         case DW_AT_abstract_origin:
17369         case DW_AT_specification:
17370         case DW_AT_extension:
17371           part_die->has_specification = 1;
17372           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
17373           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17374                                    || cu->per_cu->is_dwz);
17375           break;
17376         case DW_AT_sibling:
17377           /* Ignore absolute siblings, they might point outside of
17378              the current compile unit.  */
17379           if (attr.form == DW_FORM_ref_addr)
17380             complaint (&symfile_complaints,
17381                        _("ignoring absolute DW_AT_sibling"));
17382           else
17383             {
17384               sect_offset off = dwarf2_get_ref_die_offset (&attr);
17385               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
17386
17387               if (sibling_ptr < info_ptr)
17388                 complaint (&symfile_complaints,
17389                            _("DW_AT_sibling points backwards"));
17390               else if (sibling_ptr > reader->buffer_end)
17391                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
17392               else
17393                 part_die->sibling = sibling_ptr;
17394             }
17395           break;
17396         case DW_AT_byte_size:
17397           part_die->has_byte_size = 1;
17398           break;
17399         case DW_AT_const_value:
17400           part_die->has_const_value = 1;
17401           break;
17402         case DW_AT_calling_convention:
17403           /* DWARF doesn't provide a way to identify a program's source-level
17404              entry point.  DW_AT_calling_convention attributes are only meant
17405              to describe functions' calling conventions.
17406
17407              However, because it's a necessary piece of information in
17408              Fortran, and before DWARF 4 DW_CC_program was the only
17409              piece of debugging information whose definition refers to
17410              a 'main program' at all, several compilers marked Fortran
17411              main programs with DW_CC_program --- even when those
17412              functions use the standard calling conventions.
17413
17414              Although DWARF now specifies a way to provide this
17415              information, we support this practice for backward
17416              compatibility.  */
17417           if (DW_UNSND (&attr) == DW_CC_program
17418               && cu->language == language_fortran)
17419             part_die->main_subprogram = 1;
17420           break;
17421         case DW_AT_inline:
17422           if (DW_UNSND (&attr) == DW_INL_inlined
17423               || DW_UNSND (&attr) == DW_INL_declared_inlined)
17424             part_die->may_be_inlined = 1;
17425           break;
17426
17427         case DW_AT_import:
17428           if (part_die->tag == DW_TAG_imported_unit)
17429             {
17430               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
17431               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
17432                                   || cu->per_cu->is_dwz);
17433             }
17434           break;
17435
17436         case DW_AT_main_subprogram:
17437           part_die->main_subprogram = DW_UNSND (&attr);
17438           break;
17439
17440         default:
17441           break;
17442         }
17443     }
17444
17445   if (high_pc_relative)
17446     part_die->highpc += part_die->lowpc;
17447
17448   if (has_low_pc_attr && has_high_pc_attr)
17449     {
17450       /* When using the GNU linker, .gnu.linkonce. sections are used to
17451          eliminate duplicate copies of functions and vtables and such.
17452          The linker will arbitrarily choose one and discard the others.
17453          The AT_*_pc values for such functions refer to local labels in
17454          these sections.  If the section from that file was discarded, the
17455          labels are not in the output, so the relocs get a value of 0.
17456          If this is a discarded function, mark the pc bounds as invalid,
17457          so that GDB will ignore it.  */
17458       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
17459         {
17460           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17461
17462           complaint (&symfile_complaints,
17463                      _("DW_AT_low_pc %s is zero "
17464                        "for DIE at 0x%x [in module %s]"),
17465                      paddress (gdbarch, part_die->lowpc),
17466                      to_underlying (part_die->sect_off), objfile_name (objfile));
17467         }
17468       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
17469       else if (part_die->lowpc >= part_die->highpc)
17470         {
17471           struct gdbarch *gdbarch = get_objfile_arch (objfile);
17472
17473           complaint (&symfile_complaints,
17474                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
17475                        "for DIE at 0x%x [in module %s]"),
17476                      paddress (gdbarch, part_die->lowpc),
17477                      paddress (gdbarch, part_die->highpc),
17478                      to_underlying (part_die->sect_off),
17479                      objfile_name (objfile));
17480         }
17481       else
17482         part_die->has_pc_info = 1;
17483     }
17484
17485   return info_ptr;
17486 }
17487
17488 /* Find a cached partial DIE at OFFSET in CU.  */
17489
17490 static struct partial_die_info *
17491 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
17492 {
17493   struct partial_die_info *lookup_die = NULL;
17494   struct partial_die_info part_die;
17495
17496   part_die.sect_off = sect_off;
17497   lookup_die = ((struct partial_die_info *)
17498                 htab_find_with_hash (cu->partial_dies, &part_die,
17499                                      to_underlying (sect_off)));
17500
17501   return lookup_die;
17502 }
17503
17504 /* Find a partial DIE at OFFSET, which may or may not be in CU,
17505    except in the case of .debug_types DIEs which do not reference
17506    outside their CU (they do however referencing other types via
17507    DW_FORM_ref_sig8).  */
17508
17509 static struct partial_die_info *
17510 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
17511 {
17512   struct objfile *objfile = cu->objfile;
17513   struct dwarf2_per_cu_data *per_cu = NULL;
17514   struct partial_die_info *pd = NULL;
17515
17516   if (offset_in_dwz == cu->per_cu->is_dwz
17517       && offset_in_cu_p (&cu->header, sect_off))
17518     {
17519       pd = find_partial_die_in_comp_unit (sect_off, cu);
17520       if (pd != NULL)
17521         return pd;
17522       /* We missed recording what we needed.
17523          Load all dies and try again.  */
17524       per_cu = cu->per_cu;
17525     }
17526   else
17527     {
17528       /* TUs don't reference other CUs/TUs (except via type signatures).  */
17529       if (cu->per_cu->is_debug_types)
17530         {
17531           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
17532                    " external reference to offset 0x%x [in module %s].\n"),
17533                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
17534                  bfd_get_filename (objfile->obfd));
17535         }
17536       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
17537                                                  objfile);
17538
17539       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
17540         load_partial_comp_unit (per_cu);
17541
17542       per_cu->cu->last_used = 0;
17543       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17544     }
17545
17546   /* If we didn't find it, and not all dies have been loaded,
17547      load them all and try again.  */
17548
17549   if (pd == NULL && per_cu->load_all_dies == 0)
17550     {
17551       per_cu->load_all_dies = 1;
17552
17553       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
17554          THIS_CU->cu may already be in use.  So we can't just free it and
17555          replace its DIEs with the ones we read in.  Instead, we leave those
17556          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
17557          and clobber THIS_CU->cu->partial_dies with the hash table for the new
17558          set.  */
17559       load_partial_comp_unit (per_cu);
17560
17561       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
17562     }
17563
17564   if (pd == NULL)
17565     internal_error (__FILE__, __LINE__,
17566                     _("could not find partial DIE 0x%x "
17567                       "in cache [from module %s]\n"),
17568                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
17569   return pd;
17570 }
17571
17572 /* See if we can figure out if the class lives in a namespace.  We do
17573    this by looking for a member function; its demangled name will
17574    contain namespace info, if there is any.  */
17575
17576 static void
17577 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
17578                                   struct dwarf2_cu *cu)
17579 {
17580   /* NOTE: carlton/2003-10-07: Getting the info this way changes
17581      what template types look like, because the demangler
17582      frequently doesn't give the same name as the debug info.  We
17583      could fix this by only using the demangled name to get the
17584      prefix (but see comment in read_structure_type).  */
17585
17586   struct partial_die_info *real_pdi;
17587   struct partial_die_info *child_pdi;
17588
17589   /* If this DIE (this DIE's specification, if any) has a parent, then
17590      we should not do this.  We'll prepend the parent's fully qualified
17591      name when we create the partial symbol.  */
17592
17593   real_pdi = struct_pdi;
17594   while (real_pdi->has_specification)
17595     real_pdi = find_partial_die (real_pdi->spec_offset,
17596                                  real_pdi->spec_is_dwz, cu);
17597
17598   if (real_pdi->die_parent != NULL)
17599     return;
17600
17601   for (child_pdi = struct_pdi->die_child;
17602        child_pdi != NULL;
17603        child_pdi = child_pdi->die_sibling)
17604     {
17605       if (child_pdi->tag == DW_TAG_subprogram
17606           && child_pdi->linkage_name != NULL)
17607         {
17608           char *actual_class_name
17609             = language_class_name_from_physname (cu->language_defn,
17610                                                  child_pdi->linkage_name);
17611           if (actual_class_name != NULL)
17612             {
17613               struct_pdi->name
17614                 = ((const char *)
17615                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17616                                   actual_class_name,
17617                                   strlen (actual_class_name)));
17618               xfree (actual_class_name);
17619             }
17620           break;
17621         }
17622     }
17623 }
17624
17625 /* Adjust PART_DIE before generating a symbol for it.  This function
17626    may set the is_external flag or change the DIE's name.  */
17627
17628 static void
17629 fixup_partial_die (struct partial_die_info *part_die,
17630                    struct dwarf2_cu *cu)
17631 {
17632   /* Once we've fixed up a die, there's no point in doing so again.
17633      This also avoids a memory leak if we were to call
17634      guess_partial_die_structure_name multiple times.  */
17635   if (part_die->fixup_called)
17636     return;
17637
17638   /* If we found a reference attribute and the DIE has no name, try
17639      to find a name in the referred to DIE.  */
17640
17641   if (part_die->name == NULL && part_die->has_specification)
17642     {
17643       struct partial_die_info *spec_die;
17644
17645       spec_die = find_partial_die (part_die->spec_offset,
17646                                    part_die->spec_is_dwz, cu);
17647
17648       fixup_partial_die (spec_die, cu);
17649
17650       if (spec_die->name)
17651         {
17652           part_die->name = spec_die->name;
17653
17654           /* Copy DW_AT_external attribute if it is set.  */
17655           if (spec_die->is_external)
17656             part_die->is_external = spec_die->is_external;
17657         }
17658     }
17659
17660   /* Set default names for some unnamed DIEs.  */
17661
17662   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
17663     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
17664
17665   /* If there is no parent die to provide a namespace, and there are
17666      children, see if we can determine the namespace from their linkage
17667      name.  */
17668   if (cu->language == language_cplus
17669       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
17670       && part_die->die_parent == NULL
17671       && part_die->has_children
17672       && (part_die->tag == DW_TAG_class_type
17673           || part_die->tag == DW_TAG_structure_type
17674           || part_die->tag == DW_TAG_union_type))
17675     guess_partial_die_structure_name (part_die, cu);
17676
17677   /* GCC might emit a nameless struct or union that has a linkage
17678      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
17679   if (part_die->name == NULL
17680       && (part_die->tag == DW_TAG_class_type
17681           || part_die->tag == DW_TAG_interface_type
17682           || part_die->tag == DW_TAG_structure_type
17683           || part_die->tag == DW_TAG_union_type)
17684       && part_die->linkage_name != NULL)
17685     {
17686       char *demangled;
17687
17688       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
17689       if (demangled)
17690         {
17691           const char *base;
17692
17693           /* Strip any leading namespaces/classes, keep only the base name.
17694              DW_AT_name for named DIEs does not contain the prefixes.  */
17695           base = strrchr (demangled, ':');
17696           if (base && base > demangled && base[-1] == ':')
17697             base++;
17698           else
17699             base = demangled;
17700
17701           part_die->name
17702             = ((const char *)
17703                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17704                               base, strlen (base)));
17705           xfree (demangled);
17706         }
17707     }
17708
17709   part_die->fixup_called = 1;
17710 }
17711
17712 /* Read an attribute value described by an attribute form.  */
17713
17714 static const gdb_byte *
17715 read_attribute_value (const struct die_reader_specs *reader,
17716                       struct attribute *attr, unsigned form,
17717                       LONGEST implicit_const, const gdb_byte *info_ptr)
17718 {
17719   struct dwarf2_cu *cu = reader->cu;
17720   struct objfile *objfile = cu->objfile;
17721   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17722   bfd *abfd = reader->abfd;
17723   struct comp_unit_head *cu_header = &cu->header;
17724   unsigned int bytes_read;
17725   struct dwarf_block *blk;
17726
17727   attr->form = (enum dwarf_form) form;
17728   switch (form)
17729     {
17730     case DW_FORM_ref_addr:
17731       if (cu->header.version == 2)
17732         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17733       else
17734         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17735                                        &cu->header, &bytes_read);
17736       info_ptr += bytes_read;
17737       break;
17738     case DW_FORM_GNU_ref_alt:
17739       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17740       info_ptr += bytes_read;
17741       break;
17742     case DW_FORM_addr:
17743       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17744       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17745       info_ptr += bytes_read;
17746       break;
17747     case DW_FORM_block2:
17748       blk = dwarf_alloc_block (cu);
17749       blk->size = read_2_bytes (abfd, info_ptr);
17750       info_ptr += 2;
17751       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17752       info_ptr += blk->size;
17753       DW_BLOCK (attr) = blk;
17754       break;
17755     case DW_FORM_block4:
17756       blk = dwarf_alloc_block (cu);
17757       blk->size = read_4_bytes (abfd, info_ptr);
17758       info_ptr += 4;
17759       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17760       info_ptr += blk->size;
17761       DW_BLOCK (attr) = blk;
17762       break;
17763     case DW_FORM_data2:
17764       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17765       info_ptr += 2;
17766       break;
17767     case DW_FORM_data4:
17768       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17769       info_ptr += 4;
17770       break;
17771     case DW_FORM_data8:
17772       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17773       info_ptr += 8;
17774       break;
17775     case DW_FORM_data16:
17776       blk = dwarf_alloc_block (cu);
17777       blk->size = 16;
17778       blk->data = read_n_bytes (abfd, info_ptr, 16);
17779       info_ptr += 16;
17780       DW_BLOCK (attr) = blk;
17781       break;
17782     case DW_FORM_sec_offset:
17783       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17784       info_ptr += bytes_read;
17785       break;
17786     case DW_FORM_string:
17787       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17788       DW_STRING_IS_CANONICAL (attr) = 0;
17789       info_ptr += bytes_read;
17790       break;
17791     case DW_FORM_strp:
17792       if (!cu->per_cu->is_dwz)
17793         {
17794           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17795                                                    &bytes_read);
17796           DW_STRING_IS_CANONICAL (attr) = 0;
17797           info_ptr += bytes_read;
17798           break;
17799         }
17800       /* FALLTHROUGH */
17801     case DW_FORM_line_strp:
17802       if (!cu->per_cu->is_dwz)
17803         {
17804           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17805                                                         cu_header, &bytes_read);
17806           DW_STRING_IS_CANONICAL (attr) = 0;
17807           info_ptr += bytes_read;
17808           break;
17809         }
17810       /* FALLTHROUGH */
17811     case DW_FORM_GNU_strp_alt:
17812       {
17813         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17814         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17815                                           &bytes_read);
17816
17817         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17818         DW_STRING_IS_CANONICAL (attr) = 0;
17819         info_ptr += bytes_read;
17820       }
17821       break;
17822     case DW_FORM_exprloc:
17823     case DW_FORM_block:
17824       blk = dwarf_alloc_block (cu);
17825       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17826       info_ptr += bytes_read;
17827       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17828       info_ptr += blk->size;
17829       DW_BLOCK (attr) = blk;
17830       break;
17831     case DW_FORM_block1:
17832       blk = dwarf_alloc_block (cu);
17833       blk->size = read_1_byte (abfd, info_ptr);
17834       info_ptr += 1;
17835       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17836       info_ptr += blk->size;
17837       DW_BLOCK (attr) = blk;
17838       break;
17839     case DW_FORM_data1:
17840       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17841       info_ptr += 1;
17842       break;
17843     case DW_FORM_flag:
17844       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17845       info_ptr += 1;
17846       break;
17847     case DW_FORM_flag_present:
17848       DW_UNSND (attr) = 1;
17849       break;
17850     case DW_FORM_sdata:
17851       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17852       info_ptr += bytes_read;
17853       break;
17854     case DW_FORM_udata:
17855       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17856       info_ptr += bytes_read;
17857       break;
17858     case DW_FORM_ref1:
17859       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17860                          + read_1_byte (abfd, info_ptr));
17861       info_ptr += 1;
17862       break;
17863     case DW_FORM_ref2:
17864       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17865                          + read_2_bytes (abfd, info_ptr));
17866       info_ptr += 2;
17867       break;
17868     case DW_FORM_ref4:
17869       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17870                          + read_4_bytes (abfd, info_ptr));
17871       info_ptr += 4;
17872       break;
17873     case DW_FORM_ref8:
17874       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17875                          + read_8_bytes (abfd, info_ptr));
17876       info_ptr += 8;
17877       break;
17878     case DW_FORM_ref_sig8:
17879       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17880       info_ptr += 8;
17881       break;
17882     case DW_FORM_ref_udata:
17883       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17884                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17885       info_ptr += bytes_read;
17886       break;
17887     case DW_FORM_indirect:
17888       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17889       info_ptr += bytes_read;
17890       if (form == DW_FORM_implicit_const)
17891         {
17892           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17893           info_ptr += bytes_read;
17894         }
17895       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17896                                        info_ptr);
17897       break;
17898     case DW_FORM_implicit_const:
17899       DW_SND (attr) = implicit_const;
17900       break;
17901     case DW_FORM_GNU_addr_index:
17902       if (reader->dwo_file == NULL)
17903         {
17904           /* For now flag a hard error.
17905              Later we can turn this into a complaint.  */
17906           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17907                  dwarf_form_name (form),
17908                  bfd_get_filename (abfd));
17909         }
17910       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17911       info_ptr += bytes_read;
17912       break;
17913     case DW_FORM_GNU_str_index:
17914       if (reader->dwo_file == NULL)
17915         {
17916           /* For now flag a hard error.
17917              Later we can turn this into a complaint if warranted.  */
17918           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17919                  dwarf_form_name (form),
17920                  bfd_get_filename (abfd));
17921         }
17922       {
17923         ULONGEST str_index =
17924           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17925
17926         DW_STRING (attr) = read_str_index (reader, str_index);
17927         DW_STRING_IS_CANONICAL (attr) = 0;
17928         info_ptr += bytes_read;
17929       }
17930       break;
17931     default:
17932       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17933              dwarf_form_name (form),
17934              bfd_get_filename (abfd));
17935     }
17936
17937   /* Super hack.  */
17938   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17939     attr->form = DW_FORM_GNU_ref_alt;
17940
17941   /* We have seen instances where the compiler tried to emit a byte
17942      size attribute of -1 which ended up being encoded as an unsigned
17943      0xffffffff.  Although 0xffffffff is technically a valid size value,
17944      an object of this size seems pretty unlikely so we can relatively
17945      safely treat these cases as if the size attribute was invalid and
17946      treat them as zero by default.  */
17947   if (attr->name == DW_AT_byte_size
17948       && form == DW_FORM_data4
17949       && DW_UNSND (attr) >= 0xffffffff)
17950     {
17951       complaint
17952         (&symfile_complaints,
17953          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17954          hex_string (DW_UNSND (attr)));
17955       DW_UNSND (attr) = 0;
17956     }
17957
17958   return info_ptr;
17959 }
17960
17961 /* Read an attribute described by an abbreviated attribute.  */
17962
17963 static const gdb_byte *
17964 read_attribute (const struct die_reader_specs *reader,
17965                 struct attribute *attr, struct attr_abbrev *abbrev,
17966                 const gdb_byte *info_ptr)
17967 {
17968   attr->name = abbrev->name;
17969   return read_attribute_value (reader, attr, abbrev->form,
17970                                abbrev->implicit_const, info_ptr);
17971 }
17972
17973 /* Read dwarf information from a buffer.  */
17974
17975 static unsigned int
17976 read_1_byte (bfd *abfd, const gdb_byte *buf)
17977 {
17978   return bfd_get_8 (abfd, buf);
17979 }
17980
17981 static int
17982 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17983 {
17984   return bfd_get_signed_8 (abfd, buf);
17985 }
17986
17987 static unsigned int
17988 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17989 {
17990   return bfd_get_16 (abfd, buf);
17991 }
17992
17993 static int
17994 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17995 {
17996   return bfd_get_signed_16 (abfd, buf);
17997 }
17998
17999 static unsigned int
18000 read_4_bytes (bfd *abfd, const gdb_byte *buf)
18001 {
18002   return bfd_get_32 (abfd, buf);
18003 }
18004
18005 static int
18006 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
18007 {
18008   return bfd_get_signed_32 (abfd, buf);
18009 }
18010
18011 static ULONGEST
18012 read_8_bytes (bfd *abfd, const gdb_byte *buf)
18013 {
18014   return bfd_get_64 (abfd, buf);
18015 }
18016
18017 static CORE_ADDR
18018 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
18019               unsigned int *bytes_read)
18020 {
18021   struct comp_unit_head *cu_header = &cu->header;
18022   CORE_ADDR retval = 0;
18023
18024   if (cu_header->signed_addr_p)
18025     {
18026       switch (cu_header->addr_size)
18027         {
18028         case 2:
18029           retval = bfd_get_signed_16 (abfd, buf);
18030           break;
18031         case 4:
18032           retval = bfd_get_signed_32 (abfd, buf);
18033           break;
18034         case 8:
18035           retval = bfd_get_signed_64 (abfd, buf);
18036           break;
18037         default:
18038           internal_error (__FILE__, __LINE__,
18039                           _("read_address: bad switch, signed [in module %s]"),
18040                           bfd_get_filename (abfd));
18041         }
18042     }
18043   else
18044     {
18045       switch (cu_header->addr_size)
18046         {
18047         case 2:
18048           retval = bfd_get_16 (abfd, buf);
18049           break;
18050         case 4:
18051           retval = bfd_get_32 (abfd, buf);
18052           break;
18053         case 8:
18054           retval = bfd_get_64 (abfd, buf);
18055           break;
18056         default:
18057           internal_error (__FILE__, __LINE__,
18058                           _("read_address: bad switch, "
18059                             "unsigned [in module %s]"),
18060                           bfd_get_filename (abfd));
18061         }
18062     }
18063
18064   *bytes_read = cu_header->addr_size;
18065   return retval;
18066 }
18067
18068 /* Read the initial length from a section.  The (draft) DWARF 3
18069    specification allows the initial length to take up either 4 bytes
18070    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
18071    bytes describe the length and all offsets will be 8 bytes in length
18072    instead of 4.
18073
18074    An older, non-standard 64-bit format is also handled by this
18075    function.  The older format in question stores the initial length
18076    as an 8-byte quantity without an escape value.  Lengths greater
18077    than 2^32 aren't very common which means that the initial 4 bytes
18078    is almost always zero.  Since a length value of zero doesn't make
18079    sense for the 32-bit format, this initial zero can be considered to
18080    be an escape value which indicates the presence of the older 64-bit
18081    format.  As written, the code can't detect (old format) lengths
18082    greater than 4GB.  If it becomes necessary to handle lengths
18083    somewhat larger than 4GB, we could allow other small values (such
18084    as the non-sensical values of 1, 2, and 3) to also be used as
18085    escape values indicating the presence of the old format.
18086
18087    The value returned via bytes_read should be used to increment the
18088    relevant pointer after calling read_initial_length().
18089
18090    [ Note:  read_initial_length() and read_offset() are based on the
18091      document entitled "DWARF Debugging Information Format", revision
18092      3, draft 8, dated November 19, 2001.  This document was obtained
18093      from:
18094
18095         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
18096
18097      This document is only a draft and is subject to change.  (So beware.)
18098
18099      Details regarding the older, non-standard 64-bit format were
18100      determined empirically by examining 64-bit ELF files produced by
18101      the SGI toolchain on an IRIX 6.5 machine.
18102
18103      - Kevin, July 16, 2002
18104    ] */
18105
18106 static LONGEST
18107 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
18108 {
18109   LONGEST length = bfd_get_32 (abfd, buf);
18110
18111   if (length == 0xffffffff)
18112     {
18113       length = bfd_get_64 (abfd, buf + 4);
18114       *bytes_read = 12;
18115     }
18116   else if (length == 0)
18117     {
18118       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
18119       length = bfd_get_64 (abfd, buf);
18120       *bytes_read = 8;
18121     }
18122   else
18123     {
18124       *bytes_read = 4;
18125     }
18126
18127   return length;
18128 }
18129
18130 /* Cover function for read_initial_length.
18131    Returns the length of the object at BUF, and stores the size of the
18132    initial length in *BYTES_READ and stores the size that offsets will be in
18133    *OFFSET_SIZE.
18134    If the initial length size is not equivalent to that specified in
18135    CU_HEADER then issue a complaint.
18136    This is useful when reading non-comp-unit headers.  */
18137
18138 static LONGEST
18139 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
18140                                         const struct comp_unit_head *cu_header,
18141                                         unsigned int *bytes_read,
18142                                         unsigned int *offset_size)
18143 {
18144   LONGEST length = read_initial_length (abfd, buf, bytes_read);
18145
18146   gdb_assert (cu_header->initial_length_size == 4
18147               || cu_header->initial_length_size == 8
18148               || cu_header->initial_length_size == 12);
18149
18150   if (cu_header->initial_length_size != *bytes_read)
18151     complaint (&symfile_complaints,
18152                _("intermixed 32-bit and 64-bit DWARF sections"));
18153
18154   *offset_size = (*bytes_read == 4) ? 4 : 8;
18155   return length;
18156 }
18157
18158 /* Read an offset from the data stream.  The size of the offset is
18159    given by cu_header->offset_size.  */
18160
18161 static LONGEST
18162 read_offset (bfd *abfd, const gdb_byte *buf,
18163              const struct comp_unit_head *cu_header,
18164              unsigned int *bytes_read)
18165 {
18166   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
18167
18168   *bytes_read = cu_header->offset_size;
18169   return offset;
18170 }
18171
18172 /* Read an offset from the data stream.  */
18173
18174 static LONGEST
18175 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
18176 {
18177   LONGEST retval = 0;
18178
18179   switch (offset_size)
18180     {
18181     case 4:
18182       retval = bfd_get_32 (abfd, buf);
18183       break;
18184     case 8:
18185       retval = bfd_get_64 (abfd, buf);
18186       break;
18187     default:
18188       internal_error (__FILE__, __LINE__,
18189                       _("read_offset_1: bad switch [in module %s]"),
18190                       bfd_get_filename (abfd));
18191     }
18192
18193   return retval;
18194 }
18195
18196 static const gdb_byte *
18197 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
18198 {
18199   /* If the size of a host char is 8 bits, we can return a pointer
18200      to the buffer, otherwise we have to copy the data to a buffer
18201      allocated on the temporary obstack.  */
18202   gdb_assert (HOST_CHAR_BIT == 8);
18203   return buf;
18204 }
18205
18206 static const char *
18207 read_direct_string (bfd *abfd, const gdb_byte *buf,
18208                     unsigned int *bytes_read_ptr)
18209 {
18210   /* If the size of a host char is 8 bits, we can return a pointer
18211      to the string, otherwise we have to copy the string to a buffer
18212      allocated on the temporary obstack.  */
18213   gdb_assert (HOST_CHAR_BIT == 8);
18214   if (*buf == '\0')
18215     {
18216       *bytes_read_ptr = 1;
18217       return NULL;
18218     }
18219   *bytes_read_ptr = strlen ((const char *) buf) + 1;
18220   return (const char *) buf;
18221 }
18222
18223 /* Return pointer to string at section SECT offset STR_OFFSET with error
18224    reporting strings FORM_NAME and SECT_NAME.  */
18225
18226 static const char *
18227 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
18228                                      struct dwarf2_section_info *sect,
18229                                      const char *form_name,
18230                                      const char *sect_name)
18231 {
18232   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
18233   if (sect->buffer == NULL)
18234     error (_("%s used without %s section [in module %s]"),
18235            form_name, sect_name, bfd_get_filename (abfd));
18236   if (str_offset >= sect->size)
18237     error (_("%s pointing outside of %s section [in module %s]"),
18238            form_name, sect_name, bfd_get_filename (abfd));
18239   gdb_assert (HOST_CHAR_BIT == 8);
18240   if (sect->buffer[str_offset] == '\0')
18241     return NULL;
18242   return (const char *) (sect->buffer + str_offset);
18243 }
18244
18245 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
18246
18247 static const char *
18248 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
18249 {
18250   return read_indirect_string_at_offset_from (abfd, str_offset,
18251                                               &dwarf2_per_objfile->str,
18252                                               "DW_FORM_strp", ".debug_str");
18253 }
18254
18255 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
18256
18257 static const char *
18258 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
18259 {
18260   return read_indirect_string_at_offset_from (abfd, str_offset,
18261                                               &dwarf2_per_objfile->line_str,
18262                                               "DW_FORM_line_strp",
18263                                               ".debug_line_str");
18264 }
18265
18266 /* Read a string at offset STR_OFFSET in the .debug_str section from
18267    the .dwz file DWZ.  Throw an error if the offset is too large.  If
18268    the string consists of a single NUL byte, return NULL; otherwise
18269    return a pointer to the string.  */
18270
18271 static const char *
18272 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
18273 {
18274   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
18275
18276   if (dwz->str.buffer == NULL)
18277     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
18278              "section [in module %s]"),
18279            bfd_get_filename (dwz->dwz_bfd));
18280   if (str_offset >= dwz->str.size)
18281     error (_("DW_FORM_GNU_strp_alt pointing outside of "
18282              ".debug_str section [in module %s]"),
18283            bfd_get_filename (dwz->dwz_bfd));
18284   gdb_assert (HOST_CHAR_BIT == 8);
18285   if (dwz->str.buffer[str_offset] == '\0')
18286     return NULL;
18287   return (const char *) (dwz->str.buffer + str_offset);
18288 }
18289
18290 /* Return pointer to string at .debug_str offset as read from BUF.
18291    BUF is assumed to be in a compilation unit described by CU_HEADER.
18292    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18293
18294 static const char *
18295 read_indirect_string (bfd *abfd, const gdb_byte *buf,
18296                       const struct comp_unit_head *cu_header,
18297                       unsigned int *bytes_read_ptr)
18298 {
18299   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18300
18301   return read_indirect_string_at_offset (abfd, str_offset);
18302 }
18303
18304 /* Return pointer to string at .debug_line_str offset as read from BUF.
18305    BUF is assumed to be in a compilation unit described by CU_HEADER.
18306    Return *BYTES_READ_PTR count of bytes read from BUF.  */
18307
18308 static const char *
18309 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
18310                            const struct comp_unit_head *cu_header,
18311                            unsigned int *bytes_read_ptr)
18312 {
18313   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
18314
18315   return read_indirect_line_string_at_offset (abfd, str_offset);
18316 }
18317
18318 ULONGEST
18319 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
18320                           unsigned int *bytes_read_ptr)
18321 {
18322   ULONGEST result;
18323   unsigned int num_read;
18324   int shift;
18325   unsigned char byte;
18326
18327   result = 0;
18328   shift = 0;
18329   num_read = 0;
18330   while (1)
18331     {
18332       byte = bfd_get_8 (abfd, buf);
18333       buf++;
18334       num_read++;
18335       result |= ((ULONGEST) (byte & 127) << shift);
18336       if ((byte & 128) == 0)
18337         {
18338           break;
18339         }
18340       shift += 7;
18341     }
18342   *bytes_read_ptr = num_read;
18343   return result;
18344 }
18345
18346 static LONGEST
18347 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
18348                     unsigned int *bytes_read_ptr)
18349 {
18350   LONGEST result;
18351   int shift, num_read;
18352   unsigned char byte;
18353
18354   result = 0;
18355   shift = 0;
18356   num_read = 0;
18357   while (1)
18358     {
18359       byte = bfd_get_8 (abfd, buf);
18360       buf++;
18361       num_read++;
18362       result |= ((LONGEST) (byte & 127) << shift);
18363       shift += 7;
18364       if ((byte & 128) == 0)
18365         {
18366           break;
18367         }
18368     }
18369   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
18370     result |= -(((LONGEST) 1) << shift);
18371   *bytes_read_ptr = num_read;
18372   return result;
18373 }
18374
18375 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
18376    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
18377    ADDR_SIZE is the size of addresses from the CU header.  */
18378
18379 static CORE_ADDR
18380 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
18381 {
18382   struct objfile *objfile = dwarf2_per_objfile->objfile;
18383   bfd *abfd = objfile->obfd;
18384   const gdb_byte *info_ptr;
18385
18386   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
18387   if (dwarf2_per_objfile->addr.buffer == NULL)
18388     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
18389            objfile_name (objfile));
18390   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
18391     error (_("DW_FORM_addr_index pointing outside of "
18392              ".debug_addr section [in module %s]"),
18393            objfile_name (objfile));
18394   info_ptr = (dwarf2_per_objfile->addr.buffer
18395               + addr_base + addr_index * addr_size);
18396   if (addr_size == 4)
18397     return bfd_get_32 (abfd, info_ptr);
18398   else
18399     return bfd_get_64 (abfd, info_ptr);
18400 }
18401
18402 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
18403
18404 static CORE_ADDR
18405 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
18406 {
18407   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
18408 }
18409
18410 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
18411
18412 static CORE_ADDR
18413 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
18414                              unsigned int *bytes_read)
18415 {
18416   bfd *abfd = cu->objfile->obfd;
18417   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
18418
18419   return read_addr_index (cu, addr_index);
18420 }
18421
18422 /* Data structure to pass results from dwarf2_read_addr_index_reader
18423    back to dwarf2_read_addr_index.  */
18424
18425 struct dwarf2_read_addr_index_data
18426 {
18427   ULONGEST addr_base;
18428   int addr_size;
18429 };
18430
18431 /* die_reader_func for dwarf2_read_addr_index.  */
18432
18433 static void
18434 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
18435                                const gdb_byte *info_ptr,
18436                                struct die_info *comp_unit_die,
18437                                int has_children,
18438                                void *data)
18439 {
18440   struct dwarf2_cu *cu = reader->cu;
18441   struct dwarf2_read_addr_index_data *aidata =
18442     (struct dwarf2_read_addr_index_data *) data;
18443
18444   aidata->addr_base = cu->addr_base;
18445   aidata->addr_size = cu->header.addr_size;
18446 }
18447
18448 /* Given an index in .debug_addr, fetch the value.
18449    NOTE: This can be called during dwarf expression evaluation,
18450    long after the debug information has been read, and thus per_cu->cu
18451    may no longer exist.  */
18452
18453 CORE_ADDR
18454 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
18455                         unsigned int addr_index)
18456 {
18457   struct objfile *objfile = per_cu->objfile;
18458   struct dwarf2_cu *cu = per_cu->cu;
18459   ULONGEST addr_base;
18460   int addr_size;
18461
18462   /* This is intended to be called from outside this file.  */
18463   dw2_setup (objfile);
18464
18465   /* We need addr_base and addr_size.
18466      If we don't have PER_CU->cu, we have to get it.
18467      Nasty, but the alternative is storing the needed info in PER_CU,
18468      which at this point doesn't seem justified: it's not clear how frequently
18469      it would get used and it would increase the size of every PER_CU.
18470      Entry points like dwarf2_per_cu_addr_size do a similar thing
18471      so we're not in uncharted territory here.
18472      Alas we need to be a bit more complicated as addr_base is contained
18473      in the DIE.
18474
18475      We don't need to read the entire CU(/TU).
18476      We just need the header and top level die.
18477
18478      IWBN to use the aging mechanism to let us lazily later discard the CU.
18479      For now we skip this optimization.  */
18480
18481   if (cu != NULL)
18482     {
18483       addr_base = cu->addr_base;
18484       addr_size = cu->header.addr_size;
18485     }
18486   else
18487     {
18488       struct dwarf2_read_addr_index_data aidata;
18489
18490       /* Note: We can't use init_cutu_and_read_dies_simple here,
18491          we need addr_base.  */
18492       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
18493                                dwarf2_read_addr_index_reader, &aidata);
18494       addr_base = aidata.addr_base;
18495       addr_size = aidata.addr_size;
18496     }
18497
18498   return read_addr_index_1 (addr_index, addr_base, addr_size);
18499 }
18500
18501 /* Given a DW_FORM_GNU_str_index, fetch the string.
18502    This is only used by the Fission support.  */
18503
18504 static const char *
18505 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
18506 {
18507   struct objfile *objfile = dwarf2_per_objfile->objfile;
18508   const char *objf_name = objfile_name (objfile);
18509   bfd *abfd = objfile->obfd;
18510   struct dwarf2_cu *cu = reader->cu;
18511   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
18512   struct dwarf2_section_info *str_offsets_section =
18513     &reader->dwo_file->sections.str_offsets;
18514   const gdb_byte *info_ptr;
18515   ULONGEST str_offset;
18516   static const char form_name[] = "DW_FORM_GNU_str_index";
18517
18518   dwarf2_read_section (objfile, str_section);
18519   dwarf2_read_section (objfile, str_offsets_section);
18520   if (str_section->buffer == NULL)
18521     error (_("%s used without .debug_str.dwo section"
18522              " in CU at offset 0x%x [in module %s]"),
18523            form_name, to_underlying (cu->header.sect_off), objf_name);
18524   if (str_offsets_section->buffer == NULL)
18525     error (_("%s used without .debug_str_offsets.dwo section"
18526              " in CU at offset 0x%x [in module %s]"),
18527            form_name, to_underlying (cu->header.sect_off), objf_name);
18528   if (str_index * cu->header.offset_size >= str_offsets_section->size)
18529     error (_("%s pointing outside of .debug_str_offsets.dwo"
18530              " section in CU at offset 0x%x [in module %s]"),
18531            form_name, to_underlying (cu->header.sect_off), objf_name);
18532   info_ptr = (str_offsets_section->buffer
18533               + str_index * cu->header.offset_size);
18534   if (cu->header.offset_size == 4)
18535     str_offset = bfd_get_32 (abfd, info_ptr);
18536   else
18537     str_offset = bfd_get_64 (abfd, info_ptr);
18538   if (str_offset >= str_section->size)
18539     error (_("Offset from %s pointing outside of"
18540              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
18541            form_name, to_underlying (cu->header.sect_off), objf_name);
18542   return (const char *) (str_section->buffer + str_offset);
18543 }
18544
18545 /* Return the length of an LEB128 number in BUF.  */
18546
18547 static int
18548 leb128_size (const gdb_byte *buf)
18549 {
18550   const gdb_byte *begin = buf;
18551   gdb_byte byte;
18552
18553   while (1)
18554     {
18555       byte = *buf++;
18556       if ((byte & 128) == 0)
18557         return buf - begin;
18558     }
18559 }
18560
18561 static void
18562 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
18563 {
18564   switch (lang)
18565     {
18566     case DW_LANG_C89:
18567     case DW_LANG_C99:
18568     case DW_LANG_C11:
18569     case DW_LANG_C:
18570     case DW_LANG_UPC:
18571       cu->language = language_c;
18572       break;
18573     case DW_LANG_Java:
18574     case DW_LANG_C_plus_plus:
18575     case DW_LANG_C_plus_plus_11:
18576     case DW_LANG_C_plus_plus_14:
18577       cu->language = language_cplus;
18578       break;
18579     case DW_LANG_D:
18580       cu->language = language_d;
18581       break;
18582     case DW_LANG_Fortran77:
18583     case DW_LANG_Fortran90:
18584     case DW_LANG_Fortran95:
18585     case DW_LANG_Fortran03:
18586     case DW_LANG_Fortran08:
18587       cu->language = language_fortran;
18588       break;
18589     case DW_LANG_Go:
18590       cu->language = language_go;
18591       break;
18592     case DW_LANG_Mips_Assembler:
18593       cu->language = language_asm;
18594       break;
18595     case DW_LANG_Ada83:
18596     case DW_LANG_Ada95:
18597       cu->language = language_ada;
18598       break;
18599     case DW_LANG_Modula2:
18600       cu->language = language_m2;
18601       break;
18602     case DW_LANG_Pascal83:
18603       cu->language = language_pascal;
18604       break;
18605     case DW_LANG_ObjC:
18606       cu->language = language_objc;
18607       break;
18608     case DW_LANG_Rust:
18609     case DW_LANG_Rust_old:
18610       cu->language = language_rust;
18611       break;
18612     case DW_LANG_Cobol74:
18613     case DW_LANG_Cobol85:
18614     default:
18615       cu->language = language_minimal;
18616       break;
18617     }
18618   cu->language_defn = language_def (cu->language);
18619 }
18620
18621 /* Return the named attribute or NULL if not there.  */
18622
18623 static struct attribute *
18624 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18625 {
18626   for (;;)
18627     {
18628       unsigned int i;
18629       struct attribute *spec = NULL;
18630
18631       for (i = 0; i < die->num_attrs; ++i)
18632         {
18633           if (die->attrs[i].name == name)
18634             return &die->attrs[i];
18635           if (die->attrs[i].name == DW_AT_specification
18636               || die->attrs[i].name == DW_AT_abstract_origin)
18637             spec = &die->attrs[i];
18638         }
18639
18640       if (!spec)
18641         break;
18642
18643       die = follow_die_ref (die, spec, &cu);
18644     }
18645
18646   return NULL;
18647 }
18648
18649 /* Return the named attribute or NULL if not there,
18650    but do not follow DW_AT_specification, etc.
18651    This is for use in contexts where we're reading .debug_types dies.
18652    Following DW_AT_specification, DW_AT_abstract_origin will take us
18653    back up the chain, and we want to go down.  */
18654
18655 static struct attribute *
18656 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
18657 {
18658   unsigned int i;
18659
18660   for (i = 0; i < die->num_attrs; ++i)
18661     if (die->attrs[i].name == name)
18662       return &die->attrs[i];
18663
18664   return NULL;
18665 }
18666
18667 /* Return the string associated with a string-typed attribute, or NULL if it
18668    is either not found or is of an incorrect type.  */
18669
18670 static const char *
18671 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
18672 {
18673   struct attribute *attr;
18674   const char *str = NULL;
18675
18676   attr = dwarf2_attr (die, name, cu);
18677
18678   if (attr != NULL)
18679     {
18680       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
18681           || attr->form == DW_FORM_string
18682           || attr->form == DW_FORM_GNU_str_index
18683           || attr->form == DW_FORM_GNU_strp_alt)
18684         str = DW_STRING (attr);
18685       else
18686         complaint (&symfile_complaints,
18687                    _("string type expected for attribute %s for "
18688                      "DIE at 0x%x in module %s"),
18689                    dwarf_attr_name (name), to_underlying (die->sect_off),
18690                    objfile_name (cu->objfile));
18691     }
18692
18693   return str;
18694 }
18695
18696 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18697    and holds a non-zero value.  This function should only be used for
18698    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18699
18700 static int
18701 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18702 {
18703   struct attribute *attr = dwarf2_attr (die, name, cu);
18704
18705   return (attr && DW_UNSND (attr));
18706 }
18707
18708 static int
18709 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18710 {
18711   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18712      which value is non-zero.  However, we have to be careful with
18713      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18714      (via dwarf2_flag_true_p) follows this attribute.  So we may
18715      end up accidently finding a declaration attribute that belongs
18716      to a different DIE referenced by the specification attribute,
18717      even though the given DIE does not have a declaration attribute.  */
18718   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18719           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18720 }
18721
18722 /* Return the die giving the specification for DIE, if there is
18723    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18724    containing the return value on output.  If there is no
18725    specification, but there is an abstract origin, that is
18726    returned.  */
18727
18728 static struct die_info *
18729 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18730 {
18731   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18732                                              *spec_cu);
18733
18734   if (spec_attr == NULL)
18735     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18736
18737   if (spec_attr == NULL)
18738     return NULL;
18739   else
18740     return follow_die_ref (die, spec_attr, spec_cu);
18741 }
18742
18743 /* Stub for free_line_header to match void * callback types.  */
18744
18745 static void
18746 free_line_header_voidp (void *arg)
18747 {
18748   struct line_header *lh = (struct line_header *) arg;
18749
18750   delete lh;
18751 }
18752
18753 void
18754 line_header::add_include_dir (const char *include_dir)
18755 {
18756   if (dwarf_line_debug >= 2)
18757     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18758                         include_dirs.size () + 1, include_dir);
18759
18760   include_dirs.push_back (include_dir);
18761 }
18762
18763 void
18764 line_header::add_file_name (const char *name,
18765                             dir_index d_index,
18766                             unsigned int mod_time,
18767                             unsigned int length)
18768 {
18769   if (dwarf_line_debug >= 2)
18770     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18771                         (unsigned) file_names.size () + 1, name);
18772
18773   file_names.emplace_back (name, d_index, mod_time, length);
18774 }
18775
18776 /* A convenience function to find the proper .debug_line section for a CU.  */
18777
18778 static struct dwarf2_section_info *
18779 get_debug_line_section (struct dwarf2_cu *cu)
18780 {
18781   struct dwarf2_section_info *section;
18782
18783   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18784      DWO file.  */
18785   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18786     section = &cu->dwo_unit->dwo_file->sections.line;
18787   else if (cu->per_cu->is_dwz)
18788     {
18789       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18790
18791       section = &dwz->line;
18792     }
18793   else
18794     section = &dwarf2_per_objfile->line;
18795
18796   return section;
18797 }
18798
18799 /* Read directory or file name entry format, starting with byte of
18800    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18801    entries count and the entries themselves in the described entry
18802    format.  */
18803
18804 static void
18805 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18806                         struct line_header *lh,
18807                         const struct comp_unit_head *cu_header,
18808                         void (*callback) (struct line_header *lh,
18809                                           const char *name,
18810                                           dir_index d_index,
18811                                           unsigned int mod_time,
18812                                           unsigned int length))
18813 {
18814   gdb_byte format_count, formati;
18815   ULONGEST data_count, datai;
18816   const gdb_byte *buf = *bufp;
18817   const gdb_byte *format_header_data;
18818   unsigned int bytes_read;
18819
18820   format_count = read_1_byte (abfd, buf);
18821   buf += 1;
18822   format_header_data = buf;
18823   for (formati = 0; formati < format_count; formati++)
18824     {
18825       read_unsigned_leb128 (abfd, buf, &bytes_read);
18826       buf += bytes_read;
18827       read_unsigned_leb128 (abfd, buf, &bytes_read);
18828       buf += bytes_read;
18829     }
18830
18831   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18832   buf += bytes_read;
18833   for (datai = 0; datai < data_count; datai++)
18834     {
18835       const gdb_byte *format = format_header_data;
18836       struct file_entry fe;
18837
18838       for (formati = 0; formati < format_count; formati++)
18839         {
18840           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18841           format += bytes_read;
18842
18843           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18844           format += bytes_read;
18845
18846           gdb::optional<const char *> string;
18847           gdb::optional<unsigned int> uint;
18848
18849           switch (form)
18850             {
18851             case DW_FORM_string:
18852               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18853               buf += bytes_read;
18854               break;
18855
18856             case DW_FORM_line_strp:
18857               string.emplace (read_indirect_line_string (abfd, buf,
18858                                                          cu_header,
18859                                                          &bytes_read));
18860               buf += bytes_read;
18861               break;
18862
18863             case DW_FORM_data1:
18864               uint.emplace (read_1_byte (abfd, buf));
18865               buf += 1;
18866               break;
18867
18868             case DW_FORM_data2:
18869               uint.emplace (read_2_bytes (abfd, buf));
18870               buf += 2;
18871               break;
18872
18873             case DW_FORM_data4:
18874               uint.emplace (read_4_bytes (abfd, buf));
18875               buf += 4;
18876               break;
18877
18878             case DW_FORM_data8:
18879               uint.emplace (read_8_bytes (abfd, buf));
18880               buf += 8;
18881               break;
18882
18883             case DW_FORM_udata:
18884               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18885               buf += bytes_read;
18886               break;
18887
18888             case DW_FORM_block:
18889               /* It is valid only for DW_LNCT_timestamp which is ignored by
18890                  current GDB.  */
18891               break;
18892             }
18893
18894           switch (content_type)
18895             {
18896             case DW_LNCT_path:
18897               if (string.has_value ())
18898                 fe.name = *string;
18899               break;
18900             case DW_LNCT_directory_index:
18901               if (uint.has_value ())
18902                 fe.d_index = (dir_index) *uint;
18903               break;
18904             case DW_LNCT_timestamp:
18905               if (uint.has_value ())
18906                 fe.mod_time = *uint;
18907               break;
18908             case DW_LNCT_size:
18909               if (uint.has_value ())
18910                 fe.length = *uint;
18911               break;
18912             case DW_LNCT_MD5:
18913               break;
18914             default:
18915               complaint (&symfile_complaints,
18916                          _("Unknown format content type %s"),
18917                          pulongest (content_type));
18918             }
18919         }
18920
18921       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18922     }
18923
18924   *bufp = buf;
18925 }
18926
18927 /* Read the statement program header starting at OFFSET in
18928    .debug_line, or .debug_line.dwo.  Return a pointer
18929    to a struct line_header, allocated using xmalloc.
18930    Returns NULL if there is a problem reading the header, e.g., if it
18931    has a version we don't understand.
18932
18933    NOTE: the strings in the include directory and file name tables of
18934    the returned object point into the dwarf line section buffer,
18935    and must not be freed.  */
18936
18937 static line_header_up
18938 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18939 {
18940   const gdb_byte *line_ptr;
18941   unsigned int bytes_read, offset_size;
18942   int i;
18943   const char *cur_dir, *cur_file;
18944   struct dwarf2_section_info *section;
18945   bfd *abfd;
18946
18947   section = get_debug_line_section (cu);
18948   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18949   if (section->buffer == NULL)
18950     {
18951       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18952         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18953       else
18954         complaint (&symfile_complaints, _("missing .debug_line section"));
18955       return 0;
18956     }
18957
18958   /* We can't do this until we know the section is non-empty.
18959      Only then do we know we have such a section.  */
18960   abfd = get_section_bfd_owner (section);
18961
18962   /* Make sure that at least there's room for the total_length field.
18963      That could be 12 bytes long, but we're just going to fudge that.  */
18964   if (to_underlying (sect_off) + 4 >= section->size)
18965     {
18966       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18967       return 0;
18968     }
18969
18970   line_header_up lh (new line_header ());
18971
18972   lh->sect_off = sect_off;
18973   lh->offset_in_dwz = cu->per_cu->is_dwz;
18974
18975   line_ptr = section->buffer + to_underlying (sect_off);
18976
18977   /* Read in the header.  */
18978   lh->total_length =
18979     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18980                                             &bytes_read, &offset_size);
18981   line_ptr += bytes_read;
18982   if (line_ptr + lh->total_length > (section->buffer + section->size))
18983     {
18984       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18985       return 0;
18986     }
18987   lh->statement_program_end = line_ptr + lh->total_length;
18988   lh->version = read_2_bytes (abfd, line_ptr);
18989   line_ptr += 2;
18990   if (lh->version > 5)
18991     {
18992       /* This is a version we don't understand.  The format could have
18993          changed in ways we don't handle properly so just punt.  */
18994       complaint (&symfile_complaints,
18995                  _("unsupported version in .debug_line section"));
18996       return NULL;
18997     }
18998   if (lh->version >= 5)
18999     {
19000       gdb_byte segment_selector_size;
19001
19002       /* Skip address size.  */
19003       read_1_byte (abfd, line_ptr);
19004       line_ptr += 1;
19005
19006       segment_selector_size = read_1_byte (abfd, line_ptr);
19007       line_ptr += 1;
19008       if (segment_selector_size != 0)
19009         {
19010           complaint (&symfile_complaints,
19011                      _("unsupported segment selector size %u "
19012                        "in .debug_line section"),
19013                      segment_selector_size);
19014           return NULL;
19015         }
19016     }
19017   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
19018   line_ptr += offset_size;
19019   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
19020   line_ptr += 1;
19021   if (lh->version >= 4)
19022     {
19023       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
19024       line_ptr += 1;
19025     }
19026   else
19027     lh->maximum_ops_per_instruction = 1;
19028
19029   if (lh->maximum_ops_per_instruction == 0)
19030     {
19031       lh->maximum_ops_per_instruction = 1;
19032       complaint (&symfile_complaints,
19033                  _("invalid maximum_ops_per_instruction "
19034                    "in `.debug_line' section"));
19035     }
19036
19037   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
19038   line_ptr += 1;
19039   lh->line_base = read_1_signed_byte (abfd, line_ptr);
19040   line_ptr += 1;
19041   lh->line_range = read_1_byte (abfd, line_ptr);
19042   line_ptr += 1;
19043   lh->opcode_base = read_1_byte (abfd, line_ptr);
19044   line_ptr += 1;
19045   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
19046
19047   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
19048   for (i = 1; i < lh->opcode_base; ++i)
19049     {
19050       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
19051       line_ptr += 1;
19052     }
19053
19054   if (lh->version >= 5)
19055     {
19056       /* Read directory table.  */
19057       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19058                               [] (struct line_header *lh, const char *name,
19059                                   dir_index d_index, unsigned int mod_time,
19060                                   unsigned int length)
19061         {
19062           lh->add_include_dir (name);
19063         });
19064
19065       /* Read file name table.  */
19066       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
19067                               [] (struct line_header *lh, const char *name,
19068                                   dir_index d_index, unsigned int mod_time,
19069                                   unsigned int length)
19070         {
19071           lh->add_file_name (name, d_index, mod_time, length);
19072         });
19073     }
19074   else
19075     {
19076       /* Read directory table.  */
19077       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19078         {
19079           line_ptr += bytes_read;
19080           lh->add_include_dir (cur_dir);
19081         }
19082       line_ptr += bytes_read;
19083
19084       /* Read file name table.  */
19085       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
19086         {
19087           unsigned int mod_time, length;
19088           dir_index d_index;
19089
19090           line_ptr += bytes_read;
19091           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19092           line_ptr += bytes_read;
19093           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19094           line_ptr += bytes_read;
19095           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19096           line_ptr += bytes_read;
19097
19098           lh->add_file_name (cur_file, d_index, mod_time, length);
19099         }
19100       line_ptr += bytes_read;
19101     }
19102   lh->statement_program_start = line_ptr;
19103
19104   if (line_ptr > (section->buffer + section->size))
19105     complaint (&symfile_complaints,
19106                _("line number info header doesn't "
19107                  "fit in `.debug_line' section"));
19108
19109   return lh;
19110 }
19111
19112 /* Subroutine of dwarf_decode_lines to simplify it.
19113    Return the file name of the psymtab for included file FILE_INDEX
19114    in line header LH of PST.
19115    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19116    If space for the result is malloc'd, it will be freed by a cleanup.
19117    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
19118
19119    The function creates dangling cleanup registration.  */
19120
19121 static const char *
19122 psymtab_include_file_name (const struct line_header *lh, int file_index,
19123                            const struct partial_symtab *pst,
19124                            const char *comp_dir)
19125 {
19126   const file_entry &fe = lh->file_names[file_index];
19127   const char *include_name = fe.name;
19128   const char *include_name_to_compare = include_name;
19129   const char *pst_filename;
19130   char *copied_name = NULL;
19131   int file_is_pst;
19132
19133   const char *dir_name = fe.include_dir (lh);
19134
19135   if (!IS_ABSOLUTE_PATH (include_name)
19136       && (dir_name != NULL || comp_dir != NULL))
19137     {
19138       /* Avoid creating a duplicate psymtab for PST.
19139          We do this by comparing INCLUDE_NAME and PST_FILENAME.
19140          Before we do the comparison, however, we need to account
19141          for DIR_NAME and COMP_DIR.
19142          First prepend dir_name (if non-NULL).  If we still don't
19143          have an absolute path prepend comp_dir (if non-NULL).
19144          However, the directory we record in the include-file's
19145          psymtab does not contain COMP_DIR (to match the
19146          corresponding symtab(s)).
19147
19148          Example:
19149
19150          bash$ cd /tmp
19151          bash$ gcc -g ./hello.c
19152          include_name = "hello.c"
19153          dir_name = "."
19154          DW_AT_comp_dir = comp_dir = "/tmp"
19155          DW_AT_name = "./hello.c"
19156
19157       */
19158
19159       if (dir_name != NULL)
19160         {
19161           char *tem = concat (dir_name, SLASH_STRING,
19162                               include_name, (char *)NULL);
19163
19164           make_cleanup (xfree, tem);
19165           include_name = tem;
19166           include_name_to_compare = include_name;
19167         }
19168       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
19169         {
19170           char *tem = concat (comp_dir, SLASH_STRING,
19171                               include_name, (char *)NULL);
19172
19173           make_cleanup (xfree, tem);
19174           include_name_to_compare = tem;
19175         }
19176     }
19177
19178   pst_filename = pst->filename;
19179   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
19180     {
19181       copied_name = concat (pst->dirname, SLASH_STRING,
19182                             pst_filename, (char *)NULL);
19183       pst_filename = copied_name;
19184     }
19185
19186   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
19187
19188   if (copied_name != NULL)
19189     xfree (copied_name);
19190
19191   if (file_is_pst)
19192     return NULL;
19193   return include_name;
19194 }
19195
19196 /* State machine to track the state of the line number program.  */
19197
19198 class lnp_state_machine
19199 {
19200 public:
19201   /* Initialize a machine state for the start of a line number
19202      program.  */
19203   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
19204
19205   file_entry *current_file ()
19206   {
19207     /* lh->file_names is 0-based, but the file name numbers in the
19208        statement program are 1-based.  */
19209     return m_line_header->file_name_at (m_file);
19210   }
19211
19212   /* Record the line in the state machine.  END_SEQUENCE is true if
19213      we're processing the end of a sequence.  */
19214   void record_line (bool end_sequence);
19215
19216   /* Check address and if invalid nop-out the rest of the lines in this
19217      sequence.  */
19218   void check_line_address (struct dwarf2_cu *cu,
19219                            const gdb_byte *line_ptr,
19220                            CORE_ADDR lowpc, CORE_ADDR address);
19221
19222   void handle_set_discriminator (unsigned int discriminator)
19223   {
19224     m_discriminator = discriminator;
19225     m_line_has_non_zero_discriminator |= discriminator != 0;
19226   }
19227
19228   /* Handle DW_LNE_set_address.  */
19229   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
19230   {
19231     m_op_index = 0;
19232     address += baseaddr;
19233     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
19234   }
19235
19236   /* Handle DW_LNS_advance_pc.  */
19237   void handle_advance_pc (CORE_ADDR adjust);
19238
19239   /* Handle a special opcode.  */
19240   void handle_special_opcode (unsigned char op_code);
19241
19242   /* Handle DW_LNS_advance_line.  */
19243   void handle_advance_line (int line_delta)
19244   {
19245     advance_line (line_delta);
19246   }
19247
19248   /* Handle DW_LNS_set_file.  */
19249   void handle_set_file (file_name_index file);
19250
19251   /* Handle DW_LNS_negate_stmt.  */
19252   void handle_negate_stmt ()
19253   {
19254     m_is_stmt = !m_is_stmt;
19255   }
19256
19257   /* Handle DW_LNS_const_add_pc.  */
19258   void handle_const_add_pc ();
19259
19260   /* Handle DW_LNS_fixed_advance_pc.  */
19261   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
19262   {
19263     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19264     m_op_index = 0;
19265   }
19266
19267   /* Handle DW_LNS_copy.  */
19268   void handle_copy ()
19269   {
19270     record_line (false);
19271     m_discriminator = 0;
19272   }
19273
19274   /* Handle DW_LNE_end_sequence.  */
19275   void handle_end_sequence ()
19276   {
19277     m_record_line_callback = ::record_line;
19278   }
19279
19280 private:
19281   /* Advance the line by LINE_DELTA.  */
19282   void advance_line (int line_delta)
19283   {
19284     m_line += line_delta;
19285
19286     if (line_delta != 0)
19287       m_line_has_non_zero_discriminator = m_discriminator != 0;
19288   }
19289
19290   gdbarch *m_gdbarch;
19291
19292   /* True if we're recording lines.
19293      Otherwise we're building partial symtabs and are just interested in
19294      finding include files mentioned by the line number program.  */
19295   bool m_record_lines_p;
19296
19297   /* The line number header.  */
19298   line_header *m_line_header;
19299
19300   /* These are part of the standard DWARF line number state machine,
19301      and initialized according to the DWARF spec.  */
19302
19303   unsigned char m_op_index = 0;
19304   /* The line table index (1-based) of the current file.  */
19305   file_name_index m_file = (file_name_index) 1;
19306   unsigned int m_line = 1;
19307
19308   /* These are initialized in the constructor.  */
19309
19310   CORE_ADDR m_address;
19311   bool m_is_stmt;
19312   unsigned int m_discriminator;
19313
19314   /* Additional bits of state we need to track.  */
19315
19316   /* The last file that we called dwarf2_start_subfile for.
19317      This is only used for TLLs.  */
19318   unsigned int m_last_file = 0;
19319   /* The last file a line number was recorded for.  */
19320   struct subfile *m_last_subfile = NULL;
19321
19322   /* The function to call to record a line.  */
19323   record_line_ftype *m_record_line_callback = NULL;
19324
19325   /* The last line number that was recorded, used to coalesce
19326      consecutive entries for the same line.  This can happen, for
19327      example, when discriminators are present.  PR 17276.  */
19328   unsigned int m_last_line = 0;
19329   bool m_line_has_non_zero_discriminator = false;
19330 };
19331
19332 void
19333 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
19334 {
19335   CORE_ADDR addr_adj = (((m_op_index + adjust)
19336                          / m_line_header->maximum_ops_per_instruction)
19337                         * m_line_header->minimum_instruction_length);
19338   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19339   m_op_index = ((m_op_index + adjust)
19340                 % m_line_header->maximum_ops_per_instruction);
19341 }
19342
19343 void
19344 lnp_state_machine::handle_special_opcode (unsigned char op_code)
19345 {
19346   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
19347   CORE_ADDR addr_adj = (((m_op_index
19348                           + (adj_opcode / m_line_header->line_range))
19349                          / m_line_header->maximum_ops_per_instruction)
19350                         * m_line_header->minimum_instruction_length);
19351   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19352   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
19353                 % m_line_header->maximum_ops_per_instruction);
19354
19355   int line_delta = (m_line_header->line_base
19356                     + (adj_opcode % m_line_header->line_range));
19357   advance_line (line_delta);
19358   record_line (false);
19359   m_discriminator = 0;
19360 }
19361
19362 void
19363 lnp_state_machine::handle_set_file (file_name_index file)
19364 {
19365   m_file = file;
19366
19367   const file_entry *fe = current_file ();
19368   if (fe == NULL)
19369     dwarf2_debug_line_missing_file_complaint ();
19370   else if (m_record_lines_p)
19371     {
19372       const char *dir = fe->include_dir (m_line_header);
19373
19374       m_last_subfile = current_subfile;
19375       m_line_has_non_zero_discriminator = m_discriminator != 0;
19376       dwarf2_start_subfile (fe->name, dir);
19377     }
19378 }
19379
19380 void
19381 lnp_state_machine::handle_const_add_pc ()
19382 {
19383   CORE_ADDR adjust
19384     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
19385
19386   CORE_ADDR addr_adj
19387     = (((m_op_index + adjust)
19388         / m_line_header->maximum_ops_per_instruction)
19389        * m_line_header->minimum_instruction_length);
19390
19391   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
19392   m_op_index = ((m_op_index + adjust)
19393                 % m_line_header->maximum_ops_per_instruction);
19394 }
19395
19396 /* Ignore this record_line request.  */
19397
19398 static void
19399 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
19400 {
19401   return;
19402 }
19403
19404 /* Return non-zero if we should add LINE to the line number table.
19405    LINE is the line to add, LAST_LINE is the last line that was added,
19406    LAST_SUBFILE is the subfile for LAST_LINE.
19407    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
19408    had a non-zero discriminator.
19409
19410    We have to be careful in the presence of discriminators.
19411    E.g., for this line:
19412
19413      for (i = 0; i < 100000; i++);
19414
19415    clang can emit four line number entries for that one line,
19416    each with a different discriminator.
19417    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
19418
19419    However, we want gdb to coalesce all four entries into one.
19420    Otherwise the user could stepi into the middle of the line and
19421    gdb would get confused about whether the pc really was in the
19422    middle of the line.
19423
19424    Things are further complicated by the fact that two consecutive
19425    line number entries for the same line is a heuristic used by gcc
19426    to denote the end of the prologue.  So we can't just discard duplicate
19427    entries, we have to be selective about it.  The heuristic we use is
19428    that we only collapse consecutive entries for the same line if at least
19429    one of those entries has a non-zero discriminator.  PR 17276.
19430
19431    Note: Addresses in the line number state machine can never go backwards
19432    within one sequence, thus this coalescing is ok.  */
19433
19434 static int
19435 dwarf_record_line_p (unsigned int line, unsigned int last_line,
19436                      int line_has_non_zero_discriminator,
19437                      struct subfile *last_subfile)
19438 {
19439   if (current_subfile != last_subfile)
19440     return 1;
19441   if (line != last_line)
19442     return 1;
19443   /* Same line for the same file that we've seen already.
19444      As a last check, for pr 17276, only record the line if the line
19445      has never had a non-zero discriminator.  */
19446   if (!line_has_non_zero_discriminator)
19447     return 1;
19448   return 0;
19449 }
19450
19451 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
19452    in the line table of subfile SUBFILE.  */
19453
19454 static void
19455 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
19456                      unsigned int line, CORE_ADDR address,
19457                      record_line_ftype p_record_line)
19458 {
19459   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
19460
19461   if (dwarf_line_debug)
19462     {
19463       fprintf_unfiltered (gdb_stdlog,
19464                           "Recording line %u, file %s, address %s\n",
19465                           line, lbasename (subfile->name),
19466                           paddress (gdbarch, address));
19467     }
19468
19469   (*p_record_line) (subfile, line, addr);
19470 }
19471
19472 /* Subroutine of dwarf_decode_lines_1 to simplify it.
19473    Mark the end of a set of line number records.
19474    The arguments are the same as for dwarf_record_line_1.
19475    If SUBFILE is NULL the request is ignored.  */
19476
19477 static void
19478 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
19479                    CORE_ADDR address, record_line_ftype p_record_line)
19480 {
19481   if (subfile == NULL)
19482     return;
19483
19484   if (dwarf_line_debug)
19485     {
19486       fprintf_unfiltered (gdb_stdlog,
19487                           "Finishing current line, file %s, address %s\n",
19488                           lbasename (subfile->name),
19489                           paddress (gdbarch, address));
19490     }
19491
19492   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
19493 }
19494
19495 void
19496 lnp_state_machine::record_line (bool end_sequence)
19497 {
19498   if (dwarf_line_debug)
19499     {
19500       fprintf_unfiltered (gdb_stdlog,
19501                           "Processing actual line %u: file %u,"
19502                           " address %s, is_stmt %u, discrim %u\n",
19503                           m_line, to_underlying (m_file),
19504                           paddress (m_gdbarch, m_address),
19505                           m_is_stmt, m_discriminator);
19506     }
19507
19508   file_entry *fe = current_file ();
19509
19510   if (fe == NULL)
19511     dwarf2_debug_line_missing_file_complaint ();
19512   /* For now we ignore lines not starting on an instruction boundary.
19513      But not when processing end_sequence for compatibility with the
19514      previous version of the code.  */
19515   else if (m_op_index == 0 || end_sequence)
19516     {
19517       fe->included_p = 1;
19518       if (m_record_lines_p && m_is_stmt)
19519         {
19520           if (m_last_subfile != current_subfile || end_sequence)
19521             {
19522               dwarf_finish_line (m_gdbarch, m_last_subfile,
19523                                  m_address, m_record_line_callback);
19524             }
19525
19526           if (!end_sequence)
19527             {
19528               if (dwarf_record_line_p (m_line, m_last_line,
19529                                        m_line_has_non_zero_discriminator,
19530                                        m_last_subfile))
19531                 {
19532                   dwarf_record_line_1 (m_gdbarch, current_subfile,
19533                                        m_line, m_address,
19534                                        m_record_line_callback);
19535                 }
19536               m_last_subfile = current_subfile;
19537               m_last_line = m_line;
19538             }
19539         }
19540     }
19541 }
19542
19543 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
19544                                       bool record_lines_p)
19545 {
19546   m_gdbarch = arch;
19547   m_record_lines_p = record_lines_p;
19548   m_line_header = lh;
19549
19550   m_record_line_callback = ::record_line;
19551
19552   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
19553      was a line entry for it so that the backend has a chance to adjust it
19554      and also record it in case it needs it.  This is currently used by MIPS
19555      code, cf. `mips_adjust_dwarf2_line'.  */
19556   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
19557   m_is_stmt = lh->default_is_stmt;
19558   m_discriminator = 0;
19559 }
19560
19561 void
19562 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
19563                                        const gdb_byte *line_ptr,
19564                                        CORE_ADDR lowpc, CORE_ADDR address)
19565 {
19566   /* If address < lowpc then it's not a usable value, it's outside the
19567      pc range of the CU.  However, we restrict the test to only address
19568      values of zero to preserve GDB's previous behaviour which is to
19569      handle the specific case of a function being GC'd by the linker.  */
19570
19571   if (address == 0 && address < lowpc)
19572     {
19573       /* This line table is for a function which has been
19574          GCd by the linker.  Ignore it.  PR gdb/12528 */
19575
19576       struct objfile *objfile = cu->objfile;
19577       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
19578
19579       complaint (&symfile_complaints,
19580                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
19581                  line_offset, objfile_name (objfile));
19582       m_record_line_callback = noop_record_line;
19583       /* Note: record_line_callback is left as noop_record_line until
19584          we see DW_LNE_end_sequence.  */
19585     }
19586 }
19587
19588 /* Subroutine of dwarf_decode_lines to simplify it.
19589    Process the line number information in LH.
19590    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
19591    program in order to set included_p for every referenced header.  */
19592
19593 static void
19594 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
19595                       const int decode_for_pst_p, CORE_ADDR lowpc)
19596 {
19597   const gdb_byte *line_ptr, *extended_end;
19598   const gdb_byte *line_end;
19599   unsigned int bytes_read, extended_len;
19600   unsigned char op_code, extended_op;
19601   CORE_ADDR baseaddr;
19602   struct objfile *objfile = cu->objfile;
19603   bfd *abfd = objfile->obfd;
19604   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19605   /* True if we're recording line info (as opposed to building partial
19606      symtabs and just interested in finding include files mentioned by
19607      the line number program).  */
19608   bool record_lines_p = !decode_for_pst_p;
19609
19610   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19611
19612   line_ptr = lh->statement_program_start;
19613   line_end = lh->statement_program_end;
19614
19615   /* Read the statement sequences until there's nothing left.  */
19616   while (line_ptr < line_end)
19617     {
19618       /* The DWARF line number program state machine.  Reset the state
19619          machine at the start of each sequence.  */
19620       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
19621       bool end_sequence = false;
19622
19623       if (record_lines_p)
19624         {
19625           /* Start a subfile for the current file of the state
19626              machine.  */
19627           const file_entry *fe = state_machine.current_file ();
19628
19629           if (fe != NULL)
19630             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
19631         }
19632
19633       /* Decode the table.  */
19634       while (line_ptr < line_end && !end_sequence)
19635         {
19636           op_code = read_1_byte (abfd, line_ptr);
19637           line_ptr += 1;
19638
19639           if (op_code >= lh->opcode_base)
19640             {
19641               /* Special opcode.  */
19642               state_machine.handle_special_opcode (op_code);
19643             }
19644           else switch (op_code)
19645             {
19646             case DW_LNS_extended_op:
19647               extended_len = read_unsigned_leb128 (abfd, line_ptr,
19648                                                    &bytes_read);
19649               line_ptr += bytes_read;
19650               extended_end = line_ptr + extended_len;
19651               extended_op = read_1_byte (abfd, line_ptr);
19652               line_ptr += 1;
19653               switch (extended_op)
19654                 {
19655                 case DW_LNE_end_sequence:
19656                   state_machine.handle_end_sequence ();
19657                   end_sequence = true;
19658                   break;
19659                 case DW_LNE_set_address:
19660                   {
19661                     CORE_ADDR address
19662                       = read_address (abfd, line_ptr, cu, &bytes_read);
19663                     line_ptr += bytes_read;
19664
19665                     state_machine.check_line_address (cu, line_ptr,
19666                                                       lowpc, address);
19667                     state_machine.handle_set_address (baseaddr, address);
19668                   }
19669                   break;
19670                 case DW_LNE_define_file:
19671                   {
19672                     const char *cur_file;
19673                     unsigned int mod_time, length;
19674                     dir_index dindex;
19675
19676                     cur_file = read_direct_string (abfd, line_ptr,
19677                                                    &bytes_read);
19678                     line_ptr += bytes_read;
19679                     dindex = (dir_index)
19680                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19681                     line_ptr += bytes_read;
19682                     mod_time =
19683                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19684                     line_ptr += bytes_read;
19685                     length =
19686                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19687                     line_ptr += bytes_read;
19688                     lh->add_file_name (cur_file, dindex, mod_time, length);
19689                   }
19690                   break;
19691                 case DW_LNE_set_discriminator:
19692                   {
19693                     /* The discriminator is not interesting to the
19694                        debugger; just ignore it.  We still need to
19695                        check its value though:
19696                        if there are consecutive entries for the same
19697                        (non-prologue) line we want to coalesce them.
19698                        PR 17276.  */
19699                     unsigned int discr
19700                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19701                     line_ptr += bytes_read;
19702
19703                     state_machine.handle_set_discriminator (discr);
19704                   }
19705                   break;
19706                 default:
19707                   complaint (&symfile_complaints,
19708                              _("mangled .debug_line section"));
19709                   return;
19710                 }
19711               /* Make sure that we parsed the extended op correctly.  If e.g.
19712                  we expected a different address size than the producer used,
19713                  we may have read the wrong number of bytes.  */
19714               if (line_ptr != extended_end)
19715                 {
19716                   complaint (&symfile_complaints,
19717                              _("mangled .debug_line section"));
19718                   return;
19719                 }
19720               break;
19721             case DW_LNS_copy:
19722               state_machine.handle_copy ();
19723               break;
19724             case DW_LNS_advance_pc:
19725               {
19726                 CORE_ADDR adjust
19727                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19728                 line_ptr += bytes_read;
19729
19730                 state_machine.handle_advance_pc (adjust);
19731               }
19732               break;
19733             case DW_LNS_advance_line:
19734               {
19735                 int line_delta
19736                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19737                 line_ptr += bytes_read;
19738
19739                 state_machine.handle_advance_line (line_delta);
19740               }
19741               break;
19742             case DW_LNS_set_file:
19743               {
19744                 file_name_index file
19745                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19746                                                             &bytes_read);
19747                 line_ptr += bytes_read;
19748
19749                 state_machine.handle_set_file (file);
19750               }
19751               break;
19752             case DW_LNS_set_column:
19753               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19754               line_ptr += bytes_read;
19755               break;
19756             case DW_LNS_negate_stmt:
19757               state_machine.handle_negate_stmt ();
19758               break;
19759             case DW_LNS_set_basic_block:
19760               break;
19761             /* Add to the address register of the state machine the
19762                address increment value corresponding to special opcode
19763                255.  I.e., this value is scaled by the minimum
19764                instruction length since special opcode 255 would have
19765                scaled the increment.  */
19766             case DW_LNS_const_add_pc:
19767               state_machine.handle_const_add_pc ();
19768               break;
19769             case DW_LNS_fixed_advance_pc:
19770               {
19771                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19772                 line_ptr += 2;
19773
19774                 state_machine.handle_fixed_advance_pc (addr_adj);
19775               }
19776               break;
19777             default:
19778               {
19779                 /* Unknown standard opcode, ignore it.  */
19780                 int i;
19781
19782                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19783                   {
19784                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19785                     line_ptr += bytes_read;
19786                   }
19787               }
19788             }
19789         }
19790
19791       if (!end_sequence)
19792         dwarf2_debug_line_missing_end_sequence_complaint ();
19793
19794       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19795          in which case we still finish recording the last line).  */
19796       state_machine.record_line (true);
19797     }
19798 }
19799
19800 /* Decode the Line Number Program (LNP) for the given line_header
19801    structure and CU.  The actual information extracted and the type
19802    of structures created from the LNP depends on the value of PST.
19803
19804    1. If PST is NULL, then this procedure uses the data from the program
19805       to create all necessary symbol tables, and their linetables.
19806
19807    2. If PST is not NULL, this procedure reads the program to determine
19808       the list of files included by the unit represented by PST, and
19809       builds all the associated partial symbol tables.
19810
19811    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19812    It is used for relative paths in the line table.
19813    NOTE: When processing partial symtabs (pst != NULL),
19814    comp_dir == pst->dirname.
19815
19816    NOTE: It is important that psymtabs have the same file name (via strcmp)
19817    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19818    symtab we don't use it in the name of the psymtabs we create.
19819    E.g. expand_line_sal requires this when finding psymtabs to expand.
19820    A good testcase for this is mb-inline.exp.
19821
19822    LOWPC is the lowest address in CU (or 0 if not known).
19823
19824    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19825    for its PC<->lines mapping information.  Otherwise only the filename
19826    table is read in.  */
19827
19828 static void
19829 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19830                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19831                     CORE_ADDR lowpc, int decode_mapping)
19832 {
19833   struct objfile *objfile = cu->objfile;
19834   const int decode_for_pst_p = (pst != NULL);
19835
19836   if (decode_mapping)
19837     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19838
19839   if (decode_for_pst_p)
19840     {
19841       int file_index;
19842
19843       /* Now that we're done scanning the Line Header Program, we can
19844          create the psymtab of each included file.  */
19845       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19846         if (lh->file_names[file_index].included_p == 1)
19847           {
19848             const char *include_name =
19849               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19850             if (include_name != NULL)
19851               dwarf2_create_include_psymtab (include_name, pst, objfile);
19852           }
19853     }
19854   else
19855     {
19856       /* Make sure a symtab is created for every file, even files
19857          which contain only variables (i.e. no code with associated
19858          line numbers).  */
19859       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19860       int i;
19861
19862       for (i = 0; i < lh->file_names.size (); i++)
19863         {
19864           file_entry &fe = lh->file_names[i];
19865
19866           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19867
19868           if (current_subfile->symtab == NULL)
19869             {
19870               current_subfile->symtab
19871                 = allocate_symtab (cust, current_subfile->name);
19872             }
19873           fe.symtab = current_subfile->symtab;
19874         }
19875     }
19876 }
19877
19878 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19879    DIRNAME the name of the source directory which contains FILENAME
19880    or NULL if not known.
19881    This routine tries to keep line numbers from identical absolute and
19882    relative file names in a common subfile.
19883
19884    Using the `list' example from the GDB testsuite, which resides in
19885    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19886    of /srcdir/list0.c yields the following debugging information for list0.c:
19887
19888    DW_AT_name:          /srcdir/list0.c
19889    DW_AT_comp_dir:      /compdir
19890    files.files[0].name: list0.h
19891    files.files[0].dir:  /srcdir
19892    files.files[1].name: list0.c
19893    files.files[1].dir:  /srcdir
19894
19895    The line number information for list0.c has to end up in a single
19896    subfile, so that `break /srcdir/list0.c:1' works as expected.
19897    start_subfile will ensure that this happens provided that we pass the
19898    concatenation of files.files[1].dir and files.files[1].name as the
19899    subfile's name.  */
19900
19901 static void
19902 dwarf2_start_subfile (const char *filename, const char *dirname)
19903 {
19904   char *copy = NULL;
19905
19906   /* In order not to lose the line information directory,
19907      we concatenate it to the filename when it makes sense.
19908      Note that the Dwarf3 standard says (speaking of filenames in line
19909      information): ``The directory index is ignored for file names
19910      that represent full path names''.  Thus ignoring dirname in the
19911      `else' branch below isn't an issue.  */
19912
19913   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19914     {
19915       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19916       filename = copy;
19917     }
19918
19919   start_subfile (filename);
19920
19921   if (copy != NULL)
19922     xfree (copy);
19923 }
19924
19925 /* Start a symtab for DWARF.
19926    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19927
19928 static struct compunit_symtab *
19929 dwarf2_start_symtab (struct dwarf2_cu *cu,
19930                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19931 {
19932   struct compunit_symtab *cust
19933     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19934
19935   record_debugformat ("DWARF 2");
19936   record_producer (cu->producer);
19937
19938   /* We assume that we're processing GCC output.  */
19939   processing_gcc_compilation = 2;
19940
19941   cu->processing_has_namespace_info = 0;
19942
19943   return cust;
19944 }
19945
19946 static void
19947 var_decode_location (struct attribute *attr, struct symbol *sym,
19948                      struct dwarf2_cu *cu)
19949 {
19950   struct objfile *objfile = cu->objfile;
19951   struct comp_unit_head *cu_header = &cu->header;
19952
19953   /* NOTE drow/2003-01-30: There used to be a comment and some special
19954      code here to turn a symbol with DW_AT_external and a
19955      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19956      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19957      with some versions of binutils) where shared libraries could have
19958      relocations against symbols in their debug information - the
19959      minimal symbol would have the right address, but the debug info
19960      would not.  It's no longer necessary, because we will explicitly
19961      apply relocations when we read in the debug information now.  */
19962
19963   /* A DW_AT_location attribute with no contents indicates that a
19964      variable has been optimized away.  */
19965   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19966     {
19967       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19968       return;
19969     }
19970
19971   /* Handle one degenerate form of location expression specially, to
19972      preserve GDB's previous behavior when section offsets are
19973      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19974      then mark this symbol as LOC_STATIC.  */
19975
19976   if (attr_form_is_block (attr)
19977       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19978            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19979           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19980               && (DW_BLOCK (attr)->size
19981                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19982     {
19983       unsigned int dummy;
19984
19985       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19986         SYMBOL_VALUE_ADDRESS (sym) =
19987           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19988       else
19989         SYMBOL_VALUE_ADDRESS (sym) =
19990           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19991       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19992       fixup_symbol_section (sym, objfile);
19993       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19994                                               SYMBOL_SECTION (sym));
19995       return;
19996     }
19997
19998   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19999      expression evaluator, and use LOC_COMPUTED only when necessary
20000      (i.e. when the value of a register or memory location is
20001      referenced, or a thread-local block, etc.).  Then again, it might
20002      not be worthwhile.  I'm assuming that it isn't unless performance
20003      or memory numbers show me otherwise.  */
20004
20005   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
20006
20007   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
20008     cu->has_loclist = 1;
20009 }
20010
20011 /* Given a pointer to a DWARF information entry, figure out if we need
20012    to make a symbol table entry for it, and if so, create a new entry
20013    and return a pointer to it.
20014    If TYPE is NULL, determine symbol type from the die, otherwise
20015    used the passed type.
20016    If SPACE is not NULL, use it to hold the new symbol.  If it is
20017    NULL, allocate a new symbol on the objfile's obstack.  */
20018
20019 static struct symbol *
20020 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
20021                  struct symbol *space)
20022 {
20023   struct objfile *objfile = cu->objfile;
20024   struct gdbarch *gdbarch = get_objfile_arch (objfile);
20025   struct symbol *sym = NULL;
20026   const char *name;
20027   struct attribute *attr = NULL;
20028   struct attribute *attr2 = NULL;
20029   CORE_ADDR baseaddr;
20030   struct pending **list_to_add = NULL;
20031
20032   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
20033
20034   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
20035
20036   name = dwarf2_name (die, cu);
20037   if (name)
20038     {
20039       const char *linkagename;
20040       int suppress_add = 0;
20041
20042       if (space)
20043         sym = space;
20044       else
20045         sym = allocate_symbol (objfile);
20046       OBJSTAT (objfile, n_syms++);
20047
20048       /* Cache this symbol's name and the name's demangled form (if any).  */
20049       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
20050       linkagename = dwarf2_physname (name, die, cu);
20051       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
20052
20053       /* Fortran does not have mangling standard and the mangling does differ
20054          between gfortran, iFort etc.  */
20055       if (cu->language == language_fortran
20056           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
20057         symbol_set_demangled_name (&(sym->ginfo),
20058                                    dwarf2_full_name (name, die, cu),
20059                                    NULL);
20060
20061       /* Default assumptions.
20062          Use the passed type or decode it from the die.  */
20063       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20064       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
20065       if (type != NULL)
20066         SYMBOL_TYPE (sym) = type;
20067       else
20068         SYMBOL_TYPE (sym) = die_type (die, cu);
20069       attr = dwarf2_attr (die,
20070                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
20071                           cu);
20072       if (attr)
20073         {
20074           SYMBOL_LINE (sym) = DW_UNSND (attr);
20075         }
20076
20077       attr = dwarf2_attr (die,
20078                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
20079                           cu);
20080       if (attr)
20081         {
20082           file_name_index file_index = (file_name_index) DW_UNSND (attr);
20083           struct file_entry *fe;
20084
20085           if (cu->line_header != NULL)
20086             fe = cu->line_header->file_name_at (file_index);
20087           else
20088             fe = NULL;
20089
20090           if (fe == NULL)
20091             complaint (&symfile_complaints,
20092                        _("file index out of range"));
20093           else
20094             symbol_set_symtab (sym, fe->symtab);
20095         }
20096
20097       switch (die->tag)
20098         {
20099         case DW_TAG_label:
20100           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
20101           if (attr)
20102             {
20103               CORE_ADDR addr;
20104
20105               addr = attr_value_as_address (attr);
20106               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
20107               SYMBOL_VALUE_ADDRESS (sym) = addr;
20108             }
20109           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
20110           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
20111           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
20112           add_symbol_to_list (sym, cu->list_in_scope);
20113           break;
20114         case DW_TAG_subprogram:
20115           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20116              finish_block.  */
20117           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20118           attr2 = dwarf2_attr (die, DW_AT_external, cu);
20119           if ((attr2 && (DW_UNSND (attr2) != 0))
20120               || cu->language == language_ada)
20121             {
20122               /* Subprograms marked external are stored as a global symbol.
20123                  Ada subprograms, whether marked external or not, are always
20124                  stored as a global symbol, because we want to be able to
20125                  access them globally.  For instance, we want to be able
20126                  to break on a nested subprogram without having to
20127                  specify the context.  */
20128               list_to_add = &global_symbols;
20129             }
20130           else
20131             {
20132               list_to_add = cu->list_in_scope;
20133             }
20134           break;
20135         case DW_TAG_inlined_subroutine:
20136           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
20137              finish_block.  */
20138           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
20139           SYMBOL_INLINED (sym) = 1;
20140           list_to_add = cu->list_in_scope;
20141           break;
20142         case DW_TAG_template_value_param:
20143           suppress_add = 1;
20144           /* Fall through.  */
20145         case DW_TAG_constant:
20146         case DW_TAG_variable:
20147         case DW_TAG_member:
20148           /* Compilation with minimal debug info may result in
20149              variables with missing type entries.  Change the
20150              misleading `void' type to something sensible.  */
20151           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
20152             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
20153
20154           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20155           /* In the case of DW_TAG_member, we should only be called for
20156              static const members.  */
20157           if (die->tag == DW_TAG_member)
20158             {
20159               /* dwarf2_add_field uses die_is_declaration,
20160                  so we do the same.  */
20161               gdb_assert (die_is_declaration (die, cu));
20162               gdb_assert (attr);
20163             }
20164           if (attr)
20165             {
20166               dwarf2_const_value (attr, sym, cu);
20167               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20168               if (!suppress_add)
20169                 {
20170                   if (attr2 && (DW_UNSND (attr2) != 0))
20171                     list_to_add = &global_symbols;
20172                   else
20173                     list_to_add = cu->list_in_scope;
20174                 }
20175               break;
20176             }
20177           attr = dwarf2_attr (die, DW_AT_location, cu);
20178           if (attr)
20179             {
20180               var_decode_location (attr, sym, cu);
20181               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20182
20183               /* Fortran explicitly imports any global symbols to the local
20184                  scope by DW_TAG_common_block.  */
20185               if (cu->language == language_fortran && die->parent
20186                   && die->parent->tag == DW_TAG_common_block)
20187                 attr2 = NULL;
20188
20189               if (SYMBOL_CLASS (sym) == LOC_STATIC
20190                   && SYMBOL_VALUE_ADDRESS (sym) == 0
20191                   && !dwarf2_per_objfile->has_section_at_zero)
20192                 {
20193                   /* When a static variable is eliminated by the linker,
20194                      the corresponding debug information is not stripped
20195                      out, but the variable address is set to null;
20196                      do not add such variables into symbol table.  */
20197                 }
20198               else if (attr2 && (DW_UNSND (attr2) != 0))
20199                 {
20200                   /* Workaround gfortran PR debug/40040 - it uses
20201                      DW_AT_location for variables in -fPIC libraries which may
20202                      get overriden by other libraries/executable and get
20203                      a different address.  Resolve it by the minimal symbol
20204                      which may come from inferior's executable using copy
20205                      relocation.  Make this workaround only for gfortran as for
20206                      other compilers GDB cannot guess the minimal symbol
20207                      Fortran mangling kind.  */
20208                   if (cu->language == language_fortran && die->parent
20209                       && die->parent->tag == DW_TAG_module
20210                       && cu->producer
20211                       && startswith (cu->producer, "GNU Fortran"))
20212                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20213
20214                   /* A variable with DW_AT_external is never static,
20215                      but it may be block-scoped.  */
20216                   list_to_add = (cu->list_in_scope == &file_symbols
20217                                  ? &global_symbols : cu->list_in_scope);
20218                 }
20219               else
20220                 list_to_add = cu->list_in_scope;
20221             }
20222           else
20223             {
20224               /* We do not know the address of this symbol.
20225                  If it is an external symbol and we have type information
20226                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
20227                  The address of the variable will then be determined from
20228                  the minimal symbol table whenever the variable is
20229                  referenced.  */
20230               attr2 = dwarf2_attr (die, DW_AT_external, cu);
20231
20232               /* Fortran explicitly imports any global symbols to the local
20233                  scope by DW_TAG_common_block.  */
20234               if (cu->language == language_fortran && die->parent
20235                   && die->parent->tag == DW_TAG_common_block)
20236                 {
20237                   /* SYMBOL_CLASS doesn't matter here because
20238                      read_common_block is going to reset it.  */
20239                   if (!suppress_add)
20240                     list_to_add = cu->list_in_scope;
20241                 }
20242               else if (attr2 && (DW_UNSND (attr2) != 0)
20243                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
20244                 {
20245                   /* A variable with DW_AT_external is never static, but it
20246                      may be block-scoped.  */
20247                   list_to_add = (cu->list_in_scope == &file_symbols
20248                                  ? &global_symbols : cu->list_in_scope);
20249
20250                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
20251                 }
20252               else if (!die_is_declaration (die, cu))
20253                 {
20254                   /* Use the default LOC_OPTIMIZED_OUT class.  */
20255                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
20256                   if (!suppress_add)
20257                     list_to_add = cu->list_in_scope;
20258                 }
20259             }
20260           break;
20261         case DW_TAG_formal_parameter:
20262           /* If we are inside a function, mark this as an argument.  If
20263              not, we might be looking at an argument to an inlined function
20264              when we do not have enough information to show inlined frames;
20265              pretend it's a local variable in that case so that the user can
20266              still see it.  */
20267           if (context_stack_depth > 0
20268               && context_stack[context_stack_depth - 1].name != NULL)
20269             SYMBOL_IS_ARGUMENT (sym) = 1;
20270           attr = dwarf2_attr (die, DW_AT_location, cu);
20271           if (attr)
20272             {
20273               var_decode_location (attr, sym, cu);
20274             }
20275           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20276           if (attr)
20277             {
20278               dwarf2_const_value (attr, sym, cu);
20279             }
20280
20281           list_to_add = cu->list_in_scope;
20282           break;
20283         case DW_TAG_unspecified_parameters:
20284           /* From varargs functions; gdb doesn't seem to have any
20285              interest in this information, so just ignore it for now.
20286              (FIXME?) */
20287           break;
20288         case DW_TAG_template_type_param:
20289           suppress_add = 1;
20290           /* Fall through.  */
20291         case DW_TAG_class_type:
20292         case DW_TAG_interface_type:
20293         case DW_TAG_structure_type:
20294         case DW_TAG_union_type:
20295         case DW_TAG_set_type:
20296         case DW_TAG_enumeration_type:
20297           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20298           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
20299
20300           {
20301             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
20302                really ever be static objects: otherwise, if you try
20303                to, say, break of a class's method and you're in a file
20304                which doesn't mention that class, it won't work unless
20305                the check for all static symbols in lookup_symbol_aux
20306                saves you.  See the OtherFileClass tests in
20307                gdb.c++/namespace.exp.  */
20308
20309             if (!suppress_add)
20310               {
20311                 list_to_add = (cu->list_in_scope == &file_symbols
20312                                && cu->language == language_cplus
20313                                ? &global_symbols : cu->list_in_scope);
20314
20315                 /* The semantics of C++ state that "struct foo {
20316                    ... }" also defines a typedef for "foo".  */
20317                 if (cu->language == language_cplus
20318                     || cu->language == language_ada
20319                     || cu->language == language_d
20320                     || cu->language == language_rust)
20321                   {
20322                     /* The symbol's name is already allocated along
20323                        with this objfile, so we don't need to
20324                        duplicate it for the type.  */
20325                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
20326                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
20327                   }
20328               }
20329           }
20330           break;
20331         case DW_TAG_typedef:
20332           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20333           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20334           list_to_add = cu->list_in_scope;
20335           break;
20336         case DW_TAG_base_type:
20337         case DW_TAG_subrange_type:
20338           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20339           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
20340           list_to_add = cu->list_in_scope;
20341           break;
20342         case DW_TAG_enumerator:
20343           attr = dwarf2_attr (die, DW_AT_const_value, cu);
20344           if (attr)
20345             {
20346               dwarf2_const_value (attr, sym, cu);
20347             }
20348           {
20349             /* NOTE: carlton/2003-11-10: See comment above in the
20350                DW_TAG_class_type, etc. block.  */
20351
20352             list_to_add = (cu->list_in_scope == &file_symbols
20353                            && cu->language == language_cplus
20354                            ? &global_symbols : cu->list_in_scope);
20355           }
20356           break;
20357         case DW_TAG_imported_declaration:
20358         case DW_TAG_namespace:
20359           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20360           list_to_add = &global_symbols;
20361           break;
20362         case DW_TAG_module:
20363           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
20364           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
20365           list_to_add = &global_symbols;
20366           break;
20367         case DW_TAG_common_block:
20368           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
20369           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
20370           add_symbol_to_list (sym, cu->list_in_scope);
20371           break;
20372         default:
20373           /* Not a tag we recognize.  Hopefully we aren't processing
20374              trash data, but since we must specifically ignore things
20375              we don't recognize, there is nothing else we should do at
20376              this point.  */
20377           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
20378                      dwarf_tag_name (die->tag));
20379           break;
20380         }
20381
20382       if (suppress_add)
20383         {
20384           sym->hash_next = objfile->template_symbols;
20385           objfile->template_symbols = sym;
20386           list_to_add = NULL;
20387         }
20388
20389       if (list_to_add != NULL)
20390         add_symbol_to_list (sym, list_to_add);
20391
20392       /* For the benefit of old versions of GCC, check for anonymous
20393          namespaces based on the demangled name.  */
20394       if (!cu->processing_has_namespace_info
20395           && cu->language == language_cplus)
20396         cp_scan_for_anonymous_namespaces (sym, objfile);
20397     }
20398   return (sym);
20399 }
20400
20401 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
20402
20403 static struct symbol *
20404 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
20405 {
20406   return new_symbol_full (die, type, cu, NULL);
20407 }
20408
20409 /* Given an attr with a DW_FORM_dataN value in host byte order,
20410    zero-extend it as appropriate for the symbol's type.  The DWARF
20411    standard (v4) is not entirely clear about the meaning of using
20412    DW_FORM_dataN for a constant with a signed type, where the type is
20413    wider than the data.  The conclusion of a discussion on the DWARF
20414    list was that this is unspecified.  We choose to always zero-extend
20415    because that is the interpretation long in use by GCC.  */
20416
20417 static gdb_byte *
20418 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
20419                          struct dwarf2_cu *cu, LONGEST *value, int bits)
20420 {
20421   struct objfile *objfile = cu->objfile;
20422   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
20423                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
20424   LONGEST l = DW_UNSND (attr);
20425
20426   if (bits < sizeof (*value) * 8)
20427     {
20428       l &= ((LONGEST) 1 << bits) - 1;
20429       *value = l;
20430     }
20431   else if (bits == sizeof (*value) * 8)
20432     *value = l;
20433   else
20434     {
20435       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
20436       store_unsigned_integer (bytes, bits / 8, byte_order, l);
20437       return bytes;
20438     }
20439
20440   return NULL;
20441 }
20442
20443 /* Read a constant value from an attribute.  Either set *VALUE, or if
20444    the value does not fit in *VALUE, set *BYTES - either already
20445    allocated on the objfile obstack, or newly allocated on OBSTACK,
20446    or, set *BATON, if we translated the constant to a location
20447    expression.  */
20448
20449 static void
20450 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
20451                          const char *name, struct obstack *obstack,
20452                          struct dwarf2_cu *cu,
20453                          LONGEST *value, const gdb_byte **bytes,
20454                          struct dwarf2_locexpr_baton **baton)
20455 {
20456   struct objfile *objfile = cu->objfile;
20457   struct comp_unit_head *cu_header = &cu->header;
20458   struct dwarf_block *blk;
20459   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
20460                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
20461
20462   *value = 0;
20463   *bytes = NULL;
20464   *baton = NULL;
20465
20466   switch (attr->form)
20467     {
20468     case DW_FORM_addr:
20469     case DW_FORM_GNU_addr_index:
20470       {
20471         gdb_byte *data;
20472
20473         if (TYPE_LENGTH (type) != cu_header->addr_size)
20474           dwarf2_const_value_length_mismatch_complaint (name,
20475                                                         cu_header->addr_size,
20476                                                         TYPE_LENGTH (type));
20477         /* Symbols of this form are reasonably rare, so we just
20478            piggyback on the existing location code rather than writing
20479            a new implementation of symbol_computed_ops.  */
20480         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
20481         (*baton)->per_cu = cu->per_cu;
20482         gdb_assert ((*baton)->per_cu);
20483
20484         (*baton)->size = 2 + cu_header->addr_size;
20485         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
20486         (*baton)->data = data;
20487
20488         data[0] = DW_OP_addr;
20489         store_unsigned_integer (&data[1], cu_header->addr_size,
20490                                 byte_order, DW_ADDR (attr));
20491         data[cu_header->addr_size + 1] = DW_OP_stack_value;
20492       }
20493       break;
20494     case DW_FORM_string:
20495     case DW_FORM_strp:
20496     case DW_FORM_GNU_str_index:
20497     case DW_FORM_GNU_strp_alt:
20498       /* DW_STRING is already allocated on the objfile obstack, point
20499          directly to it.  */
20500       *bytes = (const gdb_byte *) DW_STRING (attr);
20501       break;
20502     case DW_FORM_block1:
20503     case DW_FORM_block2:
20504     case DW_FORM_block4:
20505     case DW_FORM_block:
20506     case DW_FORM_exprloc:
20507     case DW_FORM_data16:
20508       blk = DW_BLOCK (attr);
20509       if (TYPE_LENGTH (type) != blk->size)
20510         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
20511                                                       TYPE_LENGTH (type));
20512       *bytes = blk->data;
20513       break;
20514
20515       /* The DW_AT_const_value attributes are supposed to carry the
20516          symbol's value "represented as it would be on the target
20517          architecture."  By the time we get here, it's already been
20518          converted to host endianness, so we just need to sign- or
20519          zero-extend it as appropriate.  */
20520     case DW_FORM_data1:
20521       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
20522       break;
20523     case DW_FORM_data2:
20524       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
20525       break;
20526     case DW_FORM_data4:
20527       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
20528       break;
20529     case DW_FORM_data8:
20530       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
20531       break;
20532
20533     case DW_FORM_sdata:
20534     case DW_FORM_implicit_const:
20535       *value = DW_SND (attr);
20536       break;
20537
20538     case DW_FORM_udata:
20539       *value = DW_UNSND (attr);
20540       break;
20541
20542     default:
20543       complaint (&symfile_complaints,
20544                  _("unsupported const value attribute form: '%s'"),
20545                  dwarf_form_name (attr->form));
20546       *value = 0;
20547       break;
20548     }
20549 }
20550
20551
20552 /* Copy constant value from an attribute to a symbol.  */
20553
20554 static void
20555 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
20556                     struct dwarf2_cu *cu)
20557 {
20558   struct objfile *objfile = cu->objfile;
20559   LONGEST value;
20560   const gdb_byte *bytes;
20561   struct dwarf2_locexpr_baton *baton;
20562
20563   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
20564                            SYMBOL_PRINT_NAME (sym),
20565                            &objfile->objfile_obstack, cu,
20566                            &value, &bytes, &baton);
20567
20568   if (baton != NULL)
20569     {
20570       SYMBOL_LOCATION_BATON (sym) = baton;
20571       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
20572     }
20573   else if (bytes != NULL)
20574      {
20575       SYMBOL_VALUE_BYTES (sym) = bytes;
20576       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
20577     }
20578   else
20579     {
20580       SYMBOL_VALUE (sym) = value;
20581       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
20582     }
20583 }
20584
20585 /* Return the type of the die in question using its DW_AT_type attribute.  */
20586
20587 static struct type *
20588 die_type (struct die_info *die, struct dwarf2_cu *cu)
20589 {
20590   struct attribute *type_attr;
20591
20592   type_attr = dwarf2_attr (die, DW_AT_type, cu);
20593   if (!type_attr)
20594     {
20595       /* A missing DW_AT_type represents a void type.  */
20596       return objfile_type (cu->objfile)->builtin_void;
20597     }
20598
20599   return lookup_die_type (die, type_attr, cu);
20600 }
20601
20602 /* True iff CU's producer generates GNAT Ada auxiliary information
20603    that allows to find parallel types through that information instead
20604    of having to do expensive parallel lookups by type name.  */
20605
20606 static int
20607 need_gnat_info (struct dwarf2_cu *cu)
20608 {
20609   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
20610      of GNAT produces this auxiliary information, without any indication
20611      that it is produced.  Part of enhancing the FSF version of GNAT
20612      to produce that information will be to put in place an indicator
20613      that we can use in order to determine whether the descriptive type
20614      info is available or not.  One suggestion that has been made is
20615      to use a new attribute, attached to the CU die.  For now, assume
20616      that the descriptive type info is not available.  */
20617   return 0;
20618 }
20619
20620 /* Return the auxiliary type of the die in question using its
20621    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
20622    attribute is not present.  */
20623
20624 static struct type *
20625 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
20626 {
20627   struct attribute *type_attr;
20628
20629   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
20630   if (!type_attr)
20631     return NULL;
20632
20633   return lookup_die_type (die, type_attr, cu);
20634 }
20635
20636 /* If DIE has a descriptive_type attribute, then set the TYPE's
20637    descriptive type accordingly.  */
20638
20639 static void
20640 set_descriptive_type (struct type *type, struct die_info *die,
20641                       struct dwarf2_cu *cu)
20642 {
20643   struct type *descriptive_type = die_descriptive_type (die, cu);
20644
20645   if (descriptive_type)
20646     {
20647       ALLOCATE_GNAT_AUX_TYPE (type);
20648       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
20649     }
20650 }
20651
20652 /* Return the containing type of the die in question using its
20653    DW_AT_containing_type attribute.  */
20654
20655 static struct type *
20656 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
20657 {
20658   struct attribute *type_attr;
20659
20660   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
20661   if (!type_attr)
20662     error (_("Dwarf Error: Problem turning containing type into gdb type "
20663              "[in module %s]"), objfile_name (cu->objfile));
20664
20665   return lookup_die_type (die, type_attr, cu);
20666 }
20667
20668 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
20669
20670 static struct type *
20671 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
20672 {
20673   struct objfile *objfile = dwarf2_per_objfile->objfile;
20674   char *message, *saved;
20675
20676   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
20677                         objfile_name (objfile),
20678                         to_underlying (cu->header.sect_off),
20679                         to_underlying (die->sect_off));
20680   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
20681                                   message, strlen (message));
20682   xfree (message);
20683
20684   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
20685 }
20686
20687 /* Look up the type of DIE in CU using its type attribute ATTR.
20688    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
20689    DW_AT_containing_type.
20690    If there is no type substitute an error marker.  */
20691
20692 static struct type *
20693 lookup_die_type (struct die_info *die, const struct attribute *attr,
20694                  struct dwarf2_cu *cu)
20695 {
20696   struct objfile *objfile = cu->objfile;
20697   struct type *this_type;
20698
20699   gdb_assert (attr->name == DW_AT_type
20700               || attr->name == DW_AT_GNAT_descriptive_type
20701               || attr->name == DW_AT_containing_type);
20702
20703   /* First see if we have it cached.  */
20704
20705   if (attr->form == DW_FORM_GNU_ref_alt)
20706     {
20707       struct dwarf2_per_cu_data *per_cu;
20708       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20709
20710       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20711       this_type = get_die_type_at_offset (sect_off, per_cu);
20712     }
20713   else if (attr_form_is_ref (attr))
20714     {
20715       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20716
20717       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20718     }
20719   else if (attr->form == DW_FORM_ref_sig8)
20720     {
20721       ULONGEST signature = DW_SIGNATURE (attr);
20722
20723       return get_signatured_type (die, signature, cu);
20724     }
20725   else
20726     {
20727       complaint (&symfile_complaints,
20728                  _("Dwarf Error: Bad type attribute %s in DIE"
20729                    " at 0x%x [in module %s]"),
20730                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20731                  objfile_name (objfile));
20732       return build_error_marker_type (cu, die);
20733     }
20734
20735   /* If not cached we need to read it in.  */
20736
20737   if (this_type == NULL)
20738     {
20739       struct die_info *type_die = NULL;
20740       struct dwarf2_cu *type_cu = cu;
20741
20742       if (attr_form_is_ref (attr))
20743         type_die = follow_die_ref (die, attr, &type_cu);
20744       if (type_die == NULL)
20745         return build_error_marker_type (cu, die);
20746       /* If we find the type now, it's probably because the type came
20747          from an inter-CU reference and the type's CU got expanded before
20748          ours.  */
20749       this_type = read_type_die (type_die, type_cu);
20750     }
20751
20752   /* If we still don't have a type use an error marker.  */
20753
20754   if (this_type == NULL)
20755     return build_error_marker_type (cu, die);
20756
20757   return this_type;
20758 }
20759
20760 /* Return the type in DIE, CU.
20761    Returns NULL for invalid types.
20762
20763    This first does a lookup in die_type_hash,
20764    and only reads the die in if necessary.
20765
20766    NOTE: This can be called when reading in partial or full symbols.  */
20767
20768 static struct type *
20769 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20770 {
20771   struct type *this_type;
20772
20773   this_type = get_die_type (die, cu);
20774   if (this_type)
20775     return this_type;
20776
20777   return read_type_die_1 (die, cu);
20778 }
20779
20780 /* Read the type in DIE, CU.
20781    Returns NULL for invalid types.  */
20782
20783 static struct type *
20784 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20785 {
20786   struct type *this_type = NULL;
20787
20788   switch (die->tag)
20789     {
20790     case DW_TAG_class_type:
20791     case DW_TAG_interface_type:
20792     case DW_TAG_structure_type:
20793     case DW_TAG_union_type:
20794       this_type = read_structure_type (die, cu);
20795       break;
20796     case DW_TAG_enumeration_type:
20797       this_type = read_enumeration_type (die, cu);
20798       break;
20799     case DW_TAG_subprogram:
20800     case DW_TAG_subroutine_type:
20801     case DW_TAG_inlined_subroutine:
20802       this_type = read_subroutine_type (die, cu);
20803       break;
20804     case DW_TAG_array_type:
20805       this_type = read_array_type (die, cu);
20806       break;
20807     case DW_TAG_set_type:
20808       this_type = read_set_type (die, cu);
20809       break;
20810     case DW_TAG_pointer_type:
20811       this_type = read_tag_pointer_type (die, cu);
20812       break;
20813     case DW_TAG_ptr_to_member_type:
20814       this_type = read_tag_ptr_to_member_type (die, cu);
20815       break;
20816     case DW_TAG_reference_type:
20817       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20818       break;
20819     case DW_TAG_rvalue_reference_type:
20820       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20821       break;
20822     case DW_TAG_const_type:
20823       this_type = read_tag_const_type (die, cu);
20824       break;
20825     case DW_TAG_volatile_type:
20826       this_type = read_tag_volatile_type (die, cu);
20827       break;
20828     case DW_TAG_restrict_type:
20829       this_type = read_tag_restrict_type (die, cu);
20830       break;
20831     case DW_TAG_string_type:
20832       this_type = read_tag_string_type (die, cu);
20833       break;
20834     case DW_TAG_typedef:
20835       this_type = read_typedef (die, cu);
20836       break;
20837     case DW_TAG_subrange_type:
20838       this_type = read_subrange_type (die, cu);
20839       break;
20840     case DW_TAG_base_type:
20841       this_type = read_base_type (die, cu);
20842       break;
20843     case DW_TAG_unspecified_type:
20844       this_type = read_unspecified_type (die, cu);
20845       break;
20846     case DW_TAG_namespace:
20847       this_type = read_namespace_type (die, cu);
20848       break;
20849     case DW_TAG_module:
20850       this_type = read_module_type (die, cu);
20851       break;
20852     case DW_TAG_atomic_type:
20853       this_type = read_tag_atomic_type (die, cu);
20854       break;
20855     default:
20856       complaint (&symfile_complaints,
20857                  _("unexpected tag in read_type_die: '%s'"),
20858                  dwarf_tag_name (die->tag));
20859       break;
20860     }
20861
20862   return this_type;
20863 }
20864
20865 /* See if we can figure out if the class lives in a namespace.  We do
20866    this by looking for a member function; its demangled name will
20867    contain namespace info, if there is any.
20868    Return the computed name or NULL.
20869    Space for the result is allocated on the objfile's obstack.
20870    This is the full-die version of guess_partial_die_structure_name.
20871    In this case we know DIE has no useful parent.  */
20872
20873 static char *
20874 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20875 {
20876   struct die_info *spec_die;
20877   struct dwarf2_cu *spec_cu;
20878   struct die_info *child;
20879
20880   spec_cu = cu;
20881   spec_die = die_specification (die, &spec_cu);
20882   if (spec_die != NULL)
20883     {
20884       die = spec_die;
20885       cu = spec_cu;
20886     }
20887
20888   for (child = die->child;
20889        child != NULL;
20890        child = child->sibling)
20891     {
20892       if (child->tag == DW_TAG_subprogram)
20893         {
20894           const char *linkage_name = dw2_linkage_name (child, cu);
20895
20896           if (linkage_name != NULL)
20897             {
20898               char *actual_name
20899                 = language_class_name_from_physname (cu->language_defn,
20900                                                      linkage_name);
20901               char *name = NULL;
20902
20903               if (actual_name != NULL)
20904                 {
20905                   const char *die_name = dwarf2_name (die, cu);
20906
20907                   if (die_name != NULL
20908                       && strcmp (die_name, actual_name) != 0)
20909                     {
20910                       /* Strip off the class name from the full name.
20911                          We want the prefix.  */
20912                       int die_name_len = strlen (die_name);
20913                       int actual_name_len = strlen (actual_name);
20914
20915                       /* Test for '::' as a sanity check.  */
20916                       if (actual_name_len > die_name_len + 2
20917                           && actual_name[actual_name_len
20918                                          - die_name_len - 1] == ':')
20919                         name = (char *) obstack_copy0 (
20920                           &cu->objfile->per_bfd->storage_obstack,
20921                           actual_name, actual_name_len - die_name_len - 2);
20922                     }
20923                 }
20924               xfree (actual_name);
20925               return name;
20926             }
20927         }
20928     }
20929
20930   return NULL;
20931 }
20932
20933 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20934    prefix part in such case.  See
20935    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20936
20937 static const char *
20938 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20939 {
20940   struct attribute *attr;
20941   const char *base;
20942
20943   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20944       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20945     return NULL;
20946
20947   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20948     return NULL;
20949
20950   attr = dw2_linkage_name_attr (die, cu);
20951   if (attr == NULL || DW_STRING (attr) == NULL)
20952     return NULL;
20953
20954   /* dwarf2_name had to be already called.  */
20955   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20956
20957   /* Strip the base name, keep any leading namespaces/classes.  */
20958   base = strrchr (DW_STRING (attr), ':');
20959   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20960     return "";
20961
20962   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20963                                  DW_STRING (attr),
20964                                  &base[-1] - DW_STRING (attr));
20965 }
20966
20967 /* Return the name of the namespace/class that DIE is defined within,
20968    or "" if we can't tell.  The caller should not xfree the result.
20969
20970    For example, if we're within the method foo() in the following
20971    code:
20972
20973    namespace N {
20974      class C {
20975        void foo () {
20976        }
20977      };
20978    }
20979
20980    then determine_prefix on foo's die will return "N::C".  */
20981
20982 static const char *
20983 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20984 {
20985   struct die_info *parent, *spec_die;
20986   struct dwarf2_cu *spec_cu;
20987   struct type *parent_type;
20988   const char *retval;
20989
20990   if (cu->language != language_cplus
20991       && cu->language != language_fortran && cu->language != language_d
20992       && cu->language != language_rust)
20993     return "";
20994
20995   retval = anonymous_struct_prefix (die, cu);
20996   if (retval)
20997     return retval;
20998
20999   /* We have to be careful in the presence of DW_AT_specification.
21000      For example, with GCC 3.4, given the code
21001
21002      namespace N {
21003        void foo() {
21004          // Definition of N::foo.
21005        }
21006      }
21007
21008      then we'll have a tree of DIEs like this:
21009
21010      1: DW_TAG_compile_unit
21011        2: DW_TAG_namespace        // N
21012          3: DW_TAG_subprogram     // declaration of N::foo
21013        4: DW_TAG_subprogram       // definition of N::foo
21014             DW_AT_specification   // refers to die #3
21015
21016      Thus, when processing die #4, we have to pretend that we're in
21017      the context of its DW_AT_specification, namely the contex of die
21018      #3.  */
21019   spec_cu = cu;
21020   spec_die = die_specification (die, &spec_cu);
21021   if (spec_die == NULL)
21022     parent = die->parent;
21023   else
21024     {
21025       parent = spec_die->parent;
21026       cu = spec_cu;
21027     }
21028
21029   if (parent == NULL)
21030     return "";
21031   else if (parent->building_fullname)
21032     {
21033       const char *name;
21034       const char *parent_name;
21035
21036       /* It has been seen on RealView 2.2 built binaries,
21037          DW_TAG_template_type_param types actually _defined_ as
21038          children of the parent class:
21039
21040          enum E {};
21041          template class <class Enum> Class{};
21042          Class<enum E> class_e;
21043
21044          1: DW_TAG_class_type (Class)
21045            2: DW_TAG_enumeration_type (E)
21046              3: DW_TAG_enumerator (enum1:0)
21047              3: DW_TAG_enumerator (enum2:1)
21048              ...
21049            2: DW_TAG_template_type_param
21050               DW_AT_type  DW_FORM_ref_udata (E)
21051
21052          Besides being broken debug info, it can put GDB into an
21053          infinite loop.  Consider:
21054
21055          When we're building the full name for Class<E>, we'll start
21056          at Class, and go look over its template type parameters,
21057          finding E.  We'll then try to build the full name of E, and
21058          reach here.  We're now trying to build the full name of E,
21059          and look over the parent DIE for containing scope.  In the
21060          broken case, if we followed the parent DIE of E, we'd again
21061          find Class, and once again go look at its template type
21062          arguments, etc., etc.  Simply don't consider such parent die
21063          as source-level parent of this die (it can't be, the language
21064          doesn't allow it), and break the loop here.  */
21065       name = dwarf2_name (die, cu);
21066       parent_name = dwarf2_name (parent, cu);
21067       complaint (&symfile_complaints,
21068                  _("template param type '%s' defined within parent '%s'"),
21069                  name ? name : "<unknown>",
21070                  parent_name ? parent_name : "<unknown>");
21071       return "";
21072     }
21073   else
21074     switch (parent->tag)
21075       {
21076       case DW_TAG_namespace:
21077         parent_type = read_type_die (parent, cu);
21078         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
21079            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
21080            Work around this problem here.  */
21081         if (cu->language == language_cplus
21082             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
21083           return "";
21084         /* We give a name to even anonymous namespaces.  */
21085         return TYPE_TAG_NAME (parent_type);
21086       case DW_TAG_class_type:
21087       case DW_TAG_interface_type:
21088       case DW_TAG_structure_type:
21089       case DW_TAG_union_type:
21090       case DW_TAG_module:
21091         parent_type = read_type_die (parent, cu);
21092         if (TYPE_TAG_NAME (parent_type) != NULL)
21093           return TYPE_TAG_NAME (parent_type);
21094         else
21095           /* An anonymous structure is only allowed non-static data
21096              members; no typedefs, no member functions, et cetera.
21097              So it does not need a prefix.  */
21098           return "";
21099       case DW_TAG_compile_unit:
21100       case DW_TAG_partial_unit:
21101         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
21102         if (cu->language == language_cplus
21103             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
21104             && die->child != NULL
21105             && (die->tag == DW_TAG_class_type
21106                 || die->tag == DW_TAG_structure_type
21107                 || die->tag == DW_TAG_union_type))
21108           {
21109             char *name = guess_full_die_structure_name (die, cu);
21110             if (name != NULL)
21111               return name;
21112           }
21113         return "";
21114       case DW_TAG_enumeration_type:
21115         parent_type = read_type_die (parent, cu);
21116         if (TYPE_DECLARED_CLASS (parent_type))
21117           {
21118             if (TYPE_TAG_NAME (parent_type) != NULL)
21119               return TYPE_TAG_NAME (parent_type);
21120             return "";
21121           }
21122         /* Fall through.  */
21123       default:
21124         return determine_prefix (parent, cu);
21125       }
21126 }
21127
21128 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
21129    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
21130    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
21131    an obconcat, otherwise allocate storage for the result.  The CU argument is
21132    used to determine the language and hence, the appropriate separator.  */
21133
21134 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
21135
21136 static char *
21137 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
21138                  int physname, struct dwarf2_cu *cu)
21139 {
21140   const char *lead = "";
21141   const char *sep;
21142
21143   if (suffix == NULL || suffix[0] == '\0'
21144       || prefix == NULL || prefix[0] == '\0')
21145     sep = "";
21146   else if (cu->language == language_d)
21147     {
21148       /* For D, the 'main' function could be defined in any module, but it
21149          should never be prefixed.  */
21150       if (strcmp (suffix, "D main") == 0)
21151         {
21152           prefix = "";
21153           sep = "";
21154         }
21155       else
21156         sep = ".";
21157     }
21158   else if (cu->language == language_fortran && physname)
21159     {
21160       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
21161          DW_AT_MIPS_linkage_name is preferred and used instead.  */
21162
21163       lead = "__";
21164       sep = "_MOD_";
21165     }
21166   else
21167     sep = "::";
21168
21169   if (prefix == NULL)
21170     prefix = "";
21171   if (suffix == NULL)
21172     suffix = "";
21173
21174   if (obs == NULL)
21175     {
21176       char *retval
21177         = ((char *)
21178            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
21179
21180       strcpy (retval, lead);
21181       strcat (retval, prefix);
21182       strcat (retval, sep);
21183       strcat (retval, suffix);
21184       return retval;
21185     }
21186   else
21187     {
21188       /* We have an obstack.  */
21189       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
21190     }
21191 }
21192
21193 /* Return sibling of die, NULL if no sibling.  */
21194
21195 static struct die_info *
21196 sibling_die (struct die_info *die)
21197 {
21198   return die->sibling;
21199 }
21200
21201 /* Get name of a die, return NULL if not found.  */
21202
21203 static const char *
21204 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
21205                           struct obstack *obstack)
21206 {
21207   if (name && cu->language == language_cplus)
21208     {
21209       std::string canon_name = cp_canonicalize_string (name);
21210
21211       if (!canon_name.empty ())
21212         {
21213           if (canon_name != name)
21214             name = (const char *) obstack_copy0 (obstack,
21215                                                  canon_name.c_str (),
21216                                                  canon_name.length ());
21217         }
21218     }
21219
21220   return name;
21221 }
21222
21223 /* Get name of a die, return NULL if not found.
21224    Anonymous namespaces are converted to their magic string.  */
21225
21226 static const char *
21227 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
21228 {
21229   struct attribute *attr;
21230
21231   attr = dwarf2_attr (die, DW_AT_name, cu);
21232   if ((!attr || !DW_STRING (attr))
21233       && die->tag != DW_TAG_namespace
21234       && die->tag != DW_TAG_class_type
21235       && die->tag != DW_TAG_interface_type
21236       && die->tag != DW_TAG_structure_type
21237       && die->tag != DW_TAG_union_type)
21238     return NULL;
21239
21240   switch (die->tag)
21241     {
21242     case DW_TAG_compile_unit:
21243     case DW_TAG_partial_unit:
21244       /* Compilation units have a DW_AT_name that is a filename, not
21245          a source language identifier.  */
21246     case DW_TAG_enumeration_type:
21247     case DW_TAG_enumerator:
21248       /* These tags always have simple identifiers already; no need
21249          to canonicalize them.  */
21250       return DW_STRING (attr);
21251
21252     case DW_TAG_namespace:
21253       if (attr != NULL && DW_STRING (attr) != NULL)
21254         return DW_STRING (attr);
21255       return CP_ANONYMOUS_NAMESPACE_STR;
21256
21257     case DW_TAG_class_type:
21258     case DW_TAG_interface_type:
21259     case DW_TAG_structure_type:
21260     case DW_TAG_union_type:
21261       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
21262          structures or unions.  These were of the form "._%d" in GCC 4.1,
21263          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
21264          and GCC 4.4.  We work around this problem by ignoring these.  */
21265       if (attr && DW_STRING (attr)
21266           && (startswith (DW_STRING (attr), "._")
21267               || startswith (DW_STRING (attr), "<anonymous")))
21268         return NULL;
21269
21270       /* GCC might emit a nameless typedef that has a linkage name.  See
21271          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
21272       if (!attr || DW_STRING (attr) == NULL)
21273         {
21274           char *demangled = NULL;
21275
21276           attr = dw2_linkage_name_attr (die, cu);
21277           if (attr == NULL || DW_STRING (attr) == NULL)
21278             return NULL;
21279
21280           /* Avoid demangling DW_STRING (attr) the second time on a second
21281              call for the same DIE.  */
21282           if (!DW_STRING_IS_CANONICAL (attr))
21283             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
21284
21285           if (demangled)
21286             {
21287               const char *base;
21288
21289               /* FIXME: we already did this for the partial symbol... */
21290               DW_STRING (attr)
21291                 = ((const char *)
21292                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
21293                                   demangled, strlen (demangled)));
21294               DW_STRING_IS_CANONICAL (attr) = 1;
21295               xfree (demangled);
21296
21297               /* Strip any leading namespaces/classes, keep only the base name.
21298                  DW_AT_name for named DIEs does not contain the prefixes.  */
21299               base = strrchr (DW_STRING (attr), ':');
21300               if (base && base > DW_STRING (attr) && base[-1] == ':')
21301                 return &base[1];
21302               else
21303                 return DW_STRING (attr);
21304             }
21305         }
21306       break;
21307
21308     default:
21309       break;
21310     }
21311
21312   if (!DW_STRING_IS_CANONICAL (attr))
21313     {
21314       DW_STRING (attr)
21315         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
21316                                     &cu->objfile->per_bfd->storage_obstack);
21317       DW_STRING_IS_CANONICAL (attr) = 1;
21318     }
21319   return DW_STRING (attr);
21320 }
21321
21322 /* Return the die that this die in an extension of, or NULL if there
21323    is none.  *EXT_CU is the CU containing DIE on input, and the CU
21324    containing the return value on output.  */
21325
21326 static struct die_info *
21327 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
21328 {
21329   struct attribute *attr;
21330
21331   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
21332   if (attr == NULL)
21333     return NULL;
21334
21335   return follow_die_ref (die, attr, ext_cu);
21336 }
21337
21338 /* Convert a DIE tag into its string name.  */
21339
21340 static const char *
21341 dwarf_tag_name (unsigned tag)
21342 {
21343   const char *name = get_DW_TAG_name (tag);
21344
21345   if (name == NULL)
21346     return "DW_TAG_<unknown>";
21347
21348   return name;
21349 }
21350
21351 /* Convert a DWARF attribute code into its string name.  */
21352
21353 static const char *
21354 dwarf_attr_name (unsigned attr)
21355 {
21356   const char *name;
21357
21358 #ifdef MIPS /* collides with DW_AT_HP_block_index */
21359   if (attr == DW_AT_MIPS_fde)
21360     return "DW_AT_MIPS_fde";
21361 #else
21362   if (attr == DW_AT_HP_block_index)
21363     return "DW_AT_HP_block_index";
21364 #endif
21365
21366   name = get_DW_AT_name (attr);
21367
21368   if (name == NULL)
21369     return "DW_AT_<unknown>";
21370
21371   return name;
21372 }
21373
21374 /* Convert a DWARF value form code into its string name.  */
21375
21376 static const char *
21377 dwarf_form_name (unsigned form)
21378 {
21379   const char *name = get_DW_FORM_name (form);
21380
21381   if (name == NULL)
21382     return "DW_FORM_<unknown>";
21383
21384   return name;
21385 }
21386
21387 static const char *
21388 dwarf_bool_name (unsigned mybool)
21389 {
21390   if (mybool)
21391     return "TRUE";
21392   else
21393     return "FALSE";
21394 }
21395
21396 /* Convert a DWARF type code into its string name.  */
21397
21398 static const char *
21399 dwarf_type_encoding_name (unsigned enc)
21400 {
21401   const char *name = get_DW_ATE_name (enc);
21402
21403   if (name == NULL)
21404     return "DW_ATE_<unknown>";
21405
21406   return name;
21407 }
21408
21409 static void
21410 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
21411 {
21412   unsigned int i;
21413
21414   print_spaces (indent, f);
21415   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
21416                       dwarf_tag_name (die->tag), die->abbrev,
21417                       to_underlying (die->sect_off));
21418
21419   if (die->parent != NULL)
21420     {
21421       print_spaces (indent, f);
21422       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
21423                           to_underlying (die->parent->sect_off));
21424     }
21425
21426   print_spaces (indent, f);
21427   fprintf_unfiltered (f, "  has children: %s\n",
21428            dwarf_bool_name (die->child != NULL));
21429
21430   print_spaces (indent, f);
21431   fprintf_unfiltered (f, "  attributes:\n");
21432
21433   for (i = 0; i < die->num_attrs; ++i)
21434     {
21435       print_spaces (indent, f);
21436       fprintf_unfiltered (f, "    %s (%s) ",
21437                dwarf_attr_name (die->attrs[i].name),
21438                dwarf_form_name (die->attrs[i].form));
21439
21440       switch (die->attrs[i].form)
21441         {
21442         case DW_FORM_addr:
21443         case DW_FORM_GNU_addr_index:
21444           fprintf_unfiltered (f, "address: ");
21445           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
21446           break;
21447         case DW_FORM_block2:
21448         case DW_FORM_block4:
21449         case DW_FORM_block:
21450         case DW_FORM_block1:
21451           fprintf_unfiltered (f, "block: size %s",
21452                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21453           break;
21454         case DW_FORM_exprloc:
21455           fprintf_unfiltered (f, "expression: size %s",
21456                               pulongest (DW_BLOCK (&die->attrs[i])->size));
21457           break;
21458         case DW_FORM_data16:
21459           fprintf_unfiltered (f, "constant of 16 bytes");
21460           break;
21461         case DW_FORM_ref_addr:
21462           fprintf_unfiltered (f, "ref address: ");
21463           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21464           break;
21465         case DW_FORM_GNU_ref_alt:
21466           fprintf_unfiltered (f, "alt ref address: ");
21467           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
21468           break;
21469         case DW_FORM_ref1:
21470         case DW_FORM_ref2:
21471         case DW_FORM_ref4:
21472         case DW_FORM_ref8:
21473         case DW_FORM_ref_udata:
21474           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
21475                               (long) (DW_UNSND (&die->attrs[i])));
21476           break;
21477         case DW_FORM_data1:
21478         case DW_FORM_data2:
21479         case DW_FORM_data4:
21480         case DW_FORM_data8:
21481         case DW_FORM_udata:
21482         case DW_FORM_sdata:
21483           fprintf_unfiltered (f, "constant: %s",
21484                               pulongest (DW_UNSND (&die->attrs[i])));
21485           break;
21486         case DW_FORM_sec_offset:
21487           fprintf_unfiltered (f, "section offset: %s",
21488                               pulongest (DW_UNSND (&die->attrs[i])));
21489           break;
21490         case DW_FORM_ref_sig8:
21491           fprintf_unfiltered (f, "signature: %s",
21492                               hex_string (DW_SIGNATURE (&die->attrs[i])));
21493           break;
21494         case DW_FORM_string:
21495         case DW_FORM_strp:
21496         case DW_FORM_line_strp:
21497         case DW_FORM_GNU_str_index:
21498         case DW_FORM_GNU_strp_alt:
21499           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
21500                    DW_STRING (&die->attrs[i])
21501                    ? DW_STRING (&die->attrs[i]) : "",
21502                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
21503           break;
21504         case DW_FORM_flag:
21505           if (DW_UNSND (&die->attrs[i]))
21506             fprintf_unfiltered (f, "flag: TRUE");
21507           else
21508             fprintf_unfiltered (f, "flag: FALSE");
21509           break;
21510         case DW_FORM_flag_present:
21511           fprintf_unfiltered (f, "flag: TRUE");
21512           break;
21513         case DW_FORM_indirect:
21514           /* The reader will have reduced the indirect form to
21515              the "base form" so this form should not occur.  */
21516           fprintf_unfiltered (f, 
21517                               "unexpected attribute form: DW_FORM_indirect");
21518           break;
21519         case DW_FORM_implicit_const:
21520           fprintf_unfiltered (f, "constant: %s",
21521                               plongest (DW_SND (&die->attrs[i])));
21522           break;
21523         default:
21524           fprintf_unfiltered (f, "unsupported attribute form: %d.",
21525                    die->attrs[i].form);
21526           break;
21527         }
21528       fprintf_unfiltered (f, "\n");
21529     }
21530 }
21531
21532 static void
21533 dump_die_for_error (struct die_info *die)
21534 {
21535   dump_die_shallow (gdb_stderr, 0, die);
21536 }
21537
21538 static void
21539 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
21540 {
21541   int indent = level * 4;
21542
21543   gdb_assert (die != NULL);
21544
21545   if (level >= max_level)
21546     return;
21547
21548   dump_die_shallow (f, indent, die);
21549
21550   if (die->child != NULL)
21551     {
21552       print_spaces (indent, f);
21553       fprintf_unfiltered (f, "  Children:");
21554       if (level + 1 < max_level)
21555         {
21556           fprintf_unfiltered (f, "\n");
21557           dump_die_1 (f, level + 1, max_level, die->child);
21558         }
21559       else
21560         {
21561           fprintf_unfiltered (f,
21562                               " [not printed, max nesting level reached]\n");
21563         }
21564     }
21565
21566   if (die->sibling != NULL && level > 0)
21567     {
21568       dump_die_1 (f, level, max_level, die->sibling);
21569     }
21570 }
21571
21572 /* This is called from the pdie macro in gdbinit.in.
21573    It's not static so gcc will keep a copy callable from gdb.  */
21574
21575 void
21576 dump_die (struct die_info *die, int max_level)
21577 {
21578   dump_die_1 (gdb_stdlog, 0, max_level, die);
21579 }
21580
21581 static void
21582 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
21583 {
21584   void **slot;
21585
21586   slot = htab_find_slot_with_hash (cu->die_hash, die,
21587                                    to_underlying (die->sect_off),
21588                                    INSERT);
21589
21590   *slot = die;
21591 }
21592
21593 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
21594    required kind.  */
21595
21596 static sect_offset
21597 dwarf2_get_ref_die_offset (const struct attribute *attr)
21598 {
21599   if (attr_form_is_ref (attr))
21600     return (sect_offset) DW_UNSND (attr);
21601
21602   complaint (&symfile_complaints,
21603              _("unsupported die ref attribute form: '%s'"),
21604              dwarf_form_name (attr->form));
21605   return {};
21606 }
21607
21608 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
21609  * the value held by the attribute is not constant.  */
21610
21611 static LONGEST
21612 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
21613 {
21614   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
21615     return DW_SND (attr);
21616   else if (attr->form == DW_FORM_udata
21617            || attr->form == DW_FORM_data1
21618            || attr->form == DW_FORM_data2
21619            || attr->form == DW_FORM_data4
21620            || attr->form == DW_FORM_data8)
21621     return DW_UNSND (attr);
21622   else
21623     {
21624       /* For DW_FORM_data16 see attr_form_is_constant.  */
21625       complaint (&symfile_complaints,
21626                  _("Attribute value is not a constant (%s)"),
21627                  dwarf_form_name (attr->form));
21628       return default_value;
21629     }
21630 }
21631
21632 /* Follow reference or signature attribute ATTR of SRC_DIE.
21633    On entry *REF_CU is the CU of SRC_DIE.
21634    On exit *REF_CU is the CU of the result.  */
21635
21636 static struct die_info *
21637 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
21638                        struct dwarf2_cu **ref_cu)
21639 {
21640   struct die_info *die;
21641
21642   if (attr_form_is_ref (attr))
21643     die = follow_die_ref (src_die, attr, ref_cu);
21644   else if (attr->form == DW_FORM_ref_sig8)
21645     die = follow_die_sig (src_die, attr, ref_cu);
21646   else
21647     {
21648       dump_die_for_error (src_die);
21649       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
21650              objfile_name ((*ref_cu)->objfile));
21651     }
21652
21653   return die;
21654 }
21655
21656 /* Follow reference OFFSET.
21657    On entry *REF_CU is the CU of the source die referencing OFFSET.
21658    On exit *REF_CU is the CU of the result.
21659    Returns NULL if OFFSET is invalid.  */
21660
21661 static struct die_info *
21662 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
21663                    struct dwarf2_cu **ref_cu)
21664 {
21665   struct die_info temp_die;
21666   struct dwarf2_cu *target_cu, *cu = *ref_cu;
21667
21668   gdb_assert (cu->per_cu != NULL);
21669
21670   target_cu = cu;
21671
21672   if (cu->per_cu->is_debug_types)
21673     {
21674       /* .debug_types CUs cannot reference anything outside their CU.
21675          If they need to, they have to reference a signatured type via
21676          DW_FORM_ref_sig8.  */
21677       if (!offset_in_cu_p (&cu->header, sect_off))
21678         return NULL;
21679     }
21680   else if (offset_in_dwz != cu->per_cu->is_dwz
21681            || !offset_in_cu_p (&cu->header, sect_off))
21682     {
21683       struct dwarf2_per_cu_data *per_cu;
21684
21685       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
21686                                                  cu->objfile);
21687
21688       /* If necessary, add it to the queue and load its DIEs.  */
21689       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
21690         load_full_comp_unit (per_cu, cu->language);
21691
21692       target_cu = per_cu->cu;
21693     }
21694   else if (cu->dies == NULL)
21695     {
21696       /* We're loading full DIEs during partial symbol reading.  */
21697       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21698       load_full_comp_unit (cu->per_cu, language_minimal);
21699     }
21700
21701   *ref_cu = target_cu;
21702   temp_die.sect_off = sect_off;
21703   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21704                                                   &temp_die,
21705                                                   to_underlying (sect_off));
21706 }
21707
21708 /* Follow reference attribute ATTR of SRC_DIE.
21709    On entry *REF_CU is the CU of SRC_DIE.
21710    On exit *REF_CU is the CU of the result.  */
21711
21712 static struct die_info *
21713 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21714                 struct dwarf2_cu **ref_cu)
21715 {
21716   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21717   struct dwarf2_cu *cu = *ref_cu;
21718   struct die_info *die;
21719
21720   die = follow_die_offset (sect_off,
21721                            (attr->form == DW_FORM_GNU_ref_alt
21722                             || cu->per_cu->is_dwz),
21723                            ref_cu);
21724   if (!die)
21725     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21726            "at 0x%x [in module %s]"),
21727            to_underlying (sect_off), to_underlying (src_die->sect_off),
21728            objfile_name (cu->objfile));
21729
21730   return die;
21731 }
21732
21733 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21734    Returned value is intended for DW_OP_call*.  Returned
21735    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21736
21737 struct dwarf2_locexpr_baton
21738 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21739                                struct dwarf2_per_cu_data *per_cu,
21740                                CORE_ADDR (*get_frame_pc) (void *baton),
21741                                void *baton)
21742 {
21743   struct dwarf2_cu *cu;
21744   struct die_info *die;
21745   struct attribute *attr;
21746   struct dwarf2_locexpr_baton retval;
21747
21748   dw2_setup (per_cu->objfile);
21749
21750   if (per_cu->cu == NULL)
21751     load_cu (per_cu);
21752   cu = per_cu->cu;
21753   if (cu == NULL)
21754     {
21755       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21756          Instead just throw an error, not much else we can do.  */
21757       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21758              to_underlying (sect_off), objfile_name (per_cu->objfile));
21759     }
21760
21761   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21762   if (!die)
21763     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21764            to_underlying (sect_off), objfile_name (per_cu->objfile));
21765
21766   attr = dwarf2_attr (die, DW_AT_location, cu);
21767   if (!attr)
21768     {
21769       /* DWARF: "If there is no such attribute, then there is no effect.".
21770          DATA is ignored if SIZE is 0.  */
21771
21772       retval.data = NULL;
21773       retval.size = 0;
21774     }
21775   else if (attr_form_is_section_offset (attr))
21776     {
21777       struct dwarf2_loclist_baton loclist_baton;
21778       CORE_ADDR pc = (*get_frame_pc) (baton);
21779       size_t size;
21780
21781       fill_in_loclist_baton (cu, &loclist_baton, attr);
21782
21783       retval.data = dwarf2_find_location_expression (&loclist_baton,
21784                                                      &size, pc);
21785       retval.size = size;
21786     }
21787   else
21788     {
21789       if (!attr_form_is_block (attr))
21790         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21791                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21792                to_underlying (sect_off), objfile_name (per_cu->objfile));
21793
21794       retval.data = DW_BLOCK (attr)->data;
21795       retval.size = DW_BLOCK (attr)->size;
21796     }
21797   retval.per_cu = cu->per_cu;
21798
21799   age_cached_comp_units ();
21800
21801   return retval;
21802 }
21803
21804 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21805    offset.  */
21806
21807 struct dwarf2_locexpr_baton
21808 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21809                              struct dwarf2_per_cu_data *per_cu,
21810                              CORE_ADDR (*get_frame_pc) (void *baton),
21811                              void *baton)
21812 {
21813   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21814
21815   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21816 }
21817
21818 /* Write a constant of a given type as target-ordered bytes into
21819    OBSTACK.  */
21820
21821 static const gdb_byte *
21822 write_constant_as_bytes (struct obstack *obstack,
21823                          enum bfd_endian byte_order,
21824                          struct type *type,
21825                          ULONGEST value,
21826                          LONGEST *len)
21827 {
21828   gdb_byte *result;
21829
21830   *len = TYPE_LENGTH (type);
21831   result = (gdb_byte *) obstack_alloc (obstack, *len);
21832   store_unsigned_integer (result, *len, byte_order, value);
21833
21834   return result;
21835 }
21836
21837 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21838    pointer to the constant bytes and set LEN to the length of the
21839    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21840    does not have a DW_AT_const_value, return NULL.  */
21841
21842 const gdb_byte *
21843 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21844                              struct dwarf2_per_cu_data *per_cu,
21845                              struct obstack *obstack,
21846                              LONGEST *len)
21847 {
21848   struct dwarf2_cu *cu;
21849   struct die_info *die;
21850   struct attribute *attr;
21851   const gdb_byte *result = NULL;
21852   struct type *type;
21853   LONGEST value;
21854   enum bfd_endian byte_order;
21855
21856   dw2_setup (per_cu->objfile);
21857
21858   if (per_cu->cu == NULL)
21859     load_cu (per_cu);
21860   cu = per_cu->cu;
21861   if (cu == NULL)
21862     {
21863       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21864          Instead just throw an error, not much else we can do.  */
21865       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21866              to_underlying (sect_off), objfile_name (per_cu->objfile));
21867     }
21868
21869   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21870   if (!die)
21871     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21872            to_underlying (sect_off), objfile_name (per_cu->objfile));
21873
21874
21875   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21876   if (attr == NULL)
21877     return NULL;
21878
21879   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21880                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21881
21882   switch (attr->form)
21883     {
21884     case DW_FORM_addr:
21885     case DW_FORM_GNU_addr_index:
21886       {
21887         gdb_byte *tem;
21888
21889         *len = cu->header.addr_size;
21890         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21891         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21892         result = tem;
21893       }
21894       break;
21895     case DW_FORM_string:
21896     case DW_FORM_strp:
21897     case DW_FORM_GNU_str_index:
21898     case DW_FORM_GNU_strp_alt:
21899       /* DW_STRING is already allocated on the objfile obstack, point
21900          directly to it.  */
21901       result = (const gdb_byte *) DW_STRING (attr);
21902       *len = strlen (DW_STRING (attr));
21903       break;
21904     case DW_FORM_block1:
21905     case DW_FORM_block2:
21906     case DW_FORM_block4:
21907     case DW_FORM_block:
21908     case DW_FORM_exprloc:
21909     case DW_FORM_data16:
21910       result = DW_BLOCK (attr)->data;
21911       *len = DW_BLOCK (attr)->size;
21912       break;
21913
21914       /* The DW_AT_const_value attributes are supposed to carry the
21915          symbol's value "represented as it would be on the target
21916          architecture."  By the time we get here, it's already been
21917          converted to host endianness, so we just need to sign- or
21918          zero-extend it as appropriate.  */
21919     case DW_FORM_data1:
21920       type = die_type (die, cu);
21921       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21922       if (result == NULL)
21923         result = write_constant_as_bytes (obstack, byte_order,
21924                                           type, value, len);
21925       break;
21926     case DW_FORM_data2:
21927       type = die_type (die, cu);
21928       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21929       if (result == NULL)
21930         result = write_constant_as_bytes (obstack, byte_order,
21931                                           type, value, len);
21932       break;
21933     case DW_FORM_data4:
21934       type = die_type (die, cu);
21935       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21936       if (result == NULL)
21937         result = write_constant_as_bytes (obstack, byte_order,
21938                                           type, value, len);
21939       break;
21940     case DW_FORM_data8:
21941       type = die_type (die, cu);
21942       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21943       if (result == NULL)
21944         result = write_constant_as_bytes (obstack, byte_order,
21945                                           type, value, len);
21946       break;
21947
21948     case DW_FORM_sdata:
21949     case DW_FORM_implicit_const:
21950       type = die_type (die, cu);
21951       result = write_constant_as_bytes (obstack, byte_order,
21952                                         type, DW_SND (attr), len);
21953       break;
21954
21955     case DW_FORM_udata:
21956       type = die_type (die, cu);
21957       result = write_constant_as_bytes (obstack, byte_order,
21958                                         type, DW_UNSND (attr), len);
21959       break;
21960
21961     default:
21962       complaint (&symfile_complaints,
21963                  _("unsupported const value attribute form: '%s'"),
21964                  dwarf_form_name (attr->form));
21965       break;
21966     }
21967
21968   return result;
21969 }
21970
21971 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21972    valid type for this die is found.  */
21973
21974 struct type *
21975 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21976                                 struct dwarf2_per_cu_data *per_cu)
21977 {
21978   struct dwarf2_cu *cu;
21979   struct die_info *die;
21980
21981   dw2_setup (per_cu->objfile);
21982
21983   if (per_cu->cu == NULL)
21984     load_cu (per_cu);
21985   cu = per_cu->cu;
21986   if (!cu)
21987     return NULL;
21988
21989   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21990   if (!die)
21991     return NULL;
21992
21993   return die_type (die, cu);
21994 }
21995
21996 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21997    PER_CU.  */
21998
21999 struct type *
22000 dwarf2_get_die_type (cu_offset die_offset,
22001                      struct dwarf2_per_cu_data *per_cu)
22002 {
22003   dw2_setup (per_cu->objfile);
22004
22005   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
22006   return get_die_type_at_offset (die_offset_sect, per_cu);
22007 }
22008
22009 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
22010    On entry *REF_CU is the CU of SRC_DIE.
22011    On exit *REF_CU is the CU of the result.
22012    Returns NULL if the referenced DIE isn't found.  */
22013
22014 static struct die_info *
22015 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
22016                   struct dwarf2_cu **ref_cu)
22017 {
22018   struct die_info temp_die;
22019   struct dwarf2_cu *sig_cu;
22020   struct die_info *die;
22021
22022   /* While it might be nice to assert sig_type->type == NULL here,
22023      we can get here for DW_AT_imported_declaration where we need
22024      the DIE not the type.  */
22025
22026   /* If necessary, add it to the queue and load its DIEs.  */
22027
22028   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
22029     read_signatured_type (sig_type);
22030
22031   sig_cu = sig_type->per_cu.cu;
22032   gdb_assert (sig_cu != NULL);
22033   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
22034   temp_die.sect_off = sig_type->type_offset_in_section;
22035   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
22036                                                  to_underlying (temp_die.sect_off));
22037   if (die)
22038     {
22039       /* For .gdb_index version 7 keep track of included TUs.
22040          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
22041       if (dwarf2_per_objfile->index_table != NULL
22042           && dwarf2_per_objfile->index_table->version <= 7)
22043         {
22044           VEC_safe_push (dwarf2_per_cu_ptr,
22045                          (*ref_cu)->per_cu->imported_symtabs,
22046                          sig_cu->per_cu);
22047         }
22048
22049       *ref_cu = sig_cu;
22050       return die;
22051     }
22052
22053   return NULL;
22054 }
22055
22056 /* Follow signatured type referenced by ATTR in SRC_DIE.
22057    On entry *REF_CU is the CU of SRC_DIE.
22058    On exit *REF_CU is the CU of the result.
22059    The result is the DIE of the type.
22060    If the referenced type cannot be found an error is thrown.  */
22061
22062 static struct die_info *
22063 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
22064                 struct dwarf2_cu **ref_cu)
22065 {
22066   ULONGEST signature = DW_SIGNATURE (attr);
22067   struct signatured_type *sig_type;
22068   struct die_info *die;
22069
22070   gdb_assert (attr->form == DW_FORM_ref_sig8);
22071
22072   sig_type = lookup_signatured_type (*ref_cu, signature);
22073   /* sig_type will be NULL if the signatured type is missing from
22074      the debug info.  */
22075   if (sig_type == NULL)
22076     {
22077       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
22078                " from DIE at 0x%x [in module %s]"),
22079              hex_string (signature), to_underlying (src_die->sect_off),
22080              objfile_name ((*ref_cu)->objfile));
22081     }
22082
22083   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
22084   if (die == NULL)
22085     {
22086       dump_die_for_error (src_die);
22087       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
22088                " from DIE at 0x%x [in module %s]"),
22089              hex_string (signature), to_underlying (src_die->sect_off),
22090              objfile_name ((*ref_cu)->objfile));
22091     }
22092
22093   return die;
22094 }
22095
22096 /* Get the type specified by SIGNATURE referenced in DIE/CU,
22097    reading in and processing the type unit if necessary.  */
22098
22099 static struct type *
22100 get_signatured_type (struct die_info *die, ULONGEST signature,
22101                      struct dwarf2_cu *cu)
22102 {
22103   struct signatured_type *sig_type;
22104   struct dwarf2_cu *type_cu;
22105   struct die_info *type_die;
22106   struct type *type;
22107
22108   sig_type = lookup_signatured_type (cu, signature);
22109   /* sig_type will be NULL if the signatured type is missing from
22110      the debug info.  */
22111   if (sig_type == NULL)
22112     {
22113       complaint (&symfile_complaints,
22114                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
22115                    " from DIE at 0x%x [in module %s]"),
22116                  hex_string (signature), to_underlying (die->sect_off),
22117                  objfile_name (dwarf2_per_objfile->objfile));
22118       return build_error_marker_type (cu, die);
22119     }
22120
22121   /* If we already know the type we're done.  */
22122   if (sig_type->type != NULL)
22123     return sig_type->type;
22124
22125   type_cu = cu;
22126   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
22127   if (type_die != NULL)
22128     {
22129       /* N.B. We need to call get_die_type to ensure only one type for this DIE
22130          is created.  This is important, for example, because for c++ classes
22131          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
22132       type = read_type_die (type_die, type_cu);
22133       if (type == NULL)
22134         {
22135           complaint (&symfile_complaints,
22136                      _("Dwarf Error: Cannot build signatured type %s"
22137                        " referenced from DIE at 0x%x [in module %s]"),
22138                      hex_string (signature), to_underlying (die->sect_off),
22139                      objfile_name (dwarf2_per_objfile->objfile));
22140           type = build_error_marker_type (cu, die);
22141         }
22142     }
22143   else
22144     {
22145       complaint (&symfile_complaints,
22146                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
22147                    " from DIE at 0x%x [in module %s]"),
22148                  hex_string (signature), to_underlying (die->sect_off),
22149                  objfile_name (dwarf2_per_objfile->objfile));
22150       type = build_error_marker_type (cu, die);
22151     }
22152   sig_type->type = type;
22153
22154   return type;
22155 }
22156
22157 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
22158    reading in and processing the type unit if necessary.  */
22159
22160 static struct type *
22161 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
22162                           struct dwarf2_cu *cu) /* ARI: editCase function */
22163 {
22164   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
22165   if (attr_form_is_ref (attr))
22166     {
22167       struct dwarf2_cu *type_cu = cu;
22168       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
22169
22170       return read_type_die (type_die, type_cu);
22171     }
22172   else if (attr->form == DW_FORM_ref_sig8)
22173     {
22174       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
22175     }
22176   else
22177     {
22178       complaint (&symfile_complaints,
22179                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
22180                    " at 0x%x [in module %s]"),
22181                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
22182                  objfile_name (dwarf2_per_objfile->objfile));
22183       return build_error_marker_type (cu, die);
22184     }
22185 }
22186
22187 /* Load the DIEs associated with type unit PER_CU into memory.  */
22188
22189 static void
22190 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
22191 {
22192   struct signatured_type *sig_type;
22193
22194   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
22195   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
22196
22197   /* We have the per_cu, but we need the signatured_type.
22198      Fortunately this is an easy translation.  */
22199   gdb_assert (per_cu->is_debug_types);
22200   sig_type = (struct signatured_type *) per_cu;
22201
22202   gdb_assert (per_cu->cu == NULL);
22203
22204   read_signatured_type (sig_type);
22205
22206   gdb_assert (per_cu->cu != NULL);
22207 }
22208
22209 /* die_reader_func for read_signatured_type.
22210    This is identical to load_full_comp_unit_reader,
22211    but is kept separate for now.  */
22212
22213 static void
22214 read_signatured_type_reader (const struct die_reader_specs *reader,
22215                              const gdb_byte *info_ptr,
22216                              struct die_info *comp_unit_die,
22217                              int has_children,
22218                              void *data)
22219 {
22220   struct dwarf2_cu *cu = reader->cu;
22221
22222   gdb_assert (cu->die_hash == NULL);
22223   cu->die_hash =
22224     htab_create_alloc_ex (cu->header.length / 12,
22225                           die_hash,
22226                           die_eq,
22227                           NULL,
22228                           &cu->comp_unit_obstack,
22229                           hashtab_obstack_allocate,
22230                           dummy_obstack_deallocate);
22231
22232   if (has_children)
22233     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
22234                                                   &info_ptr, comp_unit_die);
22235   cu->dies = comp_unit_die;
22236   /* comp_unit_die is not stored in die_hash, no need.  */
22237
22238   /* We try not to read any attributes in this function, because not
22239      all CUs needed for references have been loaded yet, and symbol
22240      table processing isn't initialized.  But we have to set the CU language,
22241      or we won't be able to build types correctly.
22242      Similarly, if we do not read the producer, we can not apply
22243      producer-specific interpretation.  */
22244   prepare_one_comp_unit (cu, cu->dies, language_minimal);
22245 }
22246
22247 /* Read in a signatured type and build its CU and DIEs.
22248    If the type is a stub for the real type in a DWO file,
22249    read in the real type from the DWO file as well.  */
22250
22251 static void
22252 read_signatured_type (struct signatured_type *sig_type)
22253 {
22254   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
22255
22256   gdb_assert (per_cu->is_debug_types);
22257   gdb_assert (per_cu->cu == NULL);
22258
22259   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
22260                            read_signatured_type_reader, NULL);
22261   sig_type->per_cu.tu_read = 1;
22262 }
22263
22264 /* Decode simple location descriptions.
22265    Given a pointer to a dwarf block that defines a location, compute
22266    the location and return the value.
22267
22268    NOTE drow/2003-11-18: This function is called in two situations
22269    now: for the address of static or global variables (partial symbols
22270    only) and for offsets into structures which are expected to be
22271    (more or less) constant.  The partial symbol case should go away,
22272    and only the constant case should remain.  That will let this
22273    function complain more accurately.  A few special modes are allowed
22274    without complaint for global variables (for instance, global
22275    register values and thread-local values).
22276
22277    A location description containing no operations indicates that the
22278    object is optimized out.  The return value is 0 for that case.
22279    FIXME drow/2003-11-16: No callers check for this case any more; soon all
22280    callers will only want a very basic result and this can become a
22281    complaint.
22282
22283    Note that stack[0] is unused except as a default error return.  */
22284
22285 static CORE_ADDR
22286 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
22287 {
22288   struct objfile *objfile = cu->objfile;
22289   size_t i;
22290   size_t size = blk->size;
22291   const gdb_byte *data = blk->data;
22292   CORE_ADDR stack[64];
22293   int stacki;
22294   unsigned int bytes_read, unsnd;
22295   gdb_byte op;
22296
22297   i = 0;
22298   stacki = 0;
22299   stack[stacki] = 0;
22300   stack[++stacki] = 0;
22301
22302   while (i < size)
22303     {
22304       op = data[i++];
22305       switch (op)
22306         {
22307         case DW_OP_lit0:
22308         case DW_OP_lit1:
22309         case DW_OP_lit2:
22310         case DW_OP_lit3:
22311         case DW_OP_lit4:
22312         case DW_OP_lit5:
22313         case DW_OP_lit6:
22314         case DW_OP_lit7:
22315         case DW_OP_lit8:
22316         case DW_OP_lit9:
22317         case DW_OP_lit10:
22318         case DW_OP_lit11:
22319         case DW_OP_lit12:
22320         case DW_OP_lit13:
22321         case DW_OP_lit14:
22322         case DW_OP_lit15:
22323         case DW_OP_lit16:
22324         case DW_OP_lit17:
22325         case DW_OP_lit18:
22326         case DW_OP_lit19:
22327         case DW_OP_lit20:
22328         case DW_OP_lit21:
22329         case DW_OP_lit22:
22330         case DW_OP_lit23:
22331         case DW_OP_lit24:
22332         case DW_OP_lit25:
22333         case DW_OP_lit26:
22334         case DW_OP_lit27:
22335         case DW_OP_lit28:
22336         case DW_OP_lit29:
22337         case DW_OP_lit30:
22338         case DW_OP_lit31:
22339           stack[++stacki] = op - DW_OP_lit0;
22340           break;
22341
22342         case DW_OP_reg0:
22343         case DW_OP_reg1:
22344         case DW_OP_reg2:
22345         case DW_OP_reg3:
22346         case DW_OP_reg4:
22347         case DW_OP_reg5:
22348         case DW_OP_reg6:
22349         case DW_OP_reg7:
22350         case DW_OP_reg8:
22351         case DW_OP_reg9:
22352         case DW_OP_reg10:
22353         case DW_OP_reg11:
22354         case DW_OP_reg12:
22355         case DW_OP_reg13:
22356         case DW_OP_reg14:
22357         case DW_OP_reg15:
22358         case DW_OP_reg16:
22359         case DW_OP_reg17:
22360         case DW_OP_reg18:
22361         case DW_OP_reg19:
22362         case DW_OP_reg20:
22363         case DW_OP_reg21:
22364         case DW_OP_reg22:
22365         case DW_OP_reg23:
22366         case DW_OP_reg24:
22367         case DW_OP_reg25:
22368         case DW_OP_reg26:
22369         case DW_OP_reg27:
22370         case DW_OP_reg28:
22371         case DW_OP_reg29:
22372         case DW_OP_reg30:
22373         case DW_OP_reg31:
22374           stack[++stacki] = op - DW_OP_reg0;
22375           if (i < size)
22376             dwarf2_complex_location_expr_complaint ();
22377           break;
22378
22379         case DW_OP_regx:
22380           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
22381           i += bytes_read;
22382           stack[++stacki] = unsnd;
22383           if (i < size)
22384             dwarf2_complex_location_expr_complaint ();
22385           break;
22386
22387         case DW_OP_addr:
22388           stack[++stacki] = read_address (objfile->obfd, &data[i],
22389                                           cu, &bytes_read);
22390           i += bytes_read;
22391           break;
22392
22393         case DW_OP_const1u:
22394           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
22395           i += 1;
22396           break;
22397
22398         case DW_OP_const1s:
22399           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
22400           i += 1;
22401           break;
22402
22403         case DW_OP_const2u:
22404           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
22405           i += 2;
22406           break;
22407
22408         case DW_OP_const2s:
22409           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
22410           i += 2;
22411           break;
22412
22413         case DW_OP_const4u:
22414           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
22415           i += 4;
22416           break;
22417
22418         case DW_OP_const4s:
22419           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
22420           i += 4;
22421           break;
22422
22423         case DW_OP_const8u:
22424           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
22425           i += 8;
22426           break;
22427
22428         case DW_OP_constu:
22429           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
22430                                                   &bytes_read);
22431           i += bytes_read;
22432           break;
22433
22434         case DW_OP_consts:
22435           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
22436           i += bytes_read;
22437           break;
22438
22439         case DW_OP_dup:
22440           stack[stacki + 1] = stack[stacki];
22441           stacki++;
22442           break;
22443
22444         case DW_OP_plus:
22445           stack[stacki - 1] += stack[stacki];
22446           stacki--;
22447           break;
22448
22449         case DW_OP_plus_uconst:
22450           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
22451                                                  &bytes_read);
22452           i += bytes_read;
22453           break;
22454
22455         case DW_OP_minus:
22456           stack[stacki - 1] -= stack[stacki];
22457           stacki--;
22458           break;
22459
22460         case DW_OP_deref:
22461           /* If we're not the last op, then we definitely can't encode
22462              this using GDB's address_class enum.  This is valid for partial
22463              global symbols, although the variable's address will be bogus
22464              in the psymtab.  */
22465           if (i < size)
22466             dwarf2_complex_location_expr_complaint ();
22467           break;
22468
22469         case DW_OP_GNU_push_tls_address:
22470         case DW_OP_form_tls_address:
22471           /* The top of the stack has the offset from the beginning
22472              of the thread control block at which the variable is located.  */
22473           /* Nothing should follow this operator, so the top of stack would
22474              be returned.  */
22475           /* This is valid for partial global symbols, but the variable's
22476              address will be bogus in the psymtab.  Make it always at least
22477              non-zero to not look as a variable garbage collected by linker
22478              which have DW_OP_addr 0.  */
22479           if (i < size)
22480             dwarf2_complex_location_expr_complaint ();
22481           stack[stacki]++;
22482           break;
22483
22484         case DW_OP_GNU_uninit:
22485           break;
22486
22487         case DW_OP_GNU_addr_index:
22488         case DW_OP_GNU_const_index:
22489           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
22490                                                          &bytes_read);
22491           i += bytes_read;
22492           break;
22493
22494         default:
22495           {
22496             const char *name = get_DW_OP_name (op);
22497
22498             if (name)
22499               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
22500                          name);
22501             else
22502               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
22503                          op);
22504           }
22505
22506           return (stack[stacki]);
22507         }
22508
22509       /* Enforce maximum stack depth of SIZE-1 to avoid writing
22510          outside of the allocated space.  Also enforce minimum>0.  */
22511       if (stacki >= ARRAY_SIZE (stack) - 1)
22512         {
22513           complaint (&symfile_complaints,
22514                      _("location description stack overflow"));
22515           return 0;
22516         }
22517
22518       if (stacki <= 0)
22519         {
22520           complaint (&symfile_complaints,
22521                      _("location description stack underflow"));
22522           return 0;
22523         }
22524     }
22525   return (stack[stacki]);
22526 }
22527
22528 /* memory allocation interface */
22529
22530 static struct dwarf_block *
22531 dwarf_alloc_block (struct dwarf2_cu *cu)
22532 {
22533   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
22534 }
22535
22536 static struct die_info *
22537 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
22538 {
22539   struct die_info *die;
22540   size_t size = sizeof (struct die_info);
22541
22542   if (num_attrs > 1)
22543     size += (num_attrs - 1) * sizeof (struct attribute);
22544
22545   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
22546   memset (die, 0, sizeof (struct die_info));
22547   return (die);
22548 }
22549
22550 \f
22551 /* Macro support.  */
22552
22553 /* Return file name relative to the compilation directory of file number I in
22554    *LH's file name table.  The result is allocated using xmalloc; the caller is
22555    responsible for freeing it.  */
22556
22557 static char *
22558 file_file_name (int file, struct line_header *lh)
22559 {
22560   /* Is the file number a valid index into the line header's file name
22561      table?  Remember that file numbers start with one, not zero.  */
22562   if (1 <= file && file <= lh->file_names.size ())
22563     {
22564       const file_entry &fe = lh->file_names[file - 1];
22565
22566       if (!IS_ABSOLUTE_PATH (fe.name))
22567         {
22568           const char *dir = fe.include_dir (lh);
22569           if (dir != NULL)
22570             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
22571         }
22572       return xstrdup (fe.name);
22573     }
22574   else
22575     {
22576       /* The compiler produced a bogus file number.  We can at least
22577          record the macro definitions made in the file, even if we
22578          won't be able to find the file by name.  */
22579       char fake_name[80];
22580
22581       xsnprintf (fake_name, sizeof (fake_name),
22582                  "<bad macro file number %d>", file);
22583
22584       complaint (&symfile_complaints,
22585                  _("bad file number in macro information (%d)"),
22586                  file);
22587
22588       return xstrdup (fake_name);
22589     }
22590 }
22591
22592 /* Return the full name of file number I in *LH's file name table.
22593    Use COMP_DIR as the name of the current directory of the
22594    compilation.  The result is allocated using xmalloc; the caller is
22595    responsible for freeing it.  */
22596 static char *
22597 file_full_name (int file, struct line_header *lh, const char *comp_dir)
22598 {
22599   /* Is the file number a valid index into the line header's file name
22600      table?  Remember that file numbers start with one, not zero.  */
22601   if (1 <= file && file <= lh->file_names.size ())
22602     {
22603       char *relative = file_file_name (file, lh);
22604
22605       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
22606         return relative;
22607       return reconcat (relative, comp_dir, SLASH_STRING,
22608                        relative, (char *) NULL);
22609     }
22610   else
22611     return file_file_name (file, lh);
22612 }
22613
22614
22615 static struct macro_source_file *
22616 macro_start_file (int file, int line,
22617                   struct macro_source_file *current_file,
22618                   struct line_header *lh)
22619 {
22620   /* File name relative to the compilation directory of this source file.  */
22621   char *file_name = file_file_name (file, lh);
22622
22623   if (! current_file)
22624     {
22625       /* Note: We don't create a macro table for this compilation unit
22626          at all until we actually get a filename.  */
22627       struct macro_table *macro_table = get_macro_table ();
22628
22629       /* If we have no current file, then this must be the start_file
22630          directive for the compilation unit's main source file.  */
22631       current_file = macro_set_main (macro_table, file_name);
22632       macro_define_special (macro_table);
22633     }
22634   else
22635     current_file = macro_include (current_file, line, file_name);
22636
22637   xfree (file_name);
22638
22639   return current_file;
22640 }
22641
22642 static const char *
22643 consume_improper_spaces (const char *p, const char *body)
22644 {
22645   if (*p == ' ')
22646     {
22647       complaint (&symfile_complaints,
22648                  _("macro definition contains spaces "
22649                    "in formal argument list:\n`%s'"),
22650                  body);
22651
22652       while (*p == ' ')
22653         p++;
22654     }
22655
22656   return p;
22657 }
22658
22659
22660 static void
22661 parse_macro_definition (struct macro_source_file *file, int line,
22662                         const char *body)
22663 {
22664   const char *p;
22665
22666   /* The body string takes one of two forms.  For object-like macro
22667      definitions, it should be:
22668
22669         <macro name> " " <definition>
22670
22671      For function-like macro definitions, it should be:
22672
22673         <macro name> "() " <definition>
22674      or
22675         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
22676
22677      Spaces may appear only where explicitly indicated, and in the
22678      <definition>.
22679
22680      The Dwarf 2 spec says that an object-like macro's name is always
22681      followed by a space, but versions of GCC around March 2002 omit
22682      the space when the macro's definition is the empty string.
22683
22684      The Dwarf 2 spec says that there should be no spaces between the
22685      formal arguments in a function-like macro's formal argument list,
22686      but versions of GCC around March 2002 include spaces after the
22687      commas.  */
22688
22689
22690   /* Find the extent of the macro name.  The macro name is terminated
22691      by either a space or null character (for an object-like macro) or
22692      an opening paren (for a function-like macro).  */
22693   for (p = body; *p; p++)
22694     if (*p == ' ' || *p == '(')
22695       break;
22696
22697   if (*p == ' ' || *p == '\0')
22698     {
22699       /* It's an object-like macro.  */
22700       int name_len = p - body;
22701       char *name = savestring (body, name_len);
22702       const char *replacement;
22703
22704       if (*p == ' ')
22705         replacement = body + name_len + 1;
22706       else
22707         {
22708           dwarf2_macro_malformed_definition_complaint (body);
22709           replacement = body + name_len;
22710         }
22711
22712       macro_define_object (file, line, name, replacement);
22713
22714       xfree (name);
22715     }
22716   else if (*p == '(')
22717     {
22718       /* It's a function-like macro.  */
22719       char *name = savestring (body, p - body);
22720       int argc = 0;
22721       int argv_size = 1;
22722       char **argv = XNEWVEC (char *, argv_size);
22723
22724       p++;
22725
22726       p = consume_improper_spaces (p, body);
22727
22728       /* Parse the formal argument list.  */
22729       while (*p && *p != ')')
22730         {
22731           /* Find the extent of the current argument name.  */
22732           const char *arg_start = p;
22733
22734           while (*p && *p != ',' && *p != ')' && *p != ' ')
22735             p++;
22736
22737           if (! *p || p == arg_start)
22738             dwarf2_macro_malformed_definition_complaint (body);
22739           else
22740             {
22741               /* Make sure argv has room for the new argument.  */
22742               if (argc >= argv_size)
22743                 {
22744                   argv_size *= 2;
22745                   argv = XRESIZEVEC (char *, argv, argv_size);
22746                 }
22747
22748               argv[argc++] = savestring (arg_start, p - arg_start);
22749             }
22750
22751           p = consume_improper_spaces (p, body);
22752
22753           /* Consume the comma, if present.  */
22754           if (*p == ',')
22755             {
22756               p++;
22757
22758               p = consume_improper_spaces (p, body);
22759             }
22760         }
22761
22762       if (*p == ')')
22763         {
22764           p++;
22765
22766           if (*p == ' ')
22767             /* Perfectly formed definition, no complaints.  */
22768             macro_define_function (file, line, name,
22769                                    argc, (const char **) argv,
22770                                    p + 1);
22771           else if (*p == '\0')
22772             {
22773               /* Complain, but do define it.  */
22774               dwarf2_macro_malformed_definition_complaint (body);
22775               macro_define_function (file, line, name,
22776                                      argc, (const char **) argv,
22777                                      p);
22778             }
22779           else
22780             /* Just complain.  */
22781             dwarf2_macro_malformed_definition_complaint (body);
22782         }
22783       else
22784         /* Just complain.  */
22785         dwarf2_macro_malformed_definition_complaint (body);
22786
22787       xfree (name);
22788       {
22789         int i;
22790
22791         for (i = 0; i < argc; i++)
22792           xfree (argv[i]);
22793       }
22794       xfree (argv);
22795     }
22796   else
22797     dwarf2_macro_malformed_definition_complaint (body);
22798 }
22799
22800 /* Skip some bytes from BYTES according to the form given in FORM.
22801    Returns the new pointer.  */
22802
22803 static const gdb_byte *
22804 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22805                  enum dwarf_form form,
22806                  unsigned int offset_size,
22807                  struct dwarf2_section_info *section)
22808 {
22809   unsigned int bytes_read;
22810
22811   switch (form)
22812     {
22813     case DW_FORM_data1:
22814     case DW_FORM_flag:
22815       ++bytes;
22816       break;
22817
22818     case DW_FORM_data2:
22819       bytes += 2;
22820       break;
22821
22822     case DW_FORM_data4:
22823       bytes += 4;
22824       break;
22825
22826     case DW_FORM_data8:
22827       bytes += 8;
22828       break;
22829
22830     case DW_FORM_data16:
22831       bytes += 16;
22832       break;
22833
22834     case DW_FORM_string:
22835       read_direct_string (abfd, bytes, &bytes_read);
22836       bytes += bytes_read;
22837       break;
22838
22839     case DW_FORM_sec_offset:
22840     case DW_FORM_strp:
22841     case DW_FORM_GNU_strp_alt:
22842       bytes += offset_size;
22843       break;
22844
22845     case DW_FORM_block:
22846       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22847       bytes += bytes_read;
22848       break;
22849
22850     case DW_FORM_block1:
22851       bytes += 1 + read_1_byte (abfd, bytes);
22852       break;
22853     case DW_FORM_block2:
22854       bytes += 2 + read_2_bytes (abfd, bytes);
22855       break;
22856     case DW_FORM_block4:
22857       bytes += 4 + read_4_bytes (abfd, bytes);
22858       break;
22859
22860     case DW_FORM_sdata:
22861     case DW_FORM_udata:
22862     case DW_FORM_GNU_addr_index:
22863     case DW_FORM_GNU_str_index:
22864       bytes = gdb_skip_leb128 (bytes, buffer_end);
22865       if (bytes == NULL)
22866         {
22867           dwarf2_section_buffer_overflow_complaint (section);
22868           return NULL;
22869         }
22870       break;
22871
22872     case DW_FORM_implicit_const:
22873       break;
22874
22875     default:
22876       {
22877         complaint (&symfile_complaints,
22878                    _("invalid form 0x%x in `%s'"),
22879                    form, get_section_name (section));
22880         return NULL;
22881       }
22882     }
22883
22884   return bytes;
22885 }
22886
22887 /* A helper for dwarf_decode_macros that handles skipping an unknown
22888    opcode.  Returns an updated pointer to the macro data buffer; or,
22889    on error, issues a complaint and returns NULL.  */
22890
22891 static const gdb_byte *
22892 skip_unknown_opcode (unsigned int opcode,
22893                      const gdb_byte **opcode_definitions,
22894                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22895                      bfd *abfd,
22896                      unsigned int offset_size,
22897                      struct dwarf2_section_info *section)
22898 {
22899   unsigned int bytes_read, i;
22900   unsigned long arg;
22901   const gdb_byte *defn;
22902
22903   if (opcode_definitions[opcode] == NULL)
22904     {
22905       complaint (&symfile_complaints,
22906                  _("unrecognized DW_MACFINO opcode 0x%x"),
22907                  opcode);
22908       return NULL;
22909     }
22910
22911   defn = opcode_definitions[opcode];
22912   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22913   defn += bytes_read;
22914
22915   for (i = 0; i < arg; ++i)
22916     {
22917       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22918                                  (enum dwarf_form) defn[i], offset_size,
22919                                  section);
22920       if (mac_ptr == NULL)
22921         {
22922           /* skip_form_bytes already issued the complaint.  */
22923           return NULL;
22924         }
22925     }
22926
22927   return mac_ptr;
22928 }
22929
22930 /* A helper function which parses the header of a macro section.
22931    If the macro section is the extended (for now called "GNU") type,
22932    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22933    the header, or issues a complaint and returns NULL on error.  */
22934
22935 static const gdb_byte *
22936 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22937                           bfd *abfd,
22938                           const gdb_byte *mac_ptr,
22939                           unsigned int *offset_size,
22940                           int section_is_gnu)
22941 {
22942   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22943
22944   if (section_is_gnu)
22945     {
22946       unsigned int version, flags;
22947
22948       version = read_2_bytes (abfd, mac_ptr);
22949       if (version != 4 && version != 5)
22950         {
22951           complaint (&symfile_complaints,
22952                      _("unrecognized version `%d' in .debug_macro section"),
22953                      version);
22954           return NULL;
22955         }
22956       mac_ptr += 2;
22957
22958       flags = read_1_byte (abfd, mac_ptr);
22959       ++mac_ptr;
22960       *offset_size = (flags & 1) ? 8 : 4;
22961
22962       if ((flags & 2) != 0)
22963         /* We don't need the line table offset.  */
22964         mac_ptr += *offset_size;
22965
22966       /* Vendor opcode descriptions.  */
22967       if ((flags & 4) != 0)
22968         {
22969           unsigned int i, count;
22970
22971           count = read_1_byte (abfd, mac_ptr);
22972           ++mac_ptr;
22973           for (i = 0; i < count; ++i)
22974             {
22975               unsigned int opcode, bytes_read;
22976               unsigned long arg;
22977
22978               opcode = read_1_byte (abfd, mac_ptr);
22979               ++mac_ptr;
22980               opcode_definitions[opcode] = mac_ptr;
22981               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22982               mac_ptr += bytes_read;
22983               mac_ptr += arg;
22984             }
22985         }
22986     }
22987
22988   return mac_ptr;
22989 }
22990
22991 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22992    including DW_MACRO_import.  */
22993
22994 static void
22995 dwarf_decode_macro_bytes (bfd *abfd,
22996                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22997                           struct macro_source_file *current_file,
22998                           struct line_header *lh,
22999                           struct dwarf2_section_info *section,
23000                           int section_is_gnu, int section_is_dwz,
23001                           unsigned int offset_size,
23002                           htab_t include_hash)
23003 {
23004   struct objfile *objfile = dwarf2_per_objfile->objfile;
23005   enum dwarf_macro_record_type macinfo_type;
23006   int at_commandline;
23007   const gdb_byte *opcode_definitions[256];
23008
23009   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23010                                       &offset_size, section_is_gnu);
23011   if (mac_ptr == NULL)
23012     {
23013       /* We already issued a complaint.  */
23014       return;
23015     }
23016
23017   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
23018      GDB is still reading the definitions from command line.  First
23019      DW_MACINFO_start_file will need to be ignored as it was already executed
23020      to create CURRENT_FILE for the main source holding also the command line
23021      definitions.  On first met DW_MACINFO_start_file this flag is reset to
23022      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
23023
23024   at_commandline = 1;
23025
23026   do
23027     {
23028       /* Do we at least have room for a macinfo type byte?  */
23029       if (mac_ptr >= mac_end)
23030         {
23031           dwarf2_section_buffer_overflow_complaint (section);
23032           break;
23033         }
23034
23035       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23036       mac_ptr++;
23037
23038       /* Note that we rely on the fact that the corresponding GNU and
23039          DWARF constants are the same.  */
23040       switch (macinfo_type)
23041         {
23042           /* A zero macinfo type indicates the end of the macro
23043              information.  */
23044         case 0:
23045           break;
23046
23047         case DW_MACRO_define:
23048         case DW_MACRO_undef:
23049         case DW_MACRO_define_strp:
23050         case DW_MACRO_undef_strp:
23051         case DW_MACRO_define_sup:
23052         case DW_MACRO_undef_sup:
23053           {
23054             unsigned int bytes_read;
23055             int line;
23056             const char *body;
23057             int is_define;
23058
23059             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23060             mac_ptr += bytes_read;
23061
23062             if (macinfo_type == DW_MACRO_define
23063                 || macinfo_type == DW_MACRO_undef)
23064               {
23065                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
23066                 mac_ptr += bytes_read;
23067               }
23068             else
23069               {
23070                 LONGEST str_offset;
23071
23072                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
23073                 mac_ptr += offset_size;
23074
23075                 if (macinfo_type == DW_MACRO_define_sup
23076                     || macinfo_type == DW_MACRO_undef_sup
23077                     || section_is_dwz)
23078                   {
23079                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
23080
23081                     body = read_indirect_string_from_dwz (dwz, str_offset);
23082                   }
23083                 else
23084                   body = read_indirect_string_at_offset (abfd, str_offset);
23085               }
23086
23087             is_define = (macinfo_type == DW_MACRO_define
23088                          || macinfo_type == DW_MACRO_define_strp
23089                          || macinfo_type == DW_MACRO_define_sup);
23090             if (! current_file)
23091               {
23092                 /* DWARF violation as no main source is present.  */
23093                 complaint (&symfile_complaints,
23094                            _("debug info with no main source gives macro %s "
23095                              "on line %d: %s"),
23096                            is_define ? _("definition") : _("undefinition"),
23097                            line, body);
23098                 break;
23099               }
23100             if ((line == 0 && !at_commandline)
23101                 || (line != 0 && at_commandline))
23102               complaint (&symfile_complaints,
23103                          _("debug info gives %s macro %s with %s line %d: %s"),
23104                          at_commandline ? _("command-line") : _("in-file"),
23105                          is_define ? _("definition") : _("undefinition"),
23106                          line == 0 ? _("zero") : _("non-zero"), line, body);
23107
23108             if (is_define)
23109               parse_macro_definition (current_file, line, body);
23110             else
23111               {
23112                 gdb_assert (macinfo_type == DW_MACRO_undef
23113                             || macinfo_type == DW_MACRO_undef_strp
23114                             || macinfo_type == DW_MACRO_undef_sup);
23115                 macro_undef (current_file, line, body);
23116               }
23117           }
23118           break;
23119
23120         case DW_MACRO_start_file:
23121           {
23122             unsigned int bytes_read;
23123             int line, file;
23124
23125             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23126             mac_ptr += bytes_read;
23127             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23128             mac_ptr += bytes_read;
23129
23130             if ((line == 0 && !at_commandline)
23131                 || (line != 0 && at_commandline))
23132               complaint (&symfile_complaints,
23133                          _("debug info gives source %d included "
23134                            "from %s at %s line %d"),
23135                          file, at_commandline ? _("command-line") : _("file"),
23136                          line == 0 ? _("zero") : _("non-zero"), line);
23137
23138             if (at_commandline)
23139               {
23140                 /* This DW_MACRO_start_file was executed in the
23141                    pass one.  */
23142                 at_commandline = 0;
23143               }
23144             else
23145               current_file = macro_start_file (file, line, current_file, lh);
23146           }
23147           break;
23148
23149         case DW_MACRO_end_file:
23150           if (! current_file)
23151             complaint (&symfile_complaints,
23152                        _("macro debug info has an unmatched "
23153                          "`close_file' directive"));
23154           else
23155             {
23156               current_file = current_file->included_by;
23157               if (! current_file)
23158                 {
23159                   enum dwarf_macro_record_type next_type;
23160
23161                   /* GCC circa March 2002 doesn't produce the zero
23162                      type byte marking the end of the compilation
23163                      unit.  Complain if it's not there, but exit no
23164                      matter what.  */
23165
23166                   /* Do we at least have room for a macinfo type byte?  */
23167                   if (mac_ptr >= mac_end)
23168                     {
23169                       dwarf2_section_buffer_overflow_complaint (section);
23170                       return;
23171                     }
23172
23173                   /* We don't increment mac_ptr here, so this is just
23174                      a look-ahead.  */
23175                   next_type
23176                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
23177                                                                   mac_ptr);
23178                   if (next_type != 0)
23179                     complaint (&symfile_complaints,
23180                                _("no terminating 0-type entry for "
23181                                  "macros in `.debug_macinfo' section"));
23182
23183                   return;
23184                 }
23185             }
23186           break;
23187
23188         case DW_MACRO_import:
23189         case DW_MACRO_import_sup:
23190           {
23191             LONGEST offset;
23192             void **slot;
23193             bfd *include_bfd = abfd;
23194             struct dwarf2_section_info *include_section = section;
23195             const gdb_byte *include_mac_end = mac_end;
23196             int is_dwz = section_is_dwz;
23197             const gdb_byte *new_mac_ptr;
23198
23199             offset = read_offset_1 (abfd, mac_ptr, offset_size);
23200             mac_ptr += offset_size;
23201
23202             if (macinfo_type == DW_MACRO_import_sup)
23203               {
23204                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
23205
23206                 dwarf2_read_section (objfile, &dwz->macro);
23207
23208                 include_section = &dwz->macro;
23209                 include_bfd = get_section_bfd_owner (include_section);
23210                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
23211                 is_dwz = 1;
23212               }
23213
23214             new_mac_ptr = include_section->buffer + offset;
23215             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
23216
23217             if (*slot != NULL)
23218               {
23219                 /* This has actually happened; see
23220                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
23221                 complaint (&symfile_complaints,
23222                            _("recursive DW_MACRO_import in "
23223                              ".debug_macro section"));
23224               }
23225             else
23226               {
23227                 *slot = (void *) new_mac_ptr;
23228
23229                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
23230                                           include_mac_end, current_file, lh,
23231                                           section, section_is_gnu, is_dwz,
23232                                           offset_size, include_hash);
23233
23234                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
23235               }
23236           }
23237           break;
23238
23239         case DW_MACINFO_vendor_ext:
23240           if (!section_is_gnu)
23241             {
23242               unsigned int bytes_read;
23243
23244               /* This reads the constant, but since we don't recognize
23245                  any vendor extensions, we ignore it.  */
23246               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23247               mac_ptr += bytes_read;
23248               read_direct_string (abfd, mac_ptr, &bytes_read);
23249               mac_ptr += bytes_read;
23250
23251               /* We don't recognize any vendor extensions.  */
23252               break;
23253             }
23254           /* FALLTHROUGH */
23255
23256         default:
23257           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23258                                          mac_ptr, mac_end, abfd, offset_size,
23259                                          section);
23260           if (mac_ptr == NULL)
23261             return;
23262           break;
23263         }
23264     } while (macinfo_type != 0);
23265 }
23266
23267 static void
23268 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
23269                      int section_is_gnu)
23270 {
23271   struct objfile *objfile = dwarf2_per_objfile->objfile;
23272   struct line_header *lh = cu->line_header;
23273   bfd *abfd;
23274   const gdb_byte *mac_ptr, *mac_end;
23275   struct macro_source_file *current_file = 0;
23276   enum dwarf_macro_record_type macinfo_type;
23277   unsigned int offset_size = cu->header.offset_size;
23278   const gdb_byte *opcode_definitions[256];
23279   void **slot;
23280   struct dwarf2_section_info *section;
23281   const char *section_name;
23282
23283   if (cu->dwo_unit != NULL)
23284     {
23285       if (section_is_gnu)
23286         {
23287           section = &cu->dwo_unit->dwo_file->sections.macro;
23288           section_name = ".debug_macro.dwo";
23289         }
23290       else
23291         {
23292           section = &cu->dwo_unit->dwo_file->sections.macinfo;
23293           section_name = ".debug_macinfo.dwo";
23294         }
23295     }
23296   else
23297     {
23298       if (section_is_gnu)
23299         {
23300           section = &dwarf2_per_objfile->macro;
23301           section_name = ".debug_macro";
23302         }
23303       else
23304         {
23305           section = &dwarf2_per_objfile->macinfo;
23306           section_name = ".debug_macinfo";
23307         }
23308     }
23309
23310   dwarf2_read_section (objfile, section);
23311   if (section->buffer == NULL)
23312     {
23313       complaint (&symfile_complaints, _("missing %s section"), section_name);
23314       return;
23315     }
23316   abfd = get_section_bfd_owner (section);
23317
23318   /* First pass: Find the name of the base filename.
23319      This filename is needed in order to process all macros whose definition
23320      (or undefinition) comes from the command line.  These macros are defined
23321      before the first DW_MACINFO_start_file entry, and yet still need to be
23322      associated to the base file.
23323
23324      To determine the base file name, we scan the macro definitions until we
23325      reach the first DW_MACINFO_start_file entry.  We then initialize
23326      CURRENT_FILE accordingly so that any macro definition found before the
23327      first DW_MACINFO_start_file can still be associated to the base file.  */
23328
23329   mac_ptr = section->buffer + offset;
23330   mac_end = section->buffer + section->size;
23331
23332   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
23333                                       &offset_size, section_is_gnu);
23334   if (mac_ptr == NULL)
23335     {
23336       /* We already issued a complaint.  */
23337       return;
23338     }
23339
23340   do
23341     {
23342       /* Do we at least have room for a macinfo type byte?  */
23343       if (mac_ptr >= mac_end)
23344         {
23345           /* Complaint is printed during the second pass as GDB will probably
23346              stop the first pass earlier upon finding
23347              DW_MACINFO_start_file.  */
23348           break;
23349         }
23350
23351       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
23352       mac_ptr++;
23353
23354       /* Note that we rely on the fact that the corresponding GNU and
23355          DWARF constants are the same.  */
23356       switch (macinfo_type)
23357         {
23358           /* A zero macinfo type indicates the end of the macro
23359              information.  */
23360         case 0:
23361           break;
23362
23363         case DW_MACRO_define:
23364         case DW_MACRO_undef:
23365           /* Only skip the data by MAC_PTR.  */
23366           {
23367             unsigned int bytes_read;
23368
23369             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23370             mac_ptr += bytes_read;
23371             read_direct_string (abfd, mac_ptr, &bytes_read);
23372             mac_ptr += bytes_read;
23373           }
23374           break;
23375
23376         case DW_MACRO_start_file:
23377           {
23378             unsigned int bytes_read;
23379             int line, file;
23380
23381             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23382             mac_ptr += bytes_read;
23383             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23384             mac_ptr += bytes_read;
23385
23386             current_file = macro_start_file (file, line, current_file, lh);
23387           }
23388           break;
23389
23390         case DW_MACRO_end_file:
23391           /* No data to skip by MAC_PTR.  */
23392           break;
23393
23394         case DW_MACRO_define_strp:
23395         case DW_MACRO_undef_strp:
23396         case DW_MACRO_define_sup:
23397         case DW_MACRO_undef_sup:
23398           {
23399             unsigned int bytes_read;
23400
23401             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23402             mac_ptr += bytes_read;
23403             mac_ptr += offset_size;
23404           }
23405           break;
23406
23407         case DW_MACRO_import:
23408         case DW_MACRO_import_sup:
23409           /* Note that, according to the spec, a transparent include
23410              chain cannot call DW_MACRO_start_file.  So, we can just
23411              skip this opcode.  */
23412           mac_ptr += offset_size;
23413           break;
23414
23415         case DW_MACINFO_vendor_ext:
23416           /* Only skip the data by MAC_PTR.  */
23417           if (!section_is_gnu)
23418             {
23419               unsigned int bytes_read;
23420
23421               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
23422               mac_ptr += bytes_read;
23423               read_direct_string (abfd, mac_ptr, &bytes_read);
23424               mac_ptr += bytes_read;
23425             }
23426           /* FALLTHROUGH */
23427
23428         default:
23429           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
23430                                          mac_ptr, mac_end, abfd, offset_size,
23431                                          section);
23432           if (mac_ptr == NULL)
23433             return;
23434           break;
23435         }
23436     } while (macinfo_type != 0 && current_file == NULL);
23437
23438   /* Second pass: Process all entries.
23439
23440      Use the AT_COMMAND_LINE flag to determine whether we are still processing
23441      command-line macro definitions/undefinitions.  This flag is unset when we
23442      reach the first DW_MACINFO_start_file entry.  */
23443
23444   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
23445                                            htab_eq_pointer,
23446                                            NULL, xcalloc, xfree));
23447   mac_ptr = section->buffer + offset;
23448   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
23449   *slot = (void *) mac_ptr;
23450   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
23451                             current_file, lh, section,
23452                             section_is_gnu, 0, offset_size,
23453                             include_hash.get ());
23454 }
23455
23456 /* Check if the attribute's form is a DW_FORM_block*
23457    if so return true else false.  */
23458
23459 static int
23460 attr_form_is_block (const struct attribute *attr)
23461 {
23462   return (attr == NULL ? 0 :
23463       attr->form == DW_FORM_block1
23464       || attr->form == DW_FORM_block2
23465       || attr->form == DW_FORM_block4
23466       || attr->form == DW_FORM_block
23467       || attr->form == DW_FORM_exprloc);
23468 }
23469
23470 /* Return non-zero if ATTR's value is a section offset --- classes
23471    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
23472    You may use DW_UNSND (attr) to retrieve such offsets.
23473
23474    Section 7.5.4, "Attribute Encodings", explains that no attribute
23475    may have a value that belongs to more than one of these classes; it
23476    would be ambiguous if we did, because we use the same forms for all
23477    of them.  */
23478
23479 static int
23480 attr_form_is_section_offset (const struct attribute *attr)
23481 {
23482   return (attr->form == DW_FORM_data4
23483           || attr->form == DW_FORM_data8
23484           || attr->form == DW_FORM_sec_offset);
23485 }
23486
23487 /* Return non-zero if ATTR's value falls in the 'constant' class, or
23488    zero otherwise.  When this function returns true, you can apply
23489    dwarf2_get_attr_constant_value to it.
23490
23491    However, note that for some attributes you must check
23492    attr_form_is_section_offset before using this test.  DW_FORM_data4
23493    and DW_FORM_data8 are members of both the constant class, and of
23494    the classes that contain offsets into other debug sections
23495    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
23496    that, if an attribute's can be either a constant or one of the
23497    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
23498    taken as section offsets, not constants.
23499
23500    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
23501    cannot handle that.  */
23502
23503 static int
23504 attr_form_is_constant (const struct attribute *attr)
23505 {
23506   switch (attr->form)
23507     {
23508     case DW_FORM_sdata:
23509     case DW_FORM_udata:
23510     case DW_FORM_data1:
23511     case DW_FORM_data2:
23512     case DW_FORM_data4:
23513     case DW_FORM_data8:
23514     case DW_FORM_implicit_const:
23515       return 1;
23516     default:
23517       return 0;
23518     }
23519 }
23520
23521
23522 /* DW_ADDR is always stored already as sect_offset; despite for the forms
23523    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
23524
23525 static int
23526 attr_form_is_ref (const struct attribute *attr)
23527 {
23528   switch (attr->form)
23529     {
23530     case DW_FORM_ref_addr:
23531     case DW_FORM_ref1:
23532     case DW_FORM_ref2:
23533     case DW_FORM_ref4:
23534     case DW_FORM_ref8:
23535     case DW_FORM_ref_udata:
23536     case DW_FORM_GNU_ref_alt:
23537       return 1;
23538     default:
23539       return 0;
23540     }
23541 }
23542
23543 /* Return the .debug_loc section to use for CU.
23544    For DWO files use .debug_loc.dwo.  */
23545
23546 static struct dwarf2_section_info *
23547 cu_debug_loc_section (struct dwarf2_cu *cu)
23548 {
23549   if (cu->dwo_unit)
23550     {
23551       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
23552       
23553       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
23554     }
23555   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
23556                                   : &dwarf2_per_objfile->loc);
23557 }
23558
23559 /* A helper function that fills in a dwarf2_loclist_baton.  */
23560
23561 static void
23562 fill_in_loclist_baton (struct dwarf2_cu *cu,
23563                        struct dwarf2_loclist_baton *baton,
23564                        const struct attribute *attr)
23565 {
23566   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23567
23568   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
23569
23570   baton->per_cu = cu->per_cu;
23571   gdb_assert (baton->per_cu);
23572   /* We don't know how long the location list is, but make sure we
23573      don't run off the edge of the section.  */
23574   baton->size = section->size - DW_UNSND (attr);
23575   baton->data = section->buffer + DW_UNSND (attr);
23576   baton->base_address = cu->base_address;
23577   baton->from_dwo = cu->dwo_unit != NULL;
23578 }
23579
23580 static void
23581 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
23582                              struct dwarf2_cu *cu, int is_block)
23583 {
23584   struct objfile *objfile = dwarf2_per_objfile->objfile;
23585   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
23586
23587   if (attr_form_is_section_offset (attr)
23588       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
23589          the section.  If so, fall through to the complaint in the
23590          other branch.  */
23591       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
23592     {
23593       struct dwarf2_loclist_baton *baton;
23594
23595       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
23596
23597       fill_in_loclist_baton (cu, baton, attr);
23598
23599       if (cu->base_known == 0)
23600         complaint (&symfile_complaints,
23601                    _("Location list used without "
23602                      "specifying the CU base address."));
23603
23604       SYMBOL_ACLASS_INDEX (sym) = (is_block
23605                                    ? dwarf2_loclist_block_index
23606                                    : dwarf2_loclist_index);
23607       SYMBOL_LOCATION_BATON (sym) = baton;
23608     }
23609   else
23610     {
23611       struct dwarf2_locexpr_baton *baton;
23612
23613       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
23614       baton->per_cu = cu->per_cu;
23615       gdb_assert (baton->per_cu);
23616
23617       if (attr_form_is_block (attr))
23618         {
23619           /* Note that we're just copying the block's data pointer
23620              here, not the actual data.  We're still pointing into the
23621              info_buffer for SYM's objfile; right now we never release
23622              that buffer, but when we do clean up properly this may
23623              need to change.  */
23624           baton->size = DW_BLOCK (attr)->size;
23625           baton->data = DW_BLOCK (attr)->data;
23626         }
23627       else
23628         {
23629           dwarf2_invalid_attrib_class_complaint ("location description",
23630                                                  SYMBOL_NATURAL_NAME (sym));
23631           baton->size = 0;
23632         }
23633
23634       SYMBOL_ACLASS_INDEX (sym) = (is_block
23635                                    ? dwarf2_locexpr_block_index
23636                                    : dwarf2_locexpr_index);
23637       SYMBOL_LOCATION_BATON (sym) = baton;
23638     }
23639 }
23640
23641 /* Return the OBJFILE associated with the compilation unit CU.  If CU
23642    came from a separate debuginfo file, then the master objfile is
23643    returned.  */
23644
23645 struct objfile *
23646 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
23647 {
23648   struct objfile *objfile = per_cu->objfile;
23649
23650   /* Return the master objfile, so that we can report and look up the
23651      correct file containing this variable.  */
23652   if (objfile->separate_debug_objfile_backlink)
23653     objfile = objfile->separate_debug_objfile_backlink;
23654
23655   return objfile;
23656 }
23657
23658 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
23659    (CU_HEADERP is unused in such case) or prepare a temporary copy at
23660    CU_HEADERP first.  */
23661
23662 static const struct comp_unit_head *
23663 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
23664                        struct dwarf2_per_cu_data *per_cu)
23665 {
23666   const gdb_byte *info_ptr;
23667
23668   if (per_cu->cu)
23669     return &per_cu->cu->header;
23670
23671   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
23672
23673   memset (cu_headerp, 0, sizeof (*cu_headerp));
23674   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
23675                        rcuh_kind::COMPILE);
23676
23677   return cu_headerp;
23678 }
23679
23680 /* Return the address size given in the compilation unit header for CU.  */
23681
23682 int
23683 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
23684 {
23685   struct comp_unit_head cu_header_local;
23686   const struct comp_unit_head *cu_headerp;
23687
23688   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23689
23690   return cu_headerp->addr_size;
23691 }
23692
23693 /* Return the offset size given in the compilation unit header for CU.  */
23694
23695 int
23696 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23697 {
23698   struct comp_unit_head cu_header_local;
23699   const struct comp_unit_head *cu_headerp;
23700
23701   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23702
23703   return cu_headerp->offset_size;
23704 }
23705
23706 /* See its dwarf2loc.h declaration.  */
23707
23708 int
23709 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23710 {
23711   struct comp_unit_head cu_header_local;
23712   const struct comp_unit_head *cu_headerp;
23713
23714   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23715
23716   if (cu_headerp->version == 2)
23717     return cu_headerp->addr_size;
23718   else
23719     return cu_headerp->offset_size;
23720 }
23721
23722 /* Return the text offset of the CU.  The returned offset comes from
23723    this CU's objfile.  If this objfile came from a separate debuginfo
23724    file, then the offset may be different from the corresponding
23725    offset in the parent objfile.  */
23726
23727 CORE_ADDR
23728 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23729 {
23730   struct objfile *objfile = per_cu->objfile;
23731
23732   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23733 }
23734
23735 /* Return DWARF version number of PER_CU.  */
23736
23737 short
23738 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23739 {
23740   return per_cu->dwarf_version;
23741 }
23742
23743 /* Locate the .debug_info compilation unit from CU's objfile which contains
23744    the DIE at OFFSET.  Raises an error on failure.  */
23745
23746 static struct dwarf2_per_cu_data *
23747 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23748                                   unsigned int offset_in_dwz,
23749                                   struct objfile *objfile)
23750 {
23751   struct dwarf2_per_cu_data *this_cu;
23752   int low, high;
23753   const sect_offset *cu_off;
23754
23755   low = 0;
23756   high = dwarf2_per_objfile->n_comp_units - 1;
23757   while (high > low)
23758     {
23759       struct dwarf2_per_cu_data *mid_cu;
23760       int mid = low + (high - low) / 2;
23761
23762       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23763       cu_off = &mid_cu->sect_off;
23764       if (mid_cu->is_dwz > offset_in_dwz
23765           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23766         high = mid;
23767       else
23768         low = mid + 1;
23769     }
23770   gdb_assert (low == high);
23771   this_cu = dwarf2_per_objfile->all_comp_units[low];
23772   cu_off = &this_cu->sect_off;
23773   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23774     {
23775       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23776         error (_("Dwarf Error: could not find partial DIE containing "
23777                "offset 0x%x [in module %s]"),
23778                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23779
23780       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23781                   <= sect_off);
23782       return dwarf2_per_objfile->all_comp_units[low-1];
23783     }
23784   else
23785     {
23786       this_cu = dwarf2_per_objfile->all_comp_units[low];
23787       if (low == dwarf2_per_objfile->n_comp_units - 1
23788           && sect_off >= this_cu->sect_off + this_cu->length)
23789         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23790       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23791       return this_cu;
23792     }
23793 }
23794
23795 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23796
23797 static void
23798 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23799 {
23800   memset (cu, 0, sizeof (*cu));
23801   per_cu->cu = cu;
23802   cu->per_cu = per_cu;
23803   cu->objfile = per_cu->objfile;
23804   obstack_init (&cu->comp_unit_obstack);
23805 }
23806
23807 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23808
23809 static void
23810 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23811                        enum language pretend_language)
23812 {
23813   struct attribute *attr;
23814
23815   /* Set the language we're debugging.  */
23816   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23817   if (attr)
23818     set_cu_language (DW_UNSND (attr), cu);
23819   else
23820     {
23821       cu->language = pretend_language;
23822       cu->language_defn = language_def (cu->language);
23823     }
23824
23825   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23826 }
23827
23828 /* Release one cached compilation unit, CU.  We unlink it from the tree
23829    of compilation units, but we don't remove it from the read_in_chain;
23830    the caller is responsible for that.
23831    NOTE: DATA is a void * because this function is also used as a
23832    cleanup routine.  */
23833
23834 static void
23835 free_heap_comp_unit (void *data)
23836 {
23837   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23838
23839   gdb_assert (cu->per_cu != NULL);
23840   cu->per_cu->cu = NULL;
23841   cu->per_cu = NULL;
23842
23843   obstack_free (&cu->comp_unit_obstack, NULL);
23844
23845   xfree (cu);
23846 }
23847
23848 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23849    when we're finished with it.  We can't free the pointer itself, but be
23850    sure to unlink it from the cache.  Also release any associated storage.  */
23851
23852 static void
23853 free_stack_comp_unit (void *data)
23854 {
23855   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23856
23857   gdb_assert (cu->per_cu != NULL);
23858   cu->per_cu->cu = NULL;
23859   cu->per_cu = NULL;
23860
23861   obstack_free (&cu->comp_unit_obstack, NULL);
23862   cu->partial_dies = NULL;
23863 }
23864
23865 /* Free all cached compilation units.  */
23866
23867 static void
23868 free_cached_comp_units (void *data)
23869 {
23870   dwarf2_per_objfile->free_cached_comp_units ();
23871 }
23872
23873 /* Increase the age counter on each cached compilation unit, and free
23874    any that are too old.  */
23875
23876 static void
23877 age_cached_comp_units (void)
23878 {
23879   struct dwarf2_per_cu_data *per_cu, **last_chain;
23880
23881   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23882   per_cu = dwarf2_per_objfile->read_in_chain;
23883   while (per_cu != NULL)
23884     {
23885       per_cu->cu->last_used ++;
23886       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23887         dwarf2_mark (per_cu->cu);
23888       per_cu = per_cu->cu->read_in_chain;
23889     }
23890
23891   per_cu = dwarf2_per_objfile->read_in_chain;
23892   last_chain = &dwarf2_per_objfile->read_in_chain;
23893   while (per_cu != NULL)
23894     {
23895       struct dwarf2_per_cu_data *next_cu;
23896
23897       next_cu = per_cu->cu->read_in_chain;
23898
23899       if (!per_cu->cu->mark)
23900         {
23901           free_heap_comp_unit (per_cu->cu);
23902           *last_chain = next_cu;
23903         }
23904       else
23905         last_chain = &per_cu->cu->read_in_chain;
23906
23907       per_cu = next_cu;
23908     }
23909 }
23910
23911 /* Remove a single compilation unit from the cache.  */
23912
23913 static void
23914 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23915 {
23916   struct dwarf2_per_cu_data *per_cu, **last_chain;
23917
23918   per_cu = dwarf2_per_objfile->read_in_chain;
23919   last_chain = &dwarf2_per_objfile->read_in_chain;
23920   while (per_cu != NULL)
23921     {
23922       struct dwarf2_per_cu_data *next_cu;
23923
23924       next_cu = per_cu->cu->read_in_chain;
23925
23926       if (per_cu == target_per_cu)
23927         {
23928           free_heap_comp_unit (per_cu->cu);
23929           per_cu->cu = NULL;
23930           *last_chain = next_cu;
23931           break;
23932         }
23933       else
23934         last_chain = &per_cu->cu->read_in_chain;
23935
23936       per_cu = next_cu;
23937     }
23938 }
23939
23940 /* Release all extra memory associated with OBJFILE.  */
23941
23942 void
23943 dwarf2_free_objfile (struct objfile *objfile)
23944 {
23945   dwarf2_per_objfile
23946     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23947                                                   dwarf2_objfile_data_key);
23948
23949   if (dwarf2_per_objfile == NULL)
23950     return;
23951
23952   dwarf2_per_objfile->~dwarf2_per_objfile ();
23953 }
23954
23955 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23956    We store these in a hash table separate from the DIEs, and preserve them
23957    when the DIEs are flushed out of cache.
23958
23959    The CU "per_cu" pointer is needed because offset alone is not enough to
23960    uniquely identify the type.  A file may have multiple .debug_types sections,
23961    or the type may come from a DWO file.  Furthermore, while it's more logical
23962    to use per_cu->section+offset, with Fission the section with the data is in
23963    the DWO file but we don't know that section at the point we need it.
23964    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23965    because we can enter the lookup routine, get_die_type_at_offset, from
23966    outside this file, and thus won't necessarily have PER_CU->cu.
23967    Fortunately, PER_CU is stable for the life of the objfile.  */
23968
23969 struct dwarf2_per_cu_offset_and_type
23970 {
23971   const struct dwarf2_per_cu_data *per_cu;
23972   sect_offset sect_off;
23973   struct type *type;
23974 };
23975
23976 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23977
23978 static hashval_t
23979 per_cu_offset_and_type_hash (const void *item)
23980 {
23981   const struct dwarf2_per_cu_offset_and_type *ofs
23982     = (const struct dwarf2_per_cu_offset_and_type *) item;
23983
23984   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23985 }
23986
23987 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23988
23989 static int
23990 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23991 {
23992   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23993     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23994   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23995     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23996
23997   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23998           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23999 }
24000
24001 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
24002    table if necessary.  For convenience, return TYPE.
24003
24004    The DIEs reading must have careful ordering to:
24005     * Not cause infite loops trying to read in DIEs as a prerequisite for
24006       reading current DIE.
24007     * Not trying to dereference contents of still incompletely read in types
24008       while reading in other DIEs.
24009     * Enable referencing still incompletely read in types just by a pointer to
24010       the type without accessing its fields.
24011
24012    Therefore caller should follow these rules:
24013      * Try to fetch any prerequisite types we may need to build this DIE type
24014        before building the type and calling set_die_type.
24015      * After building type call set_die_type for current DIE as soon as
24016        possible before fetching more types to complete the current type.
24017      * Make the type as complete as possible before fetching more types.  */
24018
24019 static struct type *
24020 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
24021 {
24022   struct dwarf2_per_cu_offset_and_type **slot, ofs;
24023   struct objfile *objfile = cu->objfile;
24024   struct attribute *attr;
24025   struct dynamic_prop prop;
24026
24027   /* For Ada types, make sure that the gnat-specific data is always
24028      initialized (if not already set).  There are a few types where
24029      we should not be doing so, because the type-specific area is
24030      already used to hold some other piece of info (eg: TYPE_CODE_FLT
24031      where the type-specific area is used to store the floatformat).
24032      But this is not a problem, because the gnat-specific information
24033      is actually not needed for these types.  */
24034   if (need_gnat_info (cu)
24035       && TYPE_CODE (type) != TYPE_CODE_FUNC
24036       && TYPE_CODE (type) != TYPE_CODE_FLT
24037       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
24038       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
24039       && TYPE_CODE (type) != TYPE_CODE_METHOD
24040       && !HAVE_GNAT_AUX_INFO (type))
24041     INIT_GNAT_SPECIFIC (type);
24042
24043   /* Read DW_AT_allocated and set in type.  */
24044   attr = dwarf2_attr (die, DW_AT_allocated, cu);
24045   if (attr_form_is_block (attr))
24046     {
24047       if (attr_to_dynamic_prop (attr, die, cu, &prop))
24048         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
24049     }
24050   else if (attr != NULL)
24051     {
24052       complaint (&symfile_complaints,
24053                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
24054                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24055                  to_underlying (die->sect_off));
24056     }
24057
24058   /* Read DW_AT_associated and set in type.  */
24059   attr = dwarf2_attr (die, DW_AT_associated, cu);
24060   if (attr_form_is_block (attr))
24061     {
24062       if (attr_to_dynamic_prop (attr, die, cu, &prop))
24063         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
24064     }
24065   else if (attr != NULL)
24066     {
24067       complaint (&symfile_complaints,
24068                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
24069                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
24070                  to_underlying (die->sect_off));
24071     }
24072
24073   /* Read DW_AT_data_location and set in type.  */
24074   attr = dwarf2_attr (die, DW_AT_data_location, cu);
24075   if (attr_to_dynamic_prop (attr, die, cu, &prop))
24076     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
24077
24078   if (dwarf2_per_objfile->die_type_hash == NULL)
24079     {
24080       dwarf2_per_objfile->die_type_hash =
24081         htab_create_alloc_ex (127,
24082                               per_cu_offset_and_type_hash,
24083                               per_cu_offset_and_type_eq,
24084                               NULL,
24085                               &objfile->objfile_obstack,
24086                               hashtab_obstack_allocate,
24087                               dummy_obstack_deallocate);
24088     }
24089
24090   ofs.per_cu = cu->per_cu;
24091   ofs.sect_off = die->sect_off;
24092   ofs.type = type;
24093   slot = (struct dwarf2_per_cu_offset_and_type **)
24094     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
24095   if (*slot)
24096     complaint (&symfile_complaints,
24097                _("A problem internal to GDB: DIE 0x%x has type already set"),
24098                to_underlying (die->sect_off));
24099   *slot = XOBNEW (&objfile->objfile_obstack,
24100                   struct dwarf2_per_cu_offset_and_type);
24101   **slot = ofs;
24102   return type;
24103 }
24104
24105 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
24106    or return NULL if the die does not have a saved type.  */
24107
24108 static struct type *
24109 get_die_type_at_offset (sect_offset sect_off,
24110                         struct dwarf2_per_cu_data *per_cu)
24111 {
24112   struct dwarf2_per_cu_offset_and_type *slot, ofs;
24113
24114   if (dwarf2_per_objfile->die_type_hash == NULL)
24115     return NULL;
24116
24117   ofs.per_cu = per_cu;
24118   ofs.sect_off = sect_off;
24119   slot = ((struct dwarf2_per_cu_offset_and_type *)
24120           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
24121   if (slot)
24122     return slot->type;
24123   else
24124     return NULL;
24125 }
24126
24127 /* Look up the type for DIE in CU in die_type_hash,
24128    or return NULL if DIE does not have a saved type.  */
24129
24130 static struct type *
24131 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
24132 {
24133   return get_die_type_at_offset (die->sect_off, cu->per_cu);
24134 }
24135
24136 /* Add a dependence relationship from CU to REF_PER_CU.  */
24137
24138 static void
24139 dwarf2_add_dependence (struct dwarf2_cu *cu,
24140                        struct dwarf2_per_cu_data *ref_per_cu)
24141 {
24142   void **slot;
24143
24144   if (cu->dependencies == NULL)
24145     cu->dependencies
24146       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
24147                               NULL, &cu->comp_unit_obstack,
24148                               hashtab_obstack_allocate,
24149                               dummy_obstack_deallocate);
24150
24151   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
24152   if (*slot == NULL)
24153     *slot = ref_per_cu;
24154 }
24155
24156 /* Subroutine of dwarf2_mark to pass to htab_traverse.
24157    Set the mark field in every compilation unit in the
24158    cache that we must keep because we are keeping CU.  */
24159
24160 static int
24161 dwarf2_mark_helper (void **slot, void *data)
24162 {
24163   struct dwarf2_per_cu_data *per_cu;
24164
24165   per_cu = (struct dwarf2_per_cu_data *) *slot;
24166
24167   /* cu->dependencies references may not yet have been ever read if QUIT aborts
24168      reading of the chain.  As such dependencies remain valid it is not much
24169      useful to track and undo them during QUIT cleanups.  */
24170   if (per_cu->cu == NULL)
24171     return 1;
24172
24173   if (per_cu->cu->mark)
24174     return 1;
24175   per_cu->cu->mark = 1;
24176
24177   if (per_cu->cu->dependencies != NULL)
24178     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
24179
24180   return 1;
24181 }
24182
24183 /* Set the mark field in CU and in every other compilation unit in the
24184    cache that we must keep because we are keeping CU.  */
24185
24186 static void
24187 dwarf2_mark (struct dwarf2_cu *cu)
24188 {
24189   if (cu->mark)
24190     return;
24191   cu->mark = 1;
24192   if (cu->dependencies != NULL)
24193     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
24194 }
24195
24196 static void
24197 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
24198 {
24199   while (per_cu)
24200     {
24201       per_cu->cu->mark = 0;
24202       per_cu = per_cu->cu->read_in_chain;
24203     }
24204 }
24205
24206 /* Trivial hash function for partial_die_info: the hash value of a DIE
24207    is its offset in .debug_info for this objfile.  */
24208
24209 static hashval_t
24210 partial_die_hash (const void *item)
24211 {
24212   const struct partial_die_info *part_die
24213     = (const struct partial_die_info *) item;
24214
24215   return to_underlying (part_die->sect_off);
24216 }
24217
24218 /* Trivial comparison function for partial_die_info structures: two DIEs
24219    are equal if they have the same offset.  */
24220
24221 static int
24222 partial_die_eq (const void *item_lhs, const void *item_rhs)
24223 {
24224   const struct partial_die_info *part_die_lhs
24225     = (const struct partial_die_info *) item_lhs;
24226   const struct partial_die_info *part_die_rhs
24227     = (const struct partial_die_info *) item_rhs;
24228
24229   return part_die_lhs->sect_off == part_die_rhs->sect_off;
24230 }
24231
24232 static struct cmd_list_element *set_dwarf_cmdlist;
24233 static struct cmd_list_element *show_dwarf_cmdlist;
24234
24235 static void
24236 set_dwarf_cmd (const char *args, int from_tty)
24237 {
24238   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
24239              gdb_stdout);
24240 }
24241
24242 static void
24243 show_dwarf_cmd (const char *args, int from_tty)
24244 {
24245   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
24246 }
24247
24248 /* Free data associated with OBJFILE, if necessary.  */
24249
24250 static void
24251 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
24252 {
24253   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
24254   int ix;
24255
24256   /* Make sure we don't accidentally use dwarf2_per_objfile while
24257      cleaning up.  */
24258   dwarf2_per_objfile = NULL;
24259
24260   for (ix = 0; ix < data->n_comp_units; ++ix)
24261    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
24262
24263   for (ix = 0; ix < data->n_type_units; ++ix)
24264     VEC_free (dwarf2_per_cu_ptr,
24265               data->all_type_units[ix]->per_cu.imported_symtabs);
24266   xfree (data->all_type_units);
24267
24268   VEC_free (dwarf2_section_info_def, data->types);
24269
24270   if (data->dwo_files)
24271     free_dwo_files (data->dwo_files, objfile);
24272   if (data->dwp_file)
24273     gdb_bfd_unref (data->dwp_file->dbfd);
24274
24275   if (data->dwz_file && data->dwz_file->dwz_bfd)
24276     gdb_bfd_unref (data->dwz_file->dwz_bfd);
24277
24278   if (data->index_table != NULL)
24279     data->index_table->~mapped_index ();
24280 }
24281
24282 \f
24283 /* The "save gdb-index" command.  */
24284
24285 /* Write SIZE bytes from the buffer pointed to by DATA to FILE, with
24286    error checking.  */
24287
24288 static void
24289 file_write (FILE *file, const void *data, size_t size)
24290 {
24291   if (fwrite (data, 1, size, file) != size)
24292     error (_("couldn't data write to file"));
24293 }
24294
24295 /* Write the contents of VEC to FILE, with error checking.  */
24296
24297 template<typename Elem, typename Alloc>
24298 static void
24299 file_write (FILE *file, const std::vector<Elem, Alloc> &vec)
24300 {
24301   file_write (file, vec.data (), vec.size () * sizeof (vec[0]));
24302 }
24303
24304 /* In-memory buffer to prepare data to be written later to a file.  */
24305 class data_buf
24306 {
24307 public:
24308   /* Copy DATA to the end of the buffer.  */
24309   template<typename T>
24310   void append_data (const T &data)
24311   {
24312     std::copy (reinterpret_cast<const gdb_byte *> (&data),
24313                reinterpret_cast<const gdb_byte *> (&data + 1),
24314                grow (sizeof (data)));
24315   }
24316
24317   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
24318      terminating zero is appended too.  */
24319   void append_cstr0 (const char *cstr)
24320   {
24321     const size_t size = strlen (cstr) + 1;
24322     std::copy (cstr, cstr + size, grow (size));
24323   }
24324
24325   /* Store INPUT as ULEB128 to the end of buffer.  */
24326   void append_unsigned_leb128 (ULONGEST input)
24327   {
24328     for (;;)
24329       {
24330         gdb_byte output = input & 0x7f;
24331         input >>= 7;
24332         if (input)
24333           output |= 0x80;
24334         append_data (output);
24335         if (input == 0)
24336           break;
24337       }
24338   }
24339
24340   /* Accept a host-format integer in VAL and append it to the buffer
24341      as a target-format integer which is LEN bytes long.  */
24342   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
24343   {
24344     ::store_unsigned_integer (grow (len), len, byte_order, val);
24345   }
24346
24347   /* Return the size of the buffer.  */
24348   size_t size () const
24349   {
24350     return m_vec.size ();
24351   }
24352
24353   /* Return true iff the buffer is empty.  */
24354   bool empty () const
24355   {
24356     return m_vec.empty ();
24357   }
24358
24359   /* Write the buffer to FILE.  */
24360   void file_write (FILE *file) const
24361   {
24362     ::file_write (file, m_vec);
24363   }
24364
24365 private:
24366   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
24367      the start of the new block.  */
24368   gdb_byte *grow (size_t size)
24369   {
24370     m_vec.resize (m_vec.size () + size);
24371     return &*m_vec.end () - size;
24372   }
24373
24374   gdb::byte_vector m_vec;
24375 };
24376
24377 /* An entry in the symbol table.  */
24378 struct symtab_index_entry
24379 {
24380   /* The name of the symbol.  */
24381   const char *name;
24382   /* The offset of the name in the constant pool.  */
24383   offset_type index_offset;
24384   /* A sorted vector of the indices of all the CUs that hold an object
24385      of this name.  */
24386   std::vector<offset_type> cu_indices;
24387 };
24388
24389 /* The symbol table.  This is a power-of-2-sized hash table.  */
24390 struct mapped_symtab
24391 {
24392   mapped_symtab ()
24393   {
24394     data.resize (1024);
24395   }
24396
24397   offset_type n_elements = 0;
24398   std::vector<symtab_index_entry> data;
24399 };
24400
24401 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
24402    the slot.
24403    
24404    Function is used only during write_hash_table so no index format backward
24405    compatibility is needed.  */
24406
24407 static symtab_index_entry &
24408 find_slot (struct mapped_symtab *symtab, const char *name)
24409 {
24410   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
24411
24412   index = hash & (symtab->data.size () - 1);
24413   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
24414
24415   for (;;)
24416     {
24417       if (symtab->data[index].name == NULL
24418           || strcmp (name, symtab->data[index].name) == 0)
24419         return symtab->data[index];
24420       index = (index + step) & (symtab->data.size () - 1);
24421     }
24422 }
24423
24424 /* Expand SYMTAB's hash table.  */
24425
24426 static void
24427 hash_expand (struct mapped_symtab *symtab)
24428 {
24429   auto old_entries = std::move (symtab->data);
24430
24431   symtab->data.clear ();
24432   symtab->data.resize (old_entries.size () * 2);
24433
24434   for (auto &it : old_entries)
24435     if (it.name != NULL)
24436       {
24437         auto &ref = find_slot (symtab, it.name);
24438         ref = std::move (it);
24439       }
24440 }
24441
24442 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
24443    CU_INDEX is the index of the CU in which the symbol appears.
24444    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
24445
24446 static void
24447 add_index_entry (struct mapped_symtab *symtab, const char *name,
24448                  int is_static, gdb_index_symbol_kind kind,
24449                  offset_type cu_index)
24450 {
24451   offset_type cu_index_and_attrs;
24452
24453   ++symtab->n_elements;
24454   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
24455     hash_expand (symtab);
24456
24457   symtab_index_entry &slot = find_slot (symtab, name);
24458   if (slot.name == NULL)
24459     {
24460       slot.name = name;
24461       /* index_offset is set later.  */
24462     }
24463
24464   cu_index_and_attrs = 0;
24465   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
24466   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
24467   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
24468
24469   /* We don't want to record an index value twice as we want to avoid the
24470      duplication.
24471      We process all global symbols and then all static symbols
24472      (which would allow us to avoid the duplication by only having to check
24473      the last entry pushed), but a symbol could have multiple kinds in one CU.
24474      To keep things simple we don't worry about the duplication here and
24475      sort and uniqufy the list after we've processed all symbols.  */
24476   slot.cu_indices.push_back (cu_index_and_attrs);
24477 }
24478
24479 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
24480
24481 static void
24482 uniquify_cu_indices (struct mapped_symtab *symtab)
24483 {
24484   for (auto &entry : symtab->data)
24485     {
24486       if (entry.name != NULL && !entry.cu_indices.empty ())
24487         {
24488           auto &cu_indices = entry.cu_indices;
24489           std::sort (cu_indices.begin (), cu_indices.end ());
24490           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
24491           cu_indices.erase (from, cu_indices.end ());
24492         }
24493     }
24494 }
24495
24496 /* A form of 'const char *' suitable for container keys.  Only the
24497    pointer is stored.  The strings themselves are compared, not the
24498    pointers.  */
24499 class c_str_view
24500 {
24501 public:
24502   c_str_view (const char *cstr)
24503     : m_cstr (cstr)
24504   {}
24505
24506   bool operator== (const c_str_view &other) const
24507   {
24508     return strcmp (m_cstr, other.m_cstr) == 0;
24509   }
24510
24511   /* Return the underlying C string.  Note, the returned string is
24512      only a reference with lifetime of this object.  */
24513   const char *c_str () const
24514   {
24515     return m_cstr;
24516   }
24517
24518 private:
24519   friend class c_str_view_hasher;
24520   const char *const m_cstr;
24521 };
24522
24523 /* A std::unordered_map::hasher for c_str_view that uses the right
24524    hash function for strings in a mapped index.  */
24525 class c_str_view_hasher
24526 {
24527 public:
24528   size_t operator () (const c_str_view &x) const
24529   {
24530     return mapped_index_string_hash (INT_MAX, x.m_cstr);
24531   }
24532 };
24533
24534 /* A std::unordered_map::hasher for std::vector<>.  */
24535 template<typename T>
24536 class vector_hasher
24537 {
24538 public:
24539   size_t operator () (const std::vector<T> &key) const
24540   {
24541     return iterative_hash (key.data (),
24542                            sizeof (key.front ()) * key.size (), 0);
24543   }
24544 };
24545
24546 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
24547    constant pool entries going into the data buffer CPOOL.  */
24548
24549 static void
24550 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
24551 {
24552   {
24553     /* Elements are sorted vectors of the indices of all the CUs that
24554        hold an object of this name.  */
24555     std::unordered_map<std::vector<offset_type>, offset_type,
24556                        vector_hasher<offset_type>>
24557       symbol_hash_table;
24558
24559     /* We add all the index vectors to the constant pool first, to
24560        ensure alignment is ok.  */
24561     for (symtab_index_entry &entry : symtab->data)
24562       {
24563         if (entry.name == NULL)
24564           continue;
24565         gdb_assert (entry.index_offset == 0);
24566
24567         /* Finding before inserting is faster than always trying to
24568            insert, because inserting always allocates a node, does the
24569            lookup, and then destroys the new node if another node
24570            already had the same key.  C++17 try_emplace will avoid
24571            this.  */
24572         const auto found
24573           = symbol_hash_table.find (entry.cu_indices);
24574         if (found != symbol_hash_table.end ())
24575           {
24576             entry.index_offset = found->second;
24577             continue;
24578           }
24579
24580         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
24581         entry.index_offset = cpool.size ();
24582         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
24583         for (const auto index : entry.cu_indices)
24584           cpool.append_data (MAYBE_SWAP (index));
24585       }
24586   }
24587
24588   /* Now write out the hash table.  */
24589   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
24590   for (const auto &entry : symtab->data)
24591     {
24592       offset_type str_off, vec_off;
24593
24594       if (entry.name != NULL)
24595         {
24596           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
24597           if (insertpair.second)
24598             cpool.append_cstr0 (entry.name);
24599           str_off = insertpair.first->second;
24600           vec_off = entry.index_offset;
24601         }
24602       else
24603         {
24604           /* While 0 is a valid constant pool index, it is not valid
24605              to have 0 for both offsets.  */
24606           str_off = 0;
24607           vec_off = 0;
24608         }
24609
24610       output.append_data (MAYBE_SWAP (str_off));
24611       output.append_data (MAYBE_SWAP (vec_off));
24612     }
24613 }
24614
24615 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
24616
24617 /* Helper struct for building the address table.  */
24618 struct addrmap_index_data
24619 {
24620   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
24621     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
24622   {}
24623
24624   struct objfile *objfile;
24625   data_buf &addr_vec;
24626   psym_index_map &cu_index_htab;
24627
24628   /* Non-zero if the previous_* fields are valid.
24629      We can't write an entry until we see the next entry (since it is only then
24630      that we know the end of the entry).  */
24631   int previous_valid;
24632   /* Index of the CU in the table of all CUs in the index file.  */
24633   unsigned int previous_cu_index;
24634   /* Start address of the CU.  */
24635   CORE_ADDR previous_cu_start;
24636 };
24637
24638 /* Write an address entry to ADDR_VEC.  */
24639
24640 static void
24641 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
24642                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
24643 {
24644   CORE_ADDR baseaddr;
24645
24646   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
24647
24648   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
24649   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
24650   addr_vec.append_data (MAYBE_SWAP (cu_index));
24651 }
24652
24653 /* Worker function for traversing an addrmap to build the address table.  */
24654
24655 static int
24656 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
24657 {
24658   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
24659   struct partial_symtab *pst = (struct partial_symtab *) obj;
24660
24661   if (data->previous_valid)
24662     add_address_entry (data->objfile, data->addr_vec,
24663                        data->previous_cu_start, start_addr,
24664                        data->previous_cu_index);
24665
24666   data->previous_cu_start = start_addr;
24667   if (pst != NULL)
24668     {
24669       const auto it = data->cu_index_htab.find (pst);
24670       gdb_assert (it != data->cu_index_htab.cend ());
24671       data->previous_cu_index = it->second;
24672       data->previous_valid = 1;
24673     }
24674   else
24675     data->previous_valid = 0;
24676
24677   return 0;
24678 }
24679
24680 /* Write OBJFILE's address map to ADDR_VEC.
24681    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
24682    in the index file.  */
24683
24684 static void
24685 write_address_map (struct objfile *objfile, data_buf &addr_vec,
24686                    psym_index_map &cu_index_htab)
24687 {
24688   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
24689
24690   /* When writing the address table, we have to cope with the fact that
24691      the addrmap iterator only provides the start of a region; we have to
24692      wait until the next invocation to get the start of the next region.  */
24693
24694   addrmap_index_data.objfile = objfile;
24695   addrmap_index_data.previous_valid = 0;
24696
24697   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
24698                    &addrmap_index_data);
24699
24700   /* It's highly unlikely the last entry (end address = 0xff...ff)
24701      is valid, but we should still handle it.
24702      The end address is recorded as the start of the next region, but that
24703      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
24704      anyway.  */
24705   if (addrmap_index_data.previous_valid)
24706     add_address_entry (objfile, addr_vec,
24707                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
24708                        addrmap_index_data.previous_cu_index);
24709 }
24710
24711 /* Return the symbol kind of PSYM.  */
24712
24713 static gdb_index_symbol_kind
24714 symbol_kind (struct partial_symbol *psym)
24715 {
24716   domain_enum domain = PSYMBOL_DOMAIN (psym);
24717   enum address_class aclass = PSYMBOL_CLASS (psym);
24718
24719   switch (domain)
24720     {
24721     case VAR_DOMAIN:
24722       switch (aclass)
24723         {
24724         case LOC_BLOCK:
24725           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
24726         case LOC_TYPEDEF:
24727           return GDB_INDEX_SYMBOL_KIND_TYPE;
24728         case LOC_COMPUTED:
24729         case LOC_CONST_BYTES:
24730         case LOC_OPTIMIZED_OUT:
24731         case LOC_STATIC:
24732           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24733         case LOC_CONST:
24734           /* Note: It's currently impossible to recognize psyms as enum values
24735              short of reading the type info.  For now punt.  */
24736           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
24737         default:
24738           /* There are other LOC_FOO values that one might want to classify
24739              as variables, but dwarf2read.c doesn't currently use them.  */
24740           return GDB_INDEX_SYMBOL_KIND_OTHER;
24741         }
24742     case STRUCT_DOMAIN:
24743       return GDB_INDEX_SYMBOL_KIND_TYPE;
24744     default:
24745       return GDB_INDEX_SYMBOL_KIND_OTHER;
24746     }
24747 }
24748
24749 /* Add a list of partial symbols to SYMTAB.  */
24750
24751 static void
24752 write_psymbols (struct mapped_symtab *symtab,
24753                 std::unordered_set<partial_symbol *> &psyms_seen,
24754                 struct partial_symbol **psymp,
24755                 int count,
24756                 offset_type cu_index,
24757                 int is_static)
24758 {
24759   for (; count-- > 0; ++psymp)
24760     {
24761       struct partial_symbol *psym = *psymp;
24762
24763       if (SYMBOL_LANGUAGE (psym) == language_ada)
24764         error (_("Ada is not currently supported by the index"));
24765
24766       /* Only add a given psymbol once.  */
24767       if (psyms_seen.insert (psym).second)
24768         {
24769           gdb_index_symbol_kind kind = symbol_kind (psym);
24770
24771           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24772                            is_static, kind, cu_index);
24773         }
24774     }
24775 }
24776
24777 /* A helper struct used when iterating over debug_types.  */
24778 struct signatured_type_index_data
24779 {
24780   signatured_type_index_data (data_buf &types_list_,
24781                               std::unordered_set<partial_symbol *> &psyms_seen_)
24782     : types_list (types_list_), psyms_seen (psyms_seen_)
24783   {}
24784
24785   struct objfile *objfile;
24786   struct mapped_symtab *symtab;
24787   data_buf &types_list;
24788   std::unordered_set<partial_symbol *> &psyms_seen;
24789   int cu_index;
24790 };
24791
24792 /* A helper function that writes a single signatured_type to an
24793    obstack.  */
24794
24795 static int
24796 write_one_signatured_type (void **slot, void *d)
24797 {
24798   struct signatured_type_index_data *info
24799     = (struct signatured_type_index_data *) d;
24800   struct signatured_type *entry = (struct signatured_type *) *slot;
24801   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24802
24803   write_psymbols (info->symtab,
24804                   info->psyms_seen,
24805                   &info->objfile->global_psymbols[psymtab->globals_offset],
24806                   psymtab->n_global_syms, info->cu_index,
24807                   0);
24808   write_psymbols (info->symtab,
24809                   info->psyms_seen,
24810                   &info->objfile->static_psymbols[psymtab->statics_offset],
24811                   psymtab->n_static_syms, info->cu_index,
24812                   1);
24813
24814   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24815                                 to_underlying (entry->per_cu.sect_off));
24816   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24817                                 to_underlying (entry->type_offset_in_tu));
24818   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24819
24820   ++info->cu_index;
24821
24822   return 1;
24823 }
24824
24825 /* Recurse into all "included" dependencies and count their symbols as
24826    if they appeared in this psymtab.  */
24827
24828 static void
24829 recursively_count_psymbols (struct partial_symtab *psymtab,
24830                             size_t &psyms_seen)
24831 {
24832   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24833     if (psymtab->dependencies[i]->user != NULL)
24834       recursively_count_psymbols (psymtab->dependencies[i],
24835                                   psyms_seen);
24836
24837   psyms_seen += psymtab->n_global_syms;
24838   psyms_seen += psymtab->n_static_syms;
24839 }
24840
24841 /* Recurse into all "included" dependencies and write their symbols as
24842    if they appeared in this psymtab.  */
24843
24844 static void
24845 recursively_write_psymbols (struct objfile *objfile,
24846                             struct partial_symtab *psymtab,
24847                             struct mapped_symtab *symtab,
24848                             std::unordered_set<partial_symbol *> &psyms_seen,
24849                             offset_type cu_index)
24850 {
24851   int i;
24852
24853   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24854     if (psymtab->dependencies[i]->user != NULL)
24855       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24856                                   symtab, psyms_seen, cu_index);
24857
24858   write_psymbols (symtab,
24859                   psyms_seen,
24860                   &objfile->global_psymbols[psymtab->globals_offset],
24861                   psymtab->n_global_syms, cu_index,
24862                   0);
24863   write_psymbols (symtab,
24864                   psyms_seen,
24865                   &objfile->static_psymbols[psymtab->statics_offset],
24866                   psymtab->n_static_syms, cu_index,
24867                   1);
24868 }
24869
24870 /* Symbol name hashing function as specified by DWARF-5.  */
24871
24872 static uint32_t
24873 dwarf5_djb_hash (const char *str_)
24874 {
24875   const unsigned char *str = (const unsigned char *) str_;
24876
24877   /* Note: tolower here ignores UTF-8, which isn't fully compliant.
24878      See http://dwarfstd.org/ShowIssue.php?issue=161027.1.  */
24879
24880   uint32_t hash = 5381;
24881   while (int c = *str++)
24882     hash = hash * 33 + tolower (c);
24883   return hash;
24884 }
24885
24886 /* DWARF-5 .debug_names builder.  */
24887 class debug_names
24888 {
24889 public:
24890   debug_names (bool is_dwarf64, bfd_endian dwarf5_byte_order)
24891     : m_dwarf5_byte_order (dwarf5_byte_order),
24892       m_dwarf32 (dwarf5_byte_order),
24893       m_dwarf64 (dwarf5_byte_order),
24894       m_dwarf (is_dwarf64
24895                ? static_cast<dwarf &> (m_dwarf64)
24896                : static_cast<dwarf &> (m_dwarf32)),
24897       m_name_table_string_offs (m_dwarf.name_table_string_offs),
24898       m_name_table_entry_offs (m_dwarf.name_table_entry_offs)
24899   {}
24900
24901   /* Insert one symbol.  */
24902   void insert (const partial_symbol *psym, int cu_index, bool is_static)
24903   {
24904     const int dwarf_tag = psymbol_tag (psym);
24905     if (dwarf_tag == 0)
24906       return;
24907     const char *const name = SYMBOL_SEARCH_NAME (psym);
24908     const auto insertpair
24909       = m_name_to_value_set.emplace (c_str_view (name),
24910                                      std::set<symbol_value> ());
24911     std::set<symbol_value> &value_set = insertpair.first->second;
24912     value_set.emplace (symbol_value (dwarf_tag, cu_index, is_static));
24913   }
24914
24915   /* Build all the tables.  All symbols must be already inserted.
24916      This function does not call file_write, caller has to do it
24917      afterwards.  */
24918   void build ()
24919   {
24920     /* Verify the build method has not be called twice.  */
24921     gdb_assert (m_abbrev_table.empty ());
24922     const size_t name_count = m_name_to_value_set.size ();
24923     m_bucket_table.resize
24924       (std::pow (2, std::ceil (std::log2 (name_count * 4 / 3))));
24925     m_hash_table.reserve (name_count);
24926     m_name_table_string_offs.reserve (name_count);
24927     m_name_table_entry_offs.reserve (name_count);
24928
24929     /* Map each hash of symbol to its name and value.  */
24930     struct hash_it_pair
24931     {
24932       uint32_t hash;
24933       decltype (m_name_to_value_set)::const_iterator it;
24934     };
24935     std::vector<std::forward_list<hash_it_pair>> bucket_hash;
24936     bucket_hash.resize (m_bucket_table.size ());
24937     for (decltype (m_name_to_value_set)::const_iterator it
24938            = m_name_to_value_set.cbegin ();
24939          it != m_name_to_value_set.cend ();
24940          ++it)
24941       {
24942         const char *const name = it->first.c_str ();
24943         const uint32_t hash = dwarf5_djb_hash (name);
24944         hash_it_pair hashitpair;
24945         hashitpair.hash = hash;
24946         hashitpair.it = it;
24947         auto &slot = bucket_hash[hash % bucket_hash.size()];
24948         slot.push_front (std::move (hashitpair));
24949       }
24950     for (size_t bucket_ix = 0; bucket_ix < bucket_hash.size (); ++bucket_ix)
24951       {
24952         const std::forward_list<hash_it_pair> &hashitlist
24953           = bucket_hash[bucket_ix];
24954         if (hashitlist.empty ())
24955           continue;
24956         uint32_t &bucket_slot = m_bucket_table[bucket_ix];
24957         /* The hashes array is indexed starting at 1.  */
24958         store_unsigned_integer (reinterpret_cast<gdb_byte *> (&bucket_slot),
24959                                 sizeof (bucket_slot), m_dwarf5_byte_order,
24960                                 m_hash_table.size () + 1);
24961         for (const hash_it_pair &hashitpair : hashitlist)
24962           {
24963             m_hash_table.push_back (0);
24964             store_unsigned_integer (reinterpret_cast<gdb_byte *>
24965                                                         (&m_hash_table.back ()),
24966                                     sizeof (m_hash_table.back ()),
24967                                     m_dwarf5_byte_order, hashitpair.hash);
24968             const c_str_view &name = hashitpair.it->first;
24969             const std::set<symbol_value> &value_set = hashitpair.it->second;
24970             m_name_table_string_offs.push_back_reorder
24971               (m_debugstrlookup.lookup (name.c_str ()));
24972             m_name_table_entry_offs.push_back_reorder (m_entry_pool.size ());
24973             gdb_assert (!value_set.empty ());
24974             for (const symbol_value &value : value_set)
24975               {
24976                 int &idx = m_indexkey_to_idx[index_key (value.dwarf_tag,
24977                                                         value.is_static)];
24978                 if (idx == 0)
24979                   {
24980                     idx = m_idx_next++;
24981                     m_abbrev_table.append_unsigned_leb128 (idx);
24982                     m_abbrev_table.append_unsigned_leb128 (value.dwarf_tag);
24983                     m_abbrev_table.append_unsigned_leb128 (DW_IDX_compile_unit);
24984                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_udata);
24985                     m_abbrev_table.append_unsigned_leb128 (value.is_static
24986                                                            ? DW_IDX_GNU_internal
24987                                                            : DW_IDX_GNU_external);
24988                     m_abbrev_table.append_unsigned_leb128 (DW_FORM_flag_present);
24989
24990                     /* Terminate attributes list.  */
24991                     m_abbrev_table.append_unsigned_leb128 (0);
24992                     m_abbrev_table.append_unsigned_leb128 (0);
24993                   }
24994
24995                 m_entry_pool.append_unsigned_leb128 (idx);
24996                 m_entry_pool.append_unsigned_leb128 (value.cu_index);
24997               }
24998
24999             /* Terminate the list of CUs.  */
25000             m_entry_pool.append_unsigned_leb128 (0);
25001           }
25002       }
25003     gdb_assert (m_hash_table.size () == name_count);
25004
25005     /* Terminate tags list.  */
25006     m_abbrev_table.append_unsigned_leb128 (0);
25007   }
25008
25009   /* Return .debug_names bucket count.  This must be called only after
25010      calling the build method.  */
25011   uint32_t bucket_count () const
25012   {
25013     /* Verify the build method has been already called.  */
25014     gdb_assert (!m_abbrev_table.empty ());
25015     const uint32_t retval = m_bucket_table.size ();
25016
25017     /* Check for overflow.  */
25018     gdb_assert (retval == m_bucket_table.size ());
25019     return retval;
25020   }
25021
25022   /* Return .debug_names names count.  This must be called only after
25023      calling the build method.  */
25024   uint32_t name_count () const
25025   {
25026     /* Verify the build method has been already called.  */
25027     gdb_assert (!m_abbrev_table.empty ());
25028     const uint32_t retval = m_hash_table.size ();
25029
25030     /* Check for overflow.  */
25031     gdb_assert (retval == m_hash_table.size ());
25032     return retval;
25033   }
25034
25035   /* Return number of bytes of .debug_names abbreviation table.  This
25036      must be called only after calling the build method.  */
25037   uint32_t abbrev_table_bytes () const
25038   {
25039     gdb_assert (!m_abbrev_table.empty ());
25040     return m_abbrev_table.size ();
25041   }
25042
25043   /* Recurse into all "included" dependencies and store their symbols
25044      as if they appeared in this psymtab.  */
25045   void recursively_write_psymbols
25046     (struct objfile *objfile,
25047      struct partial_symtab *psymtab,
25048      std::unordered_set<partial_symbol *> &psyms_seen,
25049      int cu_index)
25050   {
25051     for (int i = 0; i < psymtab->number_of_dependencies; ++i)
25052       if (psymtab->dependencies[i]->user != NULL)
25053         recursively_write_psymbols (objfile, psymtab->dependencies[i],
25054                                     psyms_seen, cu_index);
25055
25056     write_psymbols (psyms_seen,
25057                     &objfile->global_psymbols[psymtab->globals_offset],
25058                     psymtab->n_global_syms, cu_index, false);
25059     write_psymbols (psyms_seen,
25060                     &objfile->static_psymbols[psymtab->statics_offset],
25061                     psymtab->n_static_syms, cu_index, true);
25062   }
25063
25064   /* Return number of bytes the .debug_names section will have.  This
25065      must be called only after calling the build method.  */
25066   size_t bytes () const
25067   {
25068     /* Verify the build method has been already called.  */
25069     gdb_assert (!m_abbrev_table.empty ());
25070     size_t expected_bytes = 0;
25071     expected_bytes += m_bucket_table.size () * sizeof (m_bucket_table[0]);
25072     expected_bytes += m_hash_table.size () * sizeof (m_hash_table[0]);
25073     expected_bytes += m_name_table_string_offs.bytes ();
25074     expected_bytes += m_name_table_entry_offs.bytes ();
25075     expected_bytes += m_abbrev_table.size ();
25076     expected_bytes += m_entry_pool.size ();
25077     return expected_bytes;
25078   }
25079
25080   /* Write .debug_names to FILE_NAMES and .debug_str addition to
25081      FILE_STR.  This must be called only after calling the build
25082      method.  */
25083   void file_write (FILE *file_names, FILE *file_str) const
25084   {
25085     /* Verify the build method has been already called.  */
25086     gdb_assert (!m_abbrev_table.empty ());
25087     ::file_write (file_names, m_bucket_table);
25088     ::file_write (file_names, m_hash_table);
25089     m_name_table_string_offs.file_write (file_names);
25090     m_name_table_entry_offs.file_write (file_names);
25091     m_abbrev_table.file_write (file_names);
25092     m_entry_pool.file_write (file_names);
25093     m_debugstrlookup.file_write (file_str);
25094   }
25095
25096 private:
25097
25098   /* Storage for symbol names mapping them to their .debug_str section
25099      offsets.  */
25100   class debug_str_lookup
25101   {
25102   public:
25103
25104     /* Object costructor to be called for current DWARF2_PER_OBJFILE.
25105        All .debug_str section strings are automatically stored.  */
25106     debug_str_lookup ()
25107       : m_abfd (dwarf2_per_objfile->objfile->obfd)
25108     {
25109       dwarf2_read_section (dwarf2_per_objfile->objfile,
25110                            &dwarf2_per_objfile->str);
25111       if (dwarf2_per_objfile->str.buffer == NULL)
25112         return;
25113       for (const gdb_byte *data = dwarf2_per_objfile->str.buffer;
25114            data < (dwarf2_per_objfile->str.buffer
25115                    + dwarf2_per_objfile->str.size);)
25116         {
25117           const char *const s = reinterpret_cast<const char *> (data);
25118           const auto insertpair
25119             = m_str_table.emplace (c_str_view (s),
25120                                    data - dwarf2_per_objfile->str.buffer);
25121           if (!insertpair.second)
25122             complaint (&symfile_complaints,
25123                        _("Duplicate string \"%s\" in "
25124                          ".debug_str section [in module %s]"),
25125                        s, bfd_get_filename (m_abfd));
25126           data += strlen (s) + 1;
25127         }
25128     }
25129
25130     /* Return offset of symbol name S in the .debug_str section.  Add
25131        such symbol to the section's end if it does not exist there
25132        yet.  */
25133     size_t lookup (const char *s)
25134     {
25135       const auto it = m_str_table.find (c_str_view (s));
25136       if (it != m_str_table.end ())
25137         return it->second;
25138       const size_t offset = (dwarf2_per_objfile->str.size
25139                              + m_str_add_buf.size ());
25140       m_str_table.emplace (c_str_view (s), offset);
25141       m_str_add_buf.append_cstr0 (s);
25142       return offset;
25143     }
25144
25145     /* Append the end of the .debug_str section to FILE.  */
25146     void file_write (FILE *file) const
25147     {
25148       m_str_add_buf.file_write (file);
25149     }
25150
25151   private:
25152     std::unordered_map<c_str_view, size_t, c_str_view_hasher> m_str_table;
25153     bfd *const m_abfd;
25154
25155     /* Data to add at the end of .debug_str for new needed symbol names.  */
25156     data_buf m_str_add_buf;
25157   };
25158
25159   /* Container to map used DWARF tags to their .debug_names abbreviation
25160      tags.  */
25161   class index_key
25162   {
25163   public:
25164     index_key (int dwarf_tag_, bool is_static_)
25165       : dwarf_tag (dwarf_tag_), is_static (is_static_)
25166     {
25167     }
25168
25169     bool
25170     operator== (const index_key &other) const
25171     {
25172       return dwarf_tag == other.dwarf_tag && is_static == other.is_static;
25173     }
25174
25175     const int dwarf_tag;
25176     const bool is_static;
25177   };
25178
25179   /* Provide std::unordered_map::hasher for index_key.  */
25180   class index_key_hasher
25181   {
25182   public:
25183     size_t
25184     operator () (const index_key &key) const
25185     {
25186       return (std::hash<int>() (key.dwarf_tag) << 1) | key.is_static;
25187     }
25188   };
25189
25190   /* Parameters of one symbol entry.  */
25191   class symbol_value
25192   {
25193   public:
25194     const int dwarf_tag, cu_index;
25195     const bool is_static;
25196
25197     symbol_value (int dwarf_tag_, int cu_index_, bool is_static_)
25198       : dwarf_tag (dwarf_tag_), cu_index (cu_index_), is_static (is_static_)
25199     {}
25200
25201     bool
25202     operator< (const symbol_value &other) const
25203     {
25204 #define X(n) \
25205   do \
25206     { \
25207       if (n < other.n) \
25208         return true; \
25209       if (n > other.n) \
25210         return false; \
25211     } \
25212   while (0)
25213       X (dwarf_tag);
25214       X (is_static);
25215       X (cu_index);
25216 #undef X
25217       return false;
25218     }
25219   };
25220
25221   /* Abstract base class to unify DWARF-32 and DWARF-64 name table
25222      output.  */
25223   class offset_vec
25224   {
25225   protected:
25226     const bfd_endian dwarf5_byte_order;
25227   public:
25228     explicit offset_vec (bfd_endian dwarf5_byte_order_)
25229       : dwarf5_byte_order (dwarf5_byte_order_)
25230     {}
25231
25232     /* Call std::vector::reserve for NELEM elements.  */
25233     virtual void reserve (size_t nelem) = 0;
25234
25235     /* Call std::vector::push_back with store_unsigned_integer byte
25236        reordering for ELEM.  */
25237     virtual void push_back_reorder (size_t elem) = 0;
25238
25239     /* Return expected output size in bytes.  */
25240     virtual size_t bytes () const = 0;
25241
25242     /* Write name table to FILE.  */
25243     virtual void file_write (FILE *file) const = 0;
25244   };
25245
25246   /* Template to unify DWARF-32 and DWARF-64 output.  */
25247   template<typename OffsetSize>
25248   class offset_vec_tmpl : public offset_vec
25249   {
25250   public:
25251     explicit offset_vec_tmpl (bfd_endian dwarf5_byte_order_)
25252       : offset_vec (dwarf5_byte_order_)
25253     {}
25254
25255     /* Implement offset_vec::reserve.  */
25256     void reserve (size_t nelem) override
25257     {
25258       m_vec.reserve (nelem);
25259     }
25260
25261     /* Implement offset_vec::push_back_reorder.  */
25262     void push_back_reorder (size_t elem) override
25263     {
25264       m_vec.push_back (elem);
25265       /* Check for overflow.  */
25266       gdb_assert (m_vec.back () == elem);
25267       store_unsigned_integer (reinterpret_cast<gdb_byte *> (&m_vec.back ()),
25268                               sizeof (m_vec.back ()), dwarf5_byte_order, elem);
25269     }
25270
25271     /* Implement offset_vec::bytes.  */
25272     size_t bytes () const override
25273     {
25274       return m_vec.size () * sizeof (m_vec[0]);
25275     }
25276
25277     /* Implement offset_vec::file_write.  */
25278     void file_write (FILE *file) const override
25279     {
25280       ::file_write (file, m_vec);
25281     }
25282
25283   private:
25284     std::vector<OffsetSize> m_vec;
25285   };
25286
25287   /* Base class to unify DWARF-32 and DWARF-64 .debug_names output
25288      respecting name table width.  */
25289   class dwarf
25290   {
25291   public:
25292     offset_vec &name_table_string_offs, &name_table_entry_offs;
25293
25294     dwarf (offset_vec &name_table_string_offs_,
25295            offset_vec &name_table_entry_offs_)
25296       : name_table_string_offs (name_table_string_offs_),
25297         name_table_entry_offs (name_table_entry_offs_)
25298     {
25299     }
25300   };
25301
25302   /* Template to unify DWARF-32 and DWARF-64 .debug_names output
25303      respecting name table width.  */
25304   template<typename OffsetSize>
25305   class dwarf_tmpl : public dwarf
25306   {
25307   public:
25308     explicit dwarf_tmpl (bfd_endian dwarf5_byte_order_)
25309       : dwarf (m_name_table_string_offs, m_name_table_entry_offs),
25310         m_name_table_string_offs (dwarf5_byte_order_),
25311         m_name_table_entry_offs (dwarf5_byte_order_)
25312     {}
25313
25314   private:
25315     offset_vec_tmpl<OffsetSize> m_name_table_string_offs;
25316     offset_vec_tmpl<OffsetSize> m_name_table_entry_offs;
25317   };
25318
25319   /* Try to reconstruct original DWARF tag for given partial_symbol.
25320      This function is not DWARF-5 compliant but it is sufficient for
25321      GDB as a DWARF-5 index consumer.  */
25322   static int psymbol_tag (const struct partial_symbol *psym)
25323   {
25324     domain_enum domain = PSYMBOL_DOMAIN (psym);
25325     enum address_class aclass = PSYMBOL_CLASS (psym);
25326
25327     switch (domain)
25328       {
25329       case VAR_DOMAIN:
25330         switch (aclass)
25331           {
25332           case LOC_BLOCK:
25333             return DW_TAG_subprogram;
25334           case LOC_TYPEDEF:
25335             return DW_TAG_typedef;
25336           case LOC_COMPUTED:
25337           case LOC_CONST_BYTES:
25338           case LOC_OPTIMIZED_OUT:
25339           case LOC_STATIC:
25340             return DW_TAG_variable;
25341           case LOC_CONST:
25342             /* Note: It's currently impossible to recognize psyms as enum values
25343                short of reading the type info.  For now punt.  */
25344             return DW_TAG_variable;
25345           default:
25346             /* There are other LOC_FOO values that one might want to classify
25347                as variables, but dwarf2read.c doesn't currently use them.  */
25348             return DW_TAG_variable;
25349           }
25350       case STRUCT_DOMAIN:
25351         return DW_TAG_structure_type;
25352       default:
25353         return 0;
25354       }
25355   }
25356
25357   /* Call insert for all partial symbols and mark them in PSYMS_SEEN.  */
25358   void write_psymbols (std::unordered_set<partial_symbol *> &psyms_seen,
25359                        struct partial_symbol **psymp, int count, int cu_index,
25360                        bool is_static)
25361   {
25362     for (; count-- > 0; ++psymp)
25363       {
25364         struct partial_symbol *psym = *psymp;
25365
25366         if (SYMBOL_LANGUAGE (psym) == language_ada)
25367           error (_("Ada is not currently supported by the index"));
25368
25369         /* Only add a given psymbol once.  */
25370         if (psyms_seen.insert (psym).second)
25371           insert (psym, cu_index, is_static);
25372       }
25373   }
25374
25375   /* Store value of each symbol.  */
25376   std::unordered_map<c_str_view, std::set<symbol_value>, c_str_view_hasher>
25377     m_name_to_value_set;
25378
25379   /* Tables of DWARF-5 .debug_names.  They are in object file byte
25380      order.  */
25381   std::vector<uint32_t> m_bucket_table;
25382   std::vector<uint32_t> m_hash_table;
25383
25384   const bfd_endian m_dwarf5_byte_order;
25385   dwarf_tmpl<uint32_t> m_dwarf32;
25386   dwarf_tmpl<uint64_t> m_dwarf64;
25387   dwarf &m_dwarf;
25388   offset_vec &m_name_table_string_offs, &m_name_table_entry_offs;
25389   debug_str_lookup m_debugstrlookup;
25390
25391   /* Map each used .debug_names abbreviation tag parameter to its
25392      index value.  */
25393   std::unordered_map<index_key, int, index_key_hasher> m_indexkey_to_idx;
25394
25395   /* Next unused .debug_names abbreviation tag for
25396      m_indexkey_to_idx.  */
25397   int m_idx_next = 1;
25398
25399   /* .debug_names abbreviation table.  */
25400   data_buf m_abbrev_table;
25401
25402   /* .debug_names entry pool.  */
25403   data_buf m_entry_pool;
25404 };
25405
25406 /* Return iff any of the needed offsets does not fit into 32-bit
25407    .debug_names section.  */
25408
25409 static bool
25410 check_dwarf64_offsets ()
25411 {
25412   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25413     {
25414       const dwarf2_per_cu_data &per_cu = *dwarf2_per_objfile->all_comp_units[i];
25415
25416       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
25417         return true;
25418     }
25419   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
25420     {
25421       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
25422       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
25423
25424       if (to_underlying (per_cu.sect_off) >= (static_cast<uint64_t> (1) << 32))
25425         return true;
25426     }
25427   return false;
25428 }
25429
25430 /* The psyms_seen set is potentially going to be largish (~40k
25431    elements when indexing a -g3 build of GDB itself).  Estimate the
25432    number of elements in order to avoid too many rehashes, which
25433    require rebuilding buckets and thus many trips to
25434    malloc/free.  */
25435
25436 static size_t
25437 psyms_seen_size ()
25438 {
25439   size_t psyms_count = 0;
25440   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25441     {
25442       struct dwarf2_per_cu_data *per_cu
25443         = dwarf2_per_objfile->all_comp_units[i];
25444       struct partial_symtab *psymtab = per_cu->v.psymtab;
25445
25446       if (psymtab != NULL && psymtab->user == NULL)
25447         recursively_count_psymbols (psymtab, psyms_count);
25448     }
25449   /* Generating an index for gdb itself shows a ratio of
25450      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
25451   return psyms_count / 4;
25452 }
25453
25454 /* Write new .gdb_index section for OBJFILE into OUT_FILE.
25455    Return how many bytes were expected to be written into OUT_FILE.  */
25456
25457 static size_t
25458 write_gdbindex (struct objfile *objfile, FILE *out_file)
25459 {
25460   mapped_symtab symtab;
25461   data_buf cu_list;
25462
25463   /* While we're scanning CU's create a table that maps a psymtab pointer
25464      (which is what addrmap records) to its index (which is what is recorded
25465      in the index file).  This will later be needed to write the address
25466      table.  */
25467   psym_index_map cu_index_htab;
25468   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
25469
25470   /* The CU list is already sorted, so we don't need to do additional
25471      work here.  Also, the debug_types entries do not appear in
25472      all_comp_units, but only in their own hash table.  */
25473
25474   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
25475   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25476     {
25477       struct dwarf2_per_cu_data *per_cu
25478         = dwarf2_per_objfile->all_comp_units[i];
25479       struct partial_symtab *psymtab = per_cu->v.psymtab;
25480
25481       /* CU of a shared file from 'dwz -m' may be unused by this main file.
25482          It may be referenced from a local scope but in such case it does not
25483          need to be present in .gdb_index.  */
25484       if (psymtab == NULL)
25485         continue;
25486
25487       if (psymtab->user == NULL)
25488         recursively_write_psymbols (objfile, psymtab, &symtab,
25489                                     psyms_seen, i);
25490
25491       const auto insertpair = cu_index_htab.emplace (psymtab, i);
25492       gdb_assert (insertpair.second);
25493
25494       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
25495                            to_underlying (per_cu->sect_off));
25496       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
25497     }
25498
25499   /* Dump the address map.  */
25500   data_buf addr_vec;
25501   write_address_map (objfile, addr_vec, cu_index_htab);
25502
25503   /* Write out the .debug_type entries, if any.  */
25504   data_buf types_cu_list;
25505   if (dwarf2_per_objfile->signatured_types)
25506     {
25507       signatured_type_index_data sig_data (types_cu_list,
25508                                            psyms_seen);
25509
25510       sig_data.objfile = objfile;
25511       sig_data.symtab = &symtab;
25512       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
25513       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
25514                               write_one_signatured_type, &sig_data);
25515     }
25516
25517   /* Now that we've processed all symbols we can shrink their cu_indices
25518      lists.  */
25519   uniquify_cu_indices (&symtab);
25520
25521   data_buf symtab_vec, constant_pool;
25522   write_hash_table (&symtab, symtab_vec, constant_pool);
25523
25524   data_buf contents;
25525   const offset_type size_of_contents = 6 * sizeof (offset_type);
25526   offset_type total_len = size_of_contents;
25527
25528   /* The version number.  */
25529   contents.append_data (MAYBE_SWAP (8));
25530
25531   /* The offset of the CU list from the start of the file.  */
25532   contents.append_data (MAYBE_SWAP (total_len));
25533   total_len += cu_list.size ();
25534
25535   /* The offset of the types CU list from the start of the file.  */
25536   contents.append_data (MAYBE_SWAP (total_len));
25537   total_len += types_cu_list.size ();
25538
25539   /* The offset of the address table from the start of the file.  */
25540   contents.append_data (MAYBE_SWAP (total_len));
25541   total_len += addr_vec.size ();
25542
25543   /* The offset of the symbol table from the start of the file.  */
25544   contents.append_data (MAYBE_SWAP (total_len));
25545   total_len += symtab_vec.size ();
25546
25547   /* The offset of the constant pool from the start of the file.  */
25548   contents.append_data (MAYBE_SWAP (total_len));
25549   total_len += constant_pool.size ();
25550
25551   gdb_assert (contents.size () == size_of_contents);
25552
25553   contents.file_write (out_file);
25554   cu_list.file_write (out_file);
25555   types_cu_list.file_write (out_file);
25556   addr_vec.file_write (out_file);
25557   symtab_vec.file_write (out_file);
25558   constant_pool.file_write (out_file);
25559
25560   return total_len;
25561 }
25562
25563 /* DWARF-5 augmentation string for GDB's DW_IDX_GNU_* extension.  */
25564 static const gdb_byte dwarf5_gdb_augmentation[] = { 'G', 'D', 'B', 0 };
25565
25566 /* Write a new .debug_names section for OBJFILE into OUT_FILE, write
25567    needed addition to .debug_str section to OUT_FILE_STR.  Return how
25568    many bytes were expected to be written into OUT_FILE.  */
25569
25570 static size_t
25571 write_debug_names (struct objfile *objfile, FILE *out_file, FILE *out_file_str)
25572 {
25573   const bool dwarf5_is_dwarf64 = check_dwarf64_offsets ();
25574   const int dwarf5_offset_size = dwarf5_is_dwarf64 ? 8 : 4;
25575   const enum bfd_endian dwarf5_byte_order
25576     = gdbarch_byte_order (get_objfile_arch (objfile));
25577
25578   /* The CU list is already sorted, so we don't need to do additional
25579      work here.  Also, the debug_types entries do not appear in
25580      all_comp_units, but only in their own hash table.  */
25581   data_buf cu_list;
25582   debug_names nametable (dwarf5_is_dwarf64, dwarf5_byte_order);
25583   std::unordered_set<partial_symbol *> psyms_seen (psyms_seen_size ());
25584   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
25585     {
25586       const dwarf2_per_cu_data *per_cu = dwarf2_per_objfile->all_comp_units[i];
25587       partial_symtab *psymtab = per_cu->v.psymtab;
25588
25589       /* CU of a shared file from 'dwz -m' may be unused by this main
25590          file.  It may be referenced from a local scope but in such
25591          case it does not need to be present in .debug_names.  */
25592       if (psymtab == NULL)
25593         continue;
25594
25595       if (psymtab->user == NULL)
25596         nametable.recursively_write_psymbols (objfile, psymtab, psyms_seen, i);
25597
25598       cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
25599                            to_underlying (per_cu->sect_off));
25600     }
25601   nametable.build ();
25602
25603   /* No addr_vec - DWARF-5 uses .debug_aranges generated by GCC.  */
25604
25605   data_buf types_cu_list;
25606   for (int i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
25607     {
25608       const signatured_type &sigtype = *dwarf2_per_objfile->all_type_units[i];
25609       const dwarf2_per_cu_data &per_cu = sigtype.per_cu;
25610
25611       types_cu_list.append_uint (dwarf5_offset_size, dwarf5_byte_order,
25612                                  to_underlying (per_cu.sect_off));
25613     }
25614
25615   const offset_type bytes_of_header
25616     = ((dwarf5_is_dwarf64 ? 12 : 4)
25617        + 2 + 2 + 7 * 4
25618        + sizeof (dwarf5_gdb_augmentation));
25619   size_t expected_bytes = 0;
25620   expected_bytes += bytes_of_header;
25621   expected_bytes += cu_list.size ();
25622   expected_bytes += types_cu_list.size ();
25623   expected_bytes += nametable.bytes ();
25624   data_buf header;
25625
25626   if (!dwarf5_is_dwarf64)
25627     {
25628       const uint64_t size64 = expected_bytes - 4;
25629       gdb_assert (size64 < 0xfffffff0);
25630       header.append_uint (4, dwarf5_byte_order, size64);
25631     }
25632   else
25633     {
25634       header.append_uint (4, dwarf5_byte_order, 0xffffffff);
25635       header.append_uint (8, dwarf5_byte_order, expected_bytes - 12);
25636     }
25637
25638   /* The version number.  */
25639   header.append_uint (2, dwarf5_byte_order, 5);
25640
25641   /* Padding.  */
25642   header.append_uint (2, dwarf5_byte_order, 0);
25643
25644   /* comp_unit_count - The number of CUs in the CU list.  */
25645   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_comp_units);
25646
25647   /* local_type_unit_count - The number of TUs in the local TU
25648      list.  */
25649   header.append_uint (4, dwarf5_byte_order, dwarf2_per_objfile->n_type_units);
25650
25651   /* foreign_type_unit_count - The number of TUs in the foreign TU
25652      list.  */
25653   header.append_uint (4, dwarf5_byte_order, 0);
25654
25655   /* bucket_count - The number of hash buckets in the hash lookup
25656      table.  */
25657   header.append_uint (4, dwarf5_byte_order, nametable.bucket_count ());
25658
25659   /* name_count - The number of unique names in the index.  */
25660   header.append_uint (4, dwarf5_byte_order, nametable.name_count ());
25661
25662   /* abbrev_table_size - The size in bytes of the abbreviations
25663      table.  */
25664   header.append_uint (4, dwarf5_byte_order, nametable.abbrev_table_bytes ());
25665
25666   /* augmentation_string_size - The size in bytes of the augmentation
25667      string.  This value is rounded up to a multiple of 4.  */
25668   static_assert (sizeof (dwarf5_gdb_augmentation) % 4 == 0, "");
25669   header.append_uint (4, dwarf5_byte_order, sizeof (dwarf5_gdb_augmentation));
25670   header.append_data (dwarf5_gdb_augmentation);
25671
25672   gdb_assert (header.size () == bytes_of_header);
25673
25674   header.file_write (out_file);
25675   cu_list.file_write (out_file);
25676   types_cu_list.file_write (out_file);
25677   nametable.file_write (out_file, out_file_str);
25678
25679   return expected_bytes;
25680 }
25681
25682 /* Assert that FILE's size is EXPECTED_SIZE.  Assumes file's seek
25683    position is at the end of the file.  */
25684
25685 static void
25686 assert_file_size (FILE *file, const char *filename, size_t expected_size)
25687 {
25688   const auto file_size = ftell (file);
25689   if (file_size == -1)
25690     error (_("Can't get `%s' size"), filename);
25691   gdb_assert (file_size == expected_size);
25692 }
25693
25694 /* An index variant.  */
25695 enum dw_index_kind
25696 {
25697   /* GDB's own .gdb_index format.   */
25698   GDB_INDEX,
25699
25700   /* DWARF5 .debug_names.  */
25701   DEBUG_NAMES,
25702 };
25703
25704 /* Create an index file for OBJFILE in the directory DIR.  */
25705
25706 static void
25707 write_psymtabs_to_index (struct objfile *objfile, const char *dir,
25708                          dw_index_kind index_kind)
25709 {
25710   if (dwarf2_per_objfile->using_index)
25711     error (_("Cannot use an index to create the index"));
25712
25713   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
25714     error (_("Cannot make an index when the file has multiple .debug_types sections"));
25715
25716   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
25717     return;
25718
25719   struct stat st;
25720   if (stat (objfile_name (objfile), &st) < 0)
25721     perror_with_name (objfile_name (objfile));
25722
25723   std::string filename (std::string (dir) + SLASH_STRING
25724                         + lbasename (objfile_name (objfile))
25725                         + (index_kind == dw_index_kind::DEBUG_NAMES
25726                            ? INDEX5_SUFFIX : INDEX4_SUFFIX));
25727
25728   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
25729   if (!out_file)
25730     error (_("Can't open `%s' for writing"), filename.c_str ());
25731
25732   /* Order matters here; we want FILE to be closed before FILENAME is
25733      unlinked, because on MS-Windows one cannot delete a file that is
25734      still open.  (Don't call anything here that might throw until
25735      file_closer is created.)  */
25736   gdb::unlinker unlink_file (filename.c_str ());
25737   gdb_file_up close_out_file (out_file);
25738
25739   if (index_kind == dw_index_kind::DEBUG_NAMES)
25740     {
25741       std::string filename_str (std::string (dir) + SLASH_STRING
25742                                 + lbasename (objfile_name (objfile))
25743                                 + DEBUG_STR_SUFFIX);
25744       FILE *out_file_str
25745         = gdb_fopen_cloexec (filename_str.c_str (), "wb").release ();
25746       if (!out_file_str)
25747         error (_("Can't open `%s' for writing"), filename_str.c_str ());
25748       gdb::unlinker unlink_file_str (filename_str.c_str ());
25749       gdb_file_up close_out_file_str (out_file_str);
25750
25751       const size_t total_len
25752         = write_debug_names (objfile, out_file, out_file_str);
25753       assert_file_size (out_file, filename.c_str (), total_len);
25754
25755       /* We want to keep the file .debug_str file too.  */
25756       unlink_file_str.keep ();
25757     }
25758   else
25759     {
25760       const size_t total_len
25761         = write_gdbindex (objfile, out_file);
25762       assert_file_size (out_file, filename.c_str (), total_len);
25763     }
25764
25765   /* We want to keep the file.  */
25766   unlink_file.keep ();
25767 }
25768
25769 /* Implementation of the `save gdb-index' command.
25770    
25771    Note that the .gdb_index file format used by this command is
25772    documented in the GDB manual.  Any changes here must be documented
25773    there.  */
25774
25775 static void
25776 save_gdb_index_command (const char *arg, int from_tty)
25777 {
25778   struct objfile *objfile;
25779   const char dwarf5space[] = "-dwarf-5 ";
25780   dw_index_kind index_kind = dw_index_kind::GDB_INDEX;
25781
25782   if (!arg)
25783     arg = "";
25784
25785   arg = skip_spaces (arg);
25786   if (strncmp (arg, dwarf5space, strlen (dwarf5space)) == 0)
25787     {
25788       index_kind = dw_index_kind::DEBUG_NAMES;
25789       arg += strlen (dwarf5space);
25790       arg = skip_spaces (arg);
25791     }
25792
25793   if (!*arg)
25794     error (_("usage: save gdb-index [-dwarf-5] DIRECTORY"));
25795
25796   ALL_OBJFILES (objfile)
25797   {
25798     struct stat st;
25799
25800     /* If the objfile does not correspond to an actual file, skip it.  */
25801     if (stat (objfile_name (objfile), &st) < 0)
25802       continue;
25803
25804     dwarf2_per_objfile
25805       = (struct dwarf2_per_objfile *) objfile_data (objfile,
25806                                                     dwarf2_objfile_data_key);
25807     if (dwarf2_per_objfile)
25808       {
25809
25810         TRY
25811           {
25812             write_psymtabs_to_index (objfile, arg, index_kind);
25813           }
25814         CATCH (except, RETURN_MASK_ERROR)
25815           {
25816             exception_fprintf (gdb_stderr, except,
25817                                _("Error while writing index for `%s': "),
25818                                objfile_name (objfile));
25819           }
25820         END_CATCH
25821       }
25822   }
25823 }
25824
25825 \f
25826
25827 int dwarf_always_disassemble;
25828
25829 static void
25830 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
25831                                struct cmd_list_element *c, const char *value)
25832 {
25833   fprintf_filtered (file,
25834                     _("Whether to always disassemble "
25835                       "DWARF expressions is %s.\n"),
25836                     value);
25837 }
25838
25839 static void
25840 show_check_physname (struct ui_file *file, int from_tty,
25841                      struct cmd_list_element *c, const char *value)
25842 {
25843   fprintf_filtered (file,
25844                     _("Whether to check \"physname\" is %s.\n"),
25845                     value);
25846 }
25847
25848 void
25849 _initialize_dwarf2_read (void)
25850 {
25851   struct cmd_list_element *c;
25852
25853   dwarf2_objfile_data_key
25854     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
25855
25856   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
25857 Set DWARF specific variables.\n\
25858 Configure DWARF variables such as the cache size"),
25859                   &set_dwarf_cmdlist, "maintenance set dwarf ",
25860                   0/*allow-unknown*/, &maintenance_set_cmdlist);
25861
25862   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
25863 Show DWARF specific variables\n\
25864 Show DWARF variables such as the cache size"),
25865                   &show_dwarf_cmdlist, "maintenance show dwarf ",
25866                   0/*allow-unknown*/, &maintenance_show_cmdlist);
25867
25868   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
25869                             &dwarf_max_cache_age, _("\
25870 Set the upper bound on the age of cached DWARF compilation units."), _("\
25871 Show the upper bound on the age of cached DWARF compilation units."), _("\
25872 A higher limit means that cached compilation units will be stored\n\
25873 in memory longer, and more total memory will be used.  Zero disables\n\
25874 caching, which can slow down startup."),
25875                             NULL,
25876                             show_dwarf_max_cache_age,
25877                             &set_dwarf_cmdlist,
25878                             &show_dwarf_cmdlist);
25879
25880   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
25881                            &dwarf_always_disassemble, _("\
25882 Set whether `info address' always disassembles DWARF expressions."), _("\
25883 Show whether `info address' always disassembles DWARF expressions."), _("\
25884 When enabled, DWARF expressions are always printed in an assembly-like\n\
25885 syntax.  When disabled, expressions will be printed in a more\n\
25886 conversational style, when possible."),
25887                            NULL,
25888                            show_dwarf_always_disassemble,
25889                            &set_dwarf_cmdlist,
25890                            &show_dwarf_cmdlist);
25891
25892   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
25893 Set debugging of the DWARF reader."), _("\
25894 Show debugging of the DWARF reader."), _("\
25895 When enabled (non-zero), debugging messages are printed during DWARF\n\
25896 reading and symtab expansion.  A value of 1 (one) provides basic\n\
25897 information.  A value greater than 1 provides more verbose information."),
25898                             NULL,
25899                             NULL,
25900                             &setdebuglist, &showdebuglist);
25901
25902   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
25903 Set debugging of the DWARF DIE reader."), _("\
25904 Show debugging of the DWARF DIE reader."), _("\
25905 When enabled (non-zero), DIEs are dumped after they are read in.\n\
25906 The value is the maximum depth to print."),
25907                              NULL,
25908                              NULL,
25909                              &setdebuglist, &showdebuglist);
25910
25911   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
25912 Set debugging of the dwarf line reader."), _("\
25913 Show debugging of the dwarf line reader."), _("\
25914 When enabled (non-zero), line number entries are dumped as they are read in.\n\
25915 A value of 1 (one) provides basic information.\n\
25916 A value greater than 1 provides more verbose information."),
25917                              NULL,
25918                              NULL,
25919                              &setdebuglist, &showdebuglist);
25920
25921   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
25922 Set cross-checking of \"physname\" code against demangler."), _("\
25923 Show cross-checking of \"physname\" code against demangler."), _("\
25924 When enabled, GDB's internal \"physname\" code is checked against\n\
25925 the demangler."),
25926                            NULL, show_check_physname,
25927                            &setdebuglist, &showdebuglist);
25928
25929   add_setshow_boolean_cmd ("use-deprecated-index-sections",
25930                            no_class, &use_deprecated_index_sections, _("\
25931 Set whether to use deprecated gdb_index sections."), _("\
25932 Show whether to use deprecated gdb_index sections."), _("\
25933 When enabled, deprecated .gdb_index sections are used anyway.\n\
25934 Normally they are ignored either because of a missing feature or\n\
25935 performance issue.\n\
25936 Warning: This option must be enabled before gdb reads the file."),
25937                            NULL,
25938                            NULL,
25939                            &setlist, &showlist);
25940
25941   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
25942                _("\
25943 Save a gdb-index file.\n\
25944 Usage: save gdb-index [-dwarf-5] DIRECTORY\n\
25945 \n\
25946 No options create one file with .gdb-index extension for pre-DWARF-5\n\
25947 compatible .gdb_index section.  With -dwarf-5 creates two files with\n\
25948 extension .debug_names and .debug_str for DWARF-5 .debug_names section."),
25949                &save_cmdlist);
25950   set_cmd_completer (c, filename_completer);
25951
25952   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
25953                                                         &dwarf2_locexpr_funcs);
25954   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
25955                                                         &dwarf2_loclist_funcs);
25956
25957   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
25958                                         &dwarf2_block_frame_base_locexpr_funcs);
25959   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
25960                                         &dwarf2_block_frame_base_loclist_funcs);
25961
25962 #if GDB_SELF_TEST
25963   selftests::register_test ("dw2_expand_symtabs_matching",
25964                             selftests::dw2_expand_symtabs_matching::run_test);
25965 #endif
25966 }