Reorder/reindent dw2_expand_symtabs_matching & friends
[external/binutils.git] / gdb / dwarf2read.c
1 /* DWARF 2 debugging format support for GDB.
2
3    Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5    Adapted by Gary Funck (gary@intrepid.com), Intrepid Technology,
6    Inc.  with support from Florida State University (under contract
7    with the Ada Joint Program Office), and Silicon Graphics, Inc.
8    Initial contribution by Brent Benson, Harris Computer Systems, Inc.,
9    based on Fred Fish's (Cygnus Support) implementation of DWARF 1
10    support.
11
12    This file is part of GDB.
13
14    This program is free software; you can redistribute it and/or modify
15    it under the terms of the GNU General Public License as published by
16    the Free Software Foundation; either version 3 of the License, or
17    (at your option) any later version.
18
19    This program is distributed in the hope that it will be useful,
20    but WITHOUT ANY WARRANTY; without even the implied warranty of
21    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22    GNU General Public License for more details.
23
24    You should have received a copy of the GNU General Public License
25    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
26
27 /* FIXME: Various die-reading functions need to be more careful with
28    reading off the end of the section.
29    E.g., load_partial_dies, read_partial_die.  */
30
31 #include "defs.h"
32 #include "bfd.h"
33 #include "elf-bfd.h"
34 #include "symtab.h"
35 #include "gdbtypes.h"
36 #include "objfiles.h"
37 #include "dwarf2.h"
38 #include "buildsym.h"
39 #include "demangle.h"
40 #include "gdb-demangle.h"
41 #include "expression.h"
42 #include "filenames.h"  /* for DOSish file names */
43 #include "macrotab.h"
44 #include "language.h"
45 #include "complaints.h"
46 #include "bcache.h"
47 #include "dwarf2expr.h"
48 #include "dwarf2loc.h"
49 #include "cp-support.h"
50 #include "hashtab.h"
51 #include "command.h"
52 #include "gdbcmd.h"
53 #include "block.h"
54 #include "addrmap.h"
55 #include "typeprint.h"
56 #include "psympriv.h"
57 #include <sys/stat.h>
58 #include "completer.h"
59 #include "vec.h"
60 #include "c-lang.h"
61 #include "go-lang.h"
62 #include "valprint.h"
63 #include "gdbcore.h" /* for gnutarget */
64 #include "gdb/gdb-index.h"
65 #include <ctype.h>
66 #include "gdb_bfd.h"
67 #include "f-lang.h"
68 #include "source.h"
69 #include "filestuff.h"
70 #include "build-id.h"
71 #include "namespace.h"
72 #include "common/gdb_unlinker.h"
73 #include "common/function-view.h"
74 #include "common/gdb_optional.h"
75 #include "common/underlying.h"
76 #include "common/byte-vector.h"
77 #include "filename-seen-cache.h"
78 #include "producer.h"
79 #include <fcntl.h>
80 #include <sys/types.h>
81 #include <algorithm>
82 #include <unordered_set>
83 #include <unordered_map>
84
85 typedef struct symbol *symbolp;
86 DEF_VEC_P (symbolp);
87
88 /* When == 1, print basic high level tracing messages.
89    When > 1, be more verbose.
90    This is in contrast to the low level DIE reading of dwarf_die_debug.  */
91 static unsigned int dwarf_read_debug = 0;
92
93 /* When non-zero, dump DIEs after they are read in.  */
94 static unsigned int dwarf_die_debug = 0;
95
96 /* When non-zero, dump line number entries as they are read in.  */
97 static unsigned int dwarf_line_debug = 0;
98
99 /* When non-zero, cross-check physname against demangler.  */
100 static int check_physname = 0;
101
102 /* When non-zero, do not reject deprecated .gdb_index sections.  */
103 static int use_deprecated_index_sections = 0;
104
105 static const struct objfile_data *dwarf2_objfile_data_key;
106
107 /* The "aclass" indices for various kinds of computed DWARF symbols.  */
108
109 static int dwarf2_locexpr_index;
110 static int dwarf2_loclist_index;
111 static int dwarf2_locexpr_block_index;
112 static int dwarf2_loclist_block_index;
113
114 /* A descriptor for dwarf sections.
115
116    S.ASECTION, SIZE are typically initialized when the objfile is first
117    scanned.  BUFFER, READIN are filled in later when the section is read.
118    If the section contained compressed data then SIZE is updated to record
119    the uncompressed size of the section.
120
121    DWP file format V2 introduces a wrinkle that is easiest to handle by
122    creating the concept of virtual sections contained within a real section.
123    In DWP V2 the sections of the input DWO files are concatenated together
124    into one section, but section offsets are kept relative to the original
125    input section.
126    If this is a virtual dwp-v2 section, S.CONTAINING_SECTION is a backlink to
127    the real section this "virtual" section is contained in, and BUFFER,SIZE
128    describe the virtual section.  */
129
130 struct dwarf2_section_info
131 {
132   union
133   {
134     /* If this is a real section, the bfd section.  */
135     asection *section;
136     /* If this is a virtual section, pointer to the containing ("real")
137        section.  */
138     struct dwarf2_section_info *containing_section;
139   } s;
140   /* Pointer to section data, only valid if readin.  */
141   const gdb_byte *buffer;
142   /* The size of the section, real or virtual.  */
143   bfd_size_type size;
144   /* If this is a virtual section, the offset in the real section.
145      Only valid if is_virtual.  */
146   bfd_size_type virtual_offset;
147   /* True if we have tried to read this section.  */
148   char readin;
149   /* True if this is a virtual section, False otherwise.
150      This specifies which of s.section and s.containing_section to use.  */
151   char is_virtual;
152 };
153
154 typedef struct dwarf2_section_info dwarf2_section_info_def;
155 DEF_VEC_O (dwarf2_section_info_def);
156
157 /* All offsets in the index are of this type.  It must be
158    architecture-independent.  */
159 typedef uint32_t offset_type;
160
161 DEF_VEC_I (offset_type);
162
163 /* Ensure only legit values are used.  */
164 #define DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE(cu_index, value) \
165   do { \
166     gdb_assert ((unsigned int) (value) <= 1); \
167     GDB_INDEX_SYMBOL_STATIC_SET_VALUE((cu_index), (value)); \
168   } while (0)
169
170 /* Ensure only legit values are used.  */
171 #define DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE(cu_index, value) \
172   do { \
173     gdb_assert ((value) >= GDB_INDEX_SYMBOL_KIND_TYPE \
174                 && (value) <= GDB_INDEX_SYMBOL_KIND_OTHER); \
175     GDB_INDEX_SYMBOL_KIND_SET_VALUE((cu_index), (value)); \
176   } while (0)
177
178 /* Ensure we don't use more than the alloted nuber of bits for the CU.  */
179 #define DW2_GDB_INDEX_CU_SET_VALUE(cu_index, value) \
180   do { \
181     gdb_assert (((value) & ~GDB_INDEX_CU_MASK) == 0); \
182     GDB_INDEX_CU_SET_VALUE((cu_index), (value)); \
183   } while (0)
184
185 #if WORDS_BIGENDIAN
186
187 /* Convert VALUE between big- and little-endian.  */
188
189 static offset_type
190 byte_swap (offset_type value)
191 {
192   offset_type result;
193
194   result = (value & 0xff) << 24;
195   result |= (value & 0xff00) << 8;
196   result |= (value & 0xff0000) >> 8;
197   result |= (value & 0xff000000) >> 24;
198   return result;
199 }
200
201 #define MAYBE_SWAP(V)  byte_swap (V)
202
203 #else
204 #define MAYBE_SWAP(V) static_cast<offset_type> (V)
205 #endif /* WORDS_BIGENDIAN */
206
207 /* An index into a (C++) symbol name component in a symbol name as
208    recorded in the mapped_index's symbol table.  For each C++ symbol
209    in the symbol table, we record one entry for the start of each
210    component in the symbol in a table of name components, and then
211    sort the table, in order to be able to binary search symbol names,
212    ignoring leading namespaces, both completion and regular look up.
213    For example, for symbol "A::B::C", we'll have an entry that points
214    to "A::B::C", another that points to "B::C", and another for "C".
215    Note that function symbols in GDB index have no parameter
216    information, just the function/method names.  You can convert a
217    name_component to a "const char *" using the
218    'mapped_index::symbol_name_at(offset_type)' method.  */
219
220 struct name_component
221 {
222   /* Offset in the symbol name where the component starts.  Stored as
223      a (32-bit) offset instead of a pointer to save memory and improve
224      locality on 64-bit architectures.  */
225   offset_type name_offset;
226
227   /* The symbol's index in the symbol and constant pool tables of a
228      mapped_index.  */
229   offset_type idx;
230 };
231
232 /* A description of the mapped index.  The file format is described in
233    a comment by the code that writes the index.  */
234 struct mapped_index
235 {
236   /* Index data format version.  */
237   int version;
238
239   /* The total length of the buffer.  */
240   off_t total_size;
241
242   /* A pointer to the address table data.  */
243   const gdb_byte *address_table;
244
245   /* Size of the address table data in bytes.  */
246   offset_type address_table_size;
247
248   /* The symbol table, implemented as a hash table.  */
249   const offset_type *symbol_table;
250
251   /* Size in slots, each slot is 2 offset_types.  */
252   offset_type symbol_table_slots;
253
254   /* A pointer to the constant pool.  */
255   const char *constant_pool;
256
257   /* The name_component table (a sorted vector).  See name_component's
258      description above.  */
259   std::vector<name_component> name_components;
260
261   /* Convenience method to get at the name of the symbol at IDX in the
262      symbol table.  */
263   const char *symbol_name_at (offset_type idx) const
264   { return this->constant_pool + MAYBE_SWAP (this->symbol_table[idx]); }
265 };
266
267 typedef struct dwarf2_per_cu_data *dwarf2_per_cu_ptr;
268 DEF_VEC_P (dwarf2_per_cu_ptr);
269
270 struct tu_stats
271 {
272   int nr_uniq_abbrev_tables;
273   int nr_symtabs;
274   int nr_symtab_sharers;
275   int nr_stmt_less_type_units;
276   int nr_all_type_units_reallocs;
277 };
278
279 /* Collection of data recorded per objfile.
280    This hangs off of dwarf2_objfile_data_key.  */
281
282 struct dwarf2_per_objfile
283 {
284   /* Construct a dwarf2_per_objfile for OBJFILE.  NAMES points to the
285      dwarf2 section names, or is NULL if the standard ELF names are
286      used.  */
287   dwarf2_per_objfile (struct objfile *objfile,
288                       const dwarf2_debug_sections *names);
289
290   ~dwarf2_per_objfile ();
291
292   DISABLE_COPY_AND_ASSIGN (dwarf2_per_objfile);
293
294   /* Free all cached compilation units.  */
295   void free_cached_comp_units ();
296 private:
297   /* This function is mapped across the sections and remembers the
298      offset and size of each of the debugging sections we are
299      interested in.  */
300   void locate_sections (bfd *abfd, asection *sectp,
301                         const dwarf2_debug_sections &names);
302
303 public:
304   dwarf2_section_info info {};
305   dwarf2_section_info abbrev {};
306   dwarf2_section_info line {};
307   dwarf2_section_info loc {};
308   dwarf2_section_info loclists {};
309   dwarf2_section_info macinfo {};
310   dwarf2_section_info macro {};
311   dwarf2_section_info str {};
312   dwarf2_section_info line_str {};
313   dwarf2_section_info ranges {};
314   dwarf2_section_info rnglists {};
315   dwarf2_section_info addr {};
316   dwarf2_section_info frame {};
317   dwarf2_section_info eh_frame {};
318   dwarf2_section_info gdb_index {};
319
320   VEC (dwarf2_section_info_def) *types = NULL;
321
322   /* Back link.  */
323   struct objfile *objfile = NULL;
324
325   /* Table of all the compilation units.  This is used to locate
326      the target compilation unit of a particular reference.  */
327   struct dwarf2_per_cu_data **all_comp_units = NULL;
328
329   /* The number of compilation units in ALL_COMP_UNITS.  */
330   int n_comp_units = 0;
331
332   /* The number of .debug_types-related CUs.  */
333   int n_type_units = 0;
334
335   /* The number of elements allocated in all_type_units.
336      If there are skeleton-less TUs, we add them to all_type_units lazily.  */
337   int n_allocated_type_units = 0;
338
339   /* The .debug_types-related CUs (TUs).
340      This is stored in malloc space because we may realloc it.  */
341   struct signatured_type **all_type_units = NULL;
342
343   /* Table of struct type_unit_group objects.
344      The hash key is the DW_AT_stmt_list value.  */
345   htab_t type_unit_groups {};
346
347   /* A table mapping .debug_types signatures to its signatured_type entry.
348      This is NULL if the .debug_types section hasn't been read in yet.  */
349   htab_t signatured_types {};
350
351   /* Type unit statistics, to see how well the scaling improvements
352      are doing.  */
353   struct tu_stats tu_stats {};
354
355   /* A chain of compilation units that are currently read in, so that
356      they can be freed later.  */
357   dwarf2_per_cu_data *read_in_chain = NULL;
358
359   /* A table mapping DW_AT_dwo_name values to struct dwo_file objects.
360      This is NULL if the table hasn't been allocated yet.  */
361   htab_t dwo_files {};
362
363   /* True if we've checked for whether there is a DWP file.  */
364   bool dwp_checked = false;
365
366   /* The DWP file if there is one, or NULL.  */
367   struct dwp_file *dwp_file = NULL;
368
369   /* The shared '.dwz' file, if one exists.  This is used when the
370      original data was compressed using 'dwz -m'.  */
371   struct dwz_file *dwz_file = NULL;
372
373   /* A flag indicating whether this objfile has a section loaded at a
374      VMA of 0.  */
375   bool has_section_at_zero = false;
376
377   /* True if we are using the mapped index,
378      or we are faking it for OBJF_READNOW's sake.  */
379   bool using_index = false;
380
381   /* The mapped index, or NULL if .gdb_index is missing or not being used.  */
382   mapped_index *index_table = NULL;
383
384   /* When using index_table, this keeps track of all quick_file_names entries.
385      TUs typically share line table entries with a CU, so we maintain a
386      separate table of all line table entries to support the sharing.
387      Note that while there can be way more TUs than CUs, we've already
388      sorted all the TUs into "type unit groups", grouped by their
389      DW_AT_stmt_list value.  Therefore the only sharing done here is with a
390      CU and its associated TU group if there is one.  */
391   htab_t quick_file_names_table {};
392
393   /* Set during partial symbol reading, to prevent queueing of full
394      symbols.  */
395   bool reading_partial_symbols = false;
396
397   /* Table mapping type DIEs to their struct type *.
398      This is NULL if not allocated yet.
399      The mapping is done via (CU/TU + DIE offset) -> type.  */
400   htab_t die_type_hash {};
401
402   /* The CUs we recently read.  */
403   VEC (dwarf2_per_cu_ptr) *just_read_cus = NULL;
404
405   /* Table containing line_header indexed by offset and offset_in_dwz.  */
406   htab_t line_header_hash {};
407
408   /* Table containing all filenames.  This is an optional because the
409      table is lazily constructed on first access.  */
410   gdb::optional<filename_seen_cache> filenames_cache;
411 };
412
413 static struct dwarf2_per_objfile *dwarf2_per_objfile;
414
415 /* Default names of the debugging sections.  */
416
417 /* Note that if the debugging section has been compressed, it might
418    have a name like .zdebug_info.  */
419
420 static const struct dwarf2_debug_sections dwarf2_elf_names =
421 {
422   { ".debug_info", ".zdebug_info" },
423   { ".debug_abbrev", ".zdebug_abbrev" },
424   { ".debug_line", ".zdebug_line" },
425   { ".debug_loc", ".zdebug_loc" },
426   { ".debug_loclists", ".zdebug_loclists" },
427   { ".debug_macinfo", ".zdebug_macinfo" },
428   { ".debug_macro", ".zdebug_macro" },
429   { ".debug_str", ".zdebug_str" },
430   { ".debug_line_str", ".zdebug_line_str" },
431   { ".debug_ranges", ".zdebug_ranges" },
432   { ".debug_rnglists", ".zdebug_rnglists" },
433   { ".debug_types", ".zdebug_types" },
434   { ".debug_addr", ".zdebug_addr" },
435   { ".debug_frame", ".zdebug_frame" },
436   { ".eh_frame", NULL },
437   { ".gdb_index", ".zgdb_index" },
438   23
439 };
440
441 /* List of DWO/DWP sections.  */
442
443 static const struct dwop_section_names
444 {
445   struct dwarf2_section_names abbrev_dwo;
446   struct dwarf2_section_names info_dwo;
447   struct dwarf2_section_names line_dwo;
448   struct dwarf2_section_names loc_dwo;
449   struct dwarf2_section_names loclists_dwo;
450   struct dwarf2_section_names macinfo_dwo;
451   struct dwarf2_section_names macro_dwo;
452   struct dwarf2_section_names str_dwo;
453   struct dwarf2_section_names str_offsets_dwo;
454   struct dwarf2_section_names types_dwo;
455   struct dwarf2_section_names cu_index;
456   struct dwarf2_section_names tu_index;
457 }
458 dwop_section_names =
459 {
460   { ".debug_abbrev.dwo", ".zdebug_abbrev.dwo" },
461   { ".debug_info.dwo", ".zdebug_info.dwo" },
462   { ".debug_line.dwo", ".zdebug_line.dwo" },
463   { ".debug_loc.dwo", ".zdebug_loc.dwo" },
464   { ".debug_loclists.dwo", ".zdebug_loclists.dwo" },
465   { ".debug_macinfo.dwo", ".zdebug_macinfo.dwo" },
466   { ".debug_macro.dwo", ".zdebug_macro.dwo" },
467   { ".debug_str.dwo", ".zdebug_str.dwo" },
468   { ".debug_str_offsets.dwo", ".zdebug_str_offsets.dwo" },
469   { ".debug_types.dwo", ".zdebug_types.dwo" },
470   { ".debug_cu_index", ".zdebug_cu_index" },
471   { ".debug_tu_index", ".zdebug_tu_index" },
472 };
473
474 /* local data types */
475
476 /* The data in a compilation unit header, after target2host
477    translation, looks like this.  */
478 struct comp_unit_head
479 {
480   unsigned int length;
481   short version;
482   unsigned char addr_size;
483   unsigned char signed_addr_p;
484   sect_offset abbrev_sect_off;
485
486   /* Size of file offsets; either 4 or 8.  */
487   unsigned int offset_size;
488
489   /* Size of the length field; either 4 or 12.  */
490   unsigned int initial_length_size;
491
492   enum dwarf_unit_type unit_type;
493
494   /* Offset to the first byte of this compilation unit header in the
495      .debug_info section, for resolving relative reference dies.  */
496   sect_offset sect_off;
497
498   /* Offset to first die in this cu from the start of the cu.
499      This will be the first byte following the compilation unit header.  */
500   cu_offset first_die_cu_offset;
501
502   /* 64-bit signature of this type unit - it is valid only for
503      UNIT_TYPE DW_UT_type.  */
504   ULONGEST signature;
505
506   /* For types, offset in the type's DIE of the type defined by this TU.  */
507   cu_offset type_cu_offset_in_tu;
508 };
509
510 /* Type used for delaying computation of method physnames.
511    See comments for compute_delayed_physnames.  */
512 struct delayed_method_info
513 {
514   /* The type to which the method is attached, i.e., its parent class.  */
515   struct type *type;
516
517   /* The index of the method in the type's function fieldlists.  */
518   int fnfield_index;
519
520   /* The index of the method in the fieldlist.  */
521   int index;
522
523   /* The name of the DIE.  */
524   const char *name;
525
526   /*  The DIE associated with this method.  */
527   struct die_info *die;
528 };
529
530 typedef struct delayed_method_info delayed_method_info;
531 DEF_VEC_O (delayed_method_info);
532
533 /* Internal state when decoding a particular compilation unit.  */
534 struct dwarf2_cu
535 {
536   /* The objfile containing this compilation unit.  */
537   struct objfile *objfile;
538
539   /* The header of the compilation unit.  */
540   struct comp_unit_head header;
541
542   /* Base address of this compilation unit.  */
543   CORE_ADDR base_address;
544
545   /* Non-zero if base_address has been set.  */
546   int base_known;
547
548   /* The language we are debugging.  */
549   enum language language;
550   const struct language_defn *language_defn;
551
552   const char *producer;
553
554   /* The generic symbol table building routines have separate lists for
555      file scope symbols and all all other scopes (local scopes).  So
556      we need to select the right one to pass to add_symbol_to_list().
557      We do it by keeping a pointer to the correct list in list_in_scope.
558
559      FIXME: The original dwarf code just treated the file scope as the
560      first local scope, and all other local scopes as nested local
561      scopes, and worked fine.  Check to see if we really need to
562      distinguish these in buildsym.c.  */
563   struct pending **list_in_scope;
564
565   /* The abbrev table for this CU.
566      Normally this points to the abbrev table in the objfile.
567      But if DWO_UNIT is non-NULL this is the abbrev table in the DWO file.  */
568   struct abbrev_table *abbrev_table;
569
570   /* Hash table holding all the loaded partial DIEs
571      with partial_die->offset.SECT_OFF as hash.  */
572   htab_t partial_dies;
573
574   /* Storage for things with the same lifetime as this read-in compilation
575      unit, including partial DIEs.  */
576   struct obstack comp_unit_obstack;
577
578   /* When multiple dwarf2_cu structures are living in memory, this field
579      chains them all together, so that they can be released efficiently.
580      We will probably also want a generation counter so that most-recently-used
581      compilation units are cached...  */
582   struct dwarf2_per_cu_data *read_in_chain;
583
584   /* Backlink to our per_cu entry.  */
585   struct dwarf2_per_cu_data *per_cu;
586
587   /* How many compilation units ago was this CU last referenced?  */
588   int last_used;
589
590   /* A hash table of DIE cu_offset for following references with
591      die_info->offset.sect_off as hash.  */
592   htab_t die_hash;
593
594   /* Full DIEs if read in.  */
595   struct die_info *dies;
596
597   /* A set of pointers to dwarf2_per_cu_data objects for compilation
598      units referenced by this one.  Only set during full symbol processing;
599      partial symbol tables do not have dependencies.  */
600   htab_t dependencies;
601
602   /* Header data from the line table, during full symbol processing.  */
603   struct line_header *line_header;
604   /* Non-NULL if LINE_HEADER is owned by this DWARF_CU.  Otherwise,
605      it's owned by dwarf2_per_objfile::line_header_hash.  If non-NULL,
606      this is the DW_TAG_compile_unit die for this CU.  We'll hold on
607      to the line header as long as this DIE is being processed.  See
608      process_die_scope.  */
609   die_info *line_header_die_owner;
610
611   /* A list of methods which need to have physnames computed
612      after all type information has been read.  */
613   VEC (delayed_method_info) *method_list;
614
615   /* To be copied to symtab->call_site_htab.  */
616   htab_t call_site_htab;
617
618   /* Non-NULL if this CU came from a DWO file.
619      There is an invariant here that is important to remember:
620      Except for attributes copied from the top level DIE in the "main"
621      (or "stub") file in preparation for reading the DWO file
622      (e.g., DW_AT_GNU_addr_base), we KISS: there is only *one* CU.
623      Either there isn't a DWO file (in which case this is NULL and the point
624      is moot), or there is and either we're not going to read it (in which
625      case this is NULL) or there is and we are reading it (in which case this
626      is non-NULL).  */
627   struct dwo_unit *dwo_unit;
628
629   /* The DW_AT_addr_base attribute if present, zero otherwise
630      (zero is a valid value though).
631      Note this value comes from the Fission stub CU/TU's DIE.  */
632   ULONGEST addr_base;
633
634   /* The DW_AT_ranges_base attribute if present, zero otherwise
635      (zero is a valid value though).
636      Note this value comes from the Fission stub CU/TU's DIE.
637      Also note that the value is zero in the non-DWO case so this value can
638      be used without needing to know whether DWO files are in use or not.
639      N.B. This does not apply to DW_AT_ranges appearing in
640      DW_TAG_compile_unit dies.  This is a bit of a wart, consider if ever
641      DW_AT_ranges appeared in the DW_TAG_compile_unit of DWO DIEs: then
642      DW_AT_ranges_base *would* have to be applied, and we'd have to care
643      whether the DW_AT_ranges attribute came from the skeleton or DWO.  */
644   ULONGEST ranges_base;
645
646   /* Mark used when releasing cached dies.  */
647   unsigned int mark : 1;
648
649   /* This CU references .debug_loc.  See the symtab->locations_valid field.
650      This test is imperfect as there may exist optimized debug code not using
651      any location list and still facing inlining issues if handled as
652      unoptimized code.  For a future better test see GCC PR other/32998.  */
653   unsigned int has_loclist : 1;
654
655   /* These cache the results for producer_is_* fields.  CHECKED_PRODUCER is set
656      if all the producer_is_* fields are valid.  This information is cached
657      because profiling CU expansion showed excessive time spent in
658      producer_is_gxx_lt_4_6.  */
659   unsigned int checked_producer : 1;
660   unsigned int producer_is_gxx_lt_4_6 : 1;
661   unsigned int producer_is_gcc_lt_4_3 : 1;
662   unsigned int producer_is_icc_lt_14 : 1;
663
664   /* When set, the file that we're processing is known to have
665      debugging info for C++ namespaces.  GCC 3.3.x did not produce
666      this information, but later versions do.  */
667
668   unsigned int processing_has_namespace_info : 1;
669 };
670
671 /* Persistent data held for a compilation unit, even when not
672    processing it.  We put a pointer to this structure in the
673    read_symtab_private field of the psymtab.  */
674
675 struct dwarf2_per_cu_data
676 {
677   /* The start offset and length of this compilation unit.
678      NOTE: Unlike comp_unit_head.length, this length includes
679      initial_length_size.
680      If the DIE refers to a DWO file, this is always of the original die,
681      not the DWO file.  */
682   sect_offset sect_off;
683   unsigned int length;
684
685   /* DWARF standard version this data has been read from (such as 4 or 5).  */
686   short dwarf_version;
687
688   /* Flag indicating this compilation unit will be read in before
689      any of the current compilation units are processed.  */
690   unsigned int queued : 1;
691
692   /* This flag will be set when reading partial DIEs if we need to load
693      absolutely all DIEs for this compilation unit, instead of just the ones
694      we think are interesting.  It gets set if we look for a DIE in the
695      hash table and don't find it.  */
696   unsigned int load_all_dies : 1;
697
698   /* Non-zero if this CU is from .debug_types.
699      Struct dwarf2_per_cu_data is contained in struct signatured_type iff
700      this is non-zero.  */
701   unsigned int is_debug_types : 1;
702
703   /* Non-zero if this CU is from the .dwz file.  */
704   unsigned int is_dwz : 1;
705
706   /* Non-zero if reading a TU directly from a DWO file, bypassing the stub.
707      This flag is only valid if is_debug_types is true.
708      We can't read a CU directly from a DWO file: There are required
709      attributes in the stub.  */
710   unsigned int reading_dwo_directly : 1;
711
712   /* Non-zero if the TU has been read.
713      This is used to assist the "Stay in DWO Optimization" for Fission:
714      When reading a DWO, it's faster to read TUs from the DWO instead of
715      fetching them from random other DWOs (due to comdat folding).
716      If the TU has already been read, the optimization is unnecessary
717      (and unwise - we don't want to change where gdb thinks the TU lives
718      "midflight").
719      This flag is only valid if is_debug_types is true.  */
720   unsigned int tu_read : 1;
721
722   /* The section this CU/TU lives in.
723      If the DIE refers to a DWO file, this is always the original die,
724      not the DWO file.  */
725   struct dwarf2_section_info *section;
726
727   /* Set to non-NULL iff this CU is currently loaded.  When it gets freed out
728      of the CU cache it gets reset to NULL again.  This is left as NULL for
729      dummy CUs (a CU header, but nothing else).  */
730   struct dwarf2_cu *cu;
731
732   /* The corresponding objfile.
733      Normally we can get the objfile from dwarf2_per_objfile.
734      However we can enter this file with just a "per_cu" handle.  */
735   struct objfile *objfile;
736
737   /* When dwarf2_per_objfile->using_index is true, the 'quick' field
738      is active.  Otherwise, the 'psymtab' field is active.  */
739   union
740   {
741     /* The partial symbol table associated with this compilation unit,
742        or NULL for unread partial units.  */
743     struct partial_symtab *psymtab;
744
745     /* Data needed by the "quick" functions.  */
746     struct dwarf2_per_cu_quick_data *quick;
747   } v;
748
749   /* The CUs we import using DW_TAG_imported_unit.  This is filled in
750      while reading psymtabs, used to compute the psymtab dependencies,
751      and then cleared.  Then it is filled in again while reading full
752      symbols, and only deleted when the objfile is destroyed.
753
754      This is also used to work around a difference between the way gold
755      generates .gdb_index version <=7 and the way gdb does.  Arguably this
756      is a gold bug.  For symbols coming from TUs, gold records in the index
757      the CU that includes the TU instead of the TU itself.  This breaks
758      dw2_lookup_symbol: It assumes that if the index says symbol X lives
759      in CU/TU Y, then one need only expand Y and a subsequent lookup in Y
760      will find X.  Alas TUs live in their own symtab, so after expanding CU Y
761      we need to look in TU Z to find X.  Fortunately, this is akin to
762      DW_TAG_imported_unit, so we just use the same mechanism: For
763      .gdb_index version <=7 this also records the TUs that the CU referred
764      to.  Concurrently with this change gdb was modified to emit version 8
765      indices so we only pay a price for gold generated indices.
766      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
767   VEC (dwarf2_per_cu_ptr) *imported_symtabs;
768 };
769
770 /* Entry in the signatured_types hash table.  */
771
772 struct signatured_type
773 {
774   /* The "per_cu" object of this type.
775      This struct is used iff per_cu.is_debug_types.
776      N.B.: This is the first member so that it's easy to convert pointers
777      between them.  */
778   struct dwarf2_per_cu_data per_cu;
779
780   /* The type's signature.  */
781   ULONGEST signature;
782
783   /* Offset in the TU of the type's DIE, as read from the TU header.
784      If this TU is a DWO stub and the definition lives in a DWO file
785      (specified by DW_AT_GNU_dwo_name), this value is unusable.  */
786   cu_offset type_offset_in_tu;
787
788   /* Offset in the section of the type's DIE.
789      If the definition lives in a DWO file, this is the offset in the
790      .debug_types.dwo section.
791      The value is zero until the actual value is known.
792      Zero is otherwise not a valid section offset.  */
793   sect_offset type_offset_in_section;
794
795   /* Type units are grouped by their DW_AT_stmt_list entry so that they
796      can share them.  This points to the containing symtab.  */
797   struct type_unit_group *type_unit_group;
798
799   /* The type.
800      The first time we encounter this type we fully read it in and install it
801      in the symbol tables.  Subsequent times we only need the type.  */
802   struct type *type;
803
804   /* Containing DWO unit.
805      This field is valid iff per_cu.reading_dwo_directly.  */
806   struct dwo_unit *dwo_unit;
807 };
808
809 typedef struct signatured_type *sig_type_ptr;
810 DEF_VEC_P (sig_type_ptr);
811
812 /* A struct that can be used as a hash key for tables based on DW_AT_stmt_list.
813    This includes type_unit_group and quick_file_names.  */
814
815 struct stmt_list_hash
816 {
817   /* The DWO unit this table is from or NULL if there is none.  */
818   struct dwo_unit *dwo_unit;
819
820   /* Offset in .debug_line or .debug_line.dwo.  */
821   sect_offset line_sect_off;
822 };
823
824 /* Each element of dwarf2_per_objfile->type_unit_groups is a pointer to
825    an object of this type.  */
826
827 struct type_unit_group
828 {
829   /* dwarf2read.c's main "handle" on a TU symtab.
830      To simplify things we create an artificial CU that "includes" all the
831      type units using this stmt_list so that the rest of the code still has
832      a "per_cu" handle on the symtab.
833      This PER_CU is recognized by having no section.  */
834 #define IS_TYPE_UNIT_GROUP(per_cu) ((per_cu)->section == NULL)
835   struct dwarf2_per_cu_data per_cu;
836
837   /* The TUs that share this DW_AT_stmt_list entry.
838      This is added to while parsing type units to build partial symtabs,
839      and is deleted afterwards and not used again.  */
840   VEC (sig_type_ptr) *tus;
841
842   /* The compunit symtab.
843      Type units in a group needn't all be defined in the same source file,
844      so we create an essentially anonymous symtab as the compunit symtab.  */
845   struct compunit_symtab *compunit_symtab;
846
847   /* The data used to construct the hash key.  */
848   struct stmt_list_hash hash;
849
850   /* The number of symtabs from the line header.
851      The value here must match line_header.num_file_names.  */
852   unsigned int num_symtabs;
853
854   /* The symbol tables for this TU (obtained from the files listed in
855      DW_AT_stmt_list).
856      WARNING: The order of entries here must match the order of entries
857      in the line header.  After the first TU using this type_unit_group, the
858      line header for the subsequent TUs is recreated from this.  This is done
859      because we need to use the same symtabs for each TU using the same
860      DW_AT_stmt_list value.  Also note that symtabs may be repeated here,
861      there's no guarantee the line header doesn't have duplicate entries.  */
862   struct symtab **symtabs;
863 };
864
865 /* These sections are what may appear in a (real or virtual) DWO file.  */
866
867 struct dwo_sections
868 {
869   struct dwarf2_section_info abbrev;
870   struct dwarf2_section_info line;
871   struct dwarf2_section_info loc;
872   struct dwarf2_section_info loclists;
873   struct dwarf2_section_info macinfo;
874   struct dwarf2_section_info macro;
875   struct dwarf2_section_info str;
876   struct dwarf2_section_info str_offsets;
877   /* In the case of a virtual DWO file, these two are unused.  */
878   struct dwarf2_section_info info;
879   VEC (dwarf2_section_info_def) *types;
880 };
881
882 /* CUs/TUs in DWP/DWO files.  */
883
884 struct dwo_unit
885 {
886   /* Backlink to the containing struct dwo_file.  */
887   struct dwo_file *dwo_file;
888
889   /* The "id" that distinguishes this CU/TU.
890      .debug_info calls this "dwo_id", .debug_types calls this "signature".
891      Since signatures came first, we stick with it for consistency.  */
892   ULONGEST signature;
893
894   /* The section this CU/TU lives in, in the DWO file.  */
895   struct dwarf2_section_info *section;
896
897   /* Same as dwarf2_per_cu_data:{sect_off,length} but in the DWO section.  */
898   sect_offset sect_off;
899   unsigned int length;
900
901   /* For types, offset in the type's DIE of the type defined by this TU.  */
902   cu_offset type_offset_in_tu;
903 };
904
905 /* include/dwarf2.h defines the DWP section codes.
906    It defines a max value but it doesn't define a min value, which we
907    use for error checking, so provide one.  */
908
909 enum dwp_v2_section_ids
910 {
911   DW_SECT_MIN = 1
912 };
913
914 /* Data for one DWO file.
915
916    This includes virtual DWO files (a virtual DWO file is a DWO file as it
917    appears in a DWP file).  DWP files don't really have DWO files per se -
918    comdat folding of types "loses" the DWO file they came from, and from
919    a high level view DWP files appear to contain a mass of random types.
920    However, to maintain consistency with the non-DWP case we pretend DWP
921    files contain virtual DWO files, and we assign each TU with one virtual
922    DWO file (generally based on the line and abbrev section offsets -
923    a heuristic that seems to work in practice).  */
924
925 struct dwo_file
926 {
927   /* The DW_AT_GNU_dwo_name attribute.
928      For virtual DWO files the name is constructed from the section offsets
929      of abbrev,line,loc,str_offsets so that we combine virtual DWO files
930      from related CU+TUs.  */
931   const char *dwo_name;
932
933   /* The DW_AT_comp_dir attribute.  */
934   const char *comp_dir;
935
936   /* The bfd, when the file is open.  Otherwise this is NULL.
937      This is unused(NULL) for virtual DWO files where we use dwp_file.dbfd.  */
938   bfd *dbfd;
939
940   /* The sections that make up this DWO file.
941      Remember that for virtual DWO files in DWP V2, these are virtual
942      sections (for lack of a better name).  */
943   struct dwo_sections sections;
944
945   /* The CUs in the file.
946      Each element is a struct dwo_unit. Multiple CUs per DWO are supported as
947      an extension to handle LLVM's Link Time Optimization output (where
948      multiple source files may be compiled into a single object/dwo pair). */
949   htab_t cus;
950
951   /* Table of TUs in the file.
952      Each element is a struct dwo_unit.  */
953   htab_t tus;
954 };
955
956 /* These sections are what may appear in a DWP file.  */
957
958 struct dwp_sections
959 {
960   /* These are used by both DWP version 1 and 2.  */
961   struct dwarf2_section_info str;
962   struct dwarf2_section_info cu_index;
963   struct dwarf2_section_info tu_index;
964
965   /* These are only used by DWP version 2 files.
966      In DWP version 1 the .debug_info.dwo, .debug_types.dwo, and other
967      sections are referenced by section number, and are not recorded here.
968      In DWP version 2 there is at most one copy of all these sections, each
969      section being (effectively) comprised of the concatenation of all of the
970      individual sections that exist in the version 1 format.
971      To keep the code simple we treat each of these concatenated pieces as a
972      section itself (a virtual section?).  */
973   struct dwarf2_section_info abbrev;
974   struct dwarf2_section_info info;
975   struct dwarf2_section_info line;
976   struct dwarf2_section_info loc;
977   struct dwarf2_section_info macinfo;
978   struct dwarf2_section_info macro;
979   struct dwarf2_section_info str_offsets;
980   struct dwarf2_section_info types;
981 };
982
983 /* These sections are what may appear in a virtual DWO file in DWP version 1.
984    A virtual DWO file is a DWO file as it appears in a DWP file.  */
985
986 struct virtual_v1_dwo_sections
987 {
988   struct dwarf2_section_info abbrev;
989   struct dwarf2_section_info line;
990   struct dwarf2_section_info loc;
991   struct dwarf2_section_info macinfo;
992   struct dwarf2_section_info macro;
993   struct dwarf2_section_info str_offsets;
994   /* Each DWP hash table entry records one CU or one TU.
995      That is recorded here, and copied to dwo_unit.section.  */
996   struct dwarf2_section_info info_or_types;
997 };
998
999 /* Similar to virtual_v1_dwo_sections, but for DWP version 2.
1000    In version 2, the sections of the DWO files are concatenated together
1001    and stored in one section of that name.  Thus each ELF section contains
1002    several "virtual" sections.  */
1003
1004 struct virtual_v2_dwo_sections
1005 {
1006   bfd_size_type abbrev_offset;
1007   bfd_size_type abbrev_size;
1008
1009   bfd_size_type line_offset;
1010   bfd_size_type line_size;
1011
1012   bfd_size_type loc_offset;
1013   bfd_size_type loc_size;
1014
1015   bfd_size_type macinfo_offset;
1016   bfd_size_type macinfo_size;
1017
1018   bfd_size_type macro_offset;
1019   bfd_size_type macro_size;
1020
1021   bfd_size_type str_offsets_offset;
1022   bfd_size_type str_offsets_size;
1023
1024   /* Each DWP hash table entry records one CU or one TU.
1025      That is recorded here, and copied to dwo_unit.section.  */
1026   bfd_size_type info_or_types_offset;
1027   bfd_size_type info_or_types_size;
1028 };
1029
1030 /* Contents of DWP hash tables.  */
1031
1032 struct dwp_hash_table
1033 {
1034   uint32_t version, nr_columns;
1035   uint32_t nr_units, nr_slots;
1036   const gdb_byte *hash_table, *unit_table;
1037   union
1038   {
1039     struct
1040     {
1041       const gdb_byte *indices;
1042     } v1;
1043     struct
1044     {
1045       /* This is indexed by column number and gives the id of the section
1046          in that column.  */
1047 #define MAX_NR_V2_DWO_SECTIONS \
1048   (1 /* .debug_info or .debug_types */ \
1049    + 1 /* .debug_abbrev */ \
1050    + 1 /* .debug_line */ \
1051    + 1 /* .debug_loc */ \
1052    + 1 /* .debug_str_offsets */ \
1053    + 1 /* .debug_macro or .debug_macinfo */)
1054       int section_ids[MAX_NR_V2_DWO_SECTIONS];
1055       const gdb_byte *offsets;
1056       const gdb_byte *sizes;
1057     } v2;
1058   } section_pool;
1059 };
1060
1061 /* Data for one DWP file.  */
1062
1063 struct dwp_file
1064 {
1065   /* Name of the file.  */
1066   const char *name;
1067
1068   /* File format version.  */
1069   int version;
1070
1071   /* The bfd.  */
1072   bfd *dbfd;
1073
1074   /* Section info for this file.  */
1075   struct dwp_sections sections;
1076
1077   /* Table of CUs in the file.  */
1078   const struct dwp_hash_table *cus;
1079
1080   /* Table of TUs in the file.  */
1081   const struct dwp_hash_table *tus;
1082
1083   /* Tables of loaded CUs/TUs.  Each entry is a struct dwo_unit *.  */
1084   htab_t loaded_cus;
1085   htab_t loaded_tus;
1086
1087   /* Table to map ELF section numbers to their sections.
1088      This is only needed for the DWP V1 file format.  */
1089   unsigned int num_sections;
1090   asection **elf_sections;
1091 };
1092
1093 /* This represents a '.dwz' file.  */
1094
1095 struct dwz_file
1096 {
1097   /* A dwz file can only contain a few sections.  */
1098   struct dwarf2_section_info abbrev;
1099   struct dwarf2_section_info info;
1100   struct dwarf2_section_info str;
1101   struct dwarf2_section_info line;
1102   struct dwarf2_section_info macro;
1103   struct dwarf2_section_info gdb_index;
1104
1105   /* The dwz's BFD.  */
1106   bfd *dwz_bfd;
1107 };
1108
1109 /* Struct used to pass misc. parameters to read_die_and_children, et
1110    al.  which are used for both .debug_info and .debug_types dies.
1111    All parameters here are unchanging for the life of the call.  This
1112    struct exists to abstract away the constant parameters of die reading.  */
1113
1114 struct die_reader_specs
1115 {
1116   /* The bfd of die_section.  */
1117   bfd* abfd;
1118
1119   /* The CU of the DIE we are parsing.  */
1120   struct dwarf2_cu *cu;
1121
1122   /* Non-NULL if reading a DWO file (including one packaged into a DWP).  */
1123   struct dwo_file *dwo_file;
1124
1125   /* The section the die comes from.
1126      This is either .debug_info or .debug_types, or the .dwo variants.  */
1127   struct dwarf2_section_info *die_section;
1128
1129   /* die_section->buffer.  */
1130   const gdb_byte *buffer;
1131
1132   /* The end of the buffer.  */
1133   const gdb_byte *buffer_end;
1134
1135   /* The value of the DW_AT_comp_dir attribute.  */
1136   const char *comp_dir;
1137 };
1138
1139 /* Type of function passed to init_cutu_and_read_dies, et.al.  */
1140 typedef void (die_reader_func_ftype) (const struct die_reader_specs *reader,
1141                                       const gdb_byte *info_ptr,
1142                                       struct die_info *comp_unit_die,
1143                                       int has_children,
1144                                       void *data);
1145
1146 /* A 1-based directory index.  This is a strong typedef to prevent
1147    accidentally using a directory index as a 0-based index into an
1148    array/vector.  */
1149 enum class dir_index : unsigned int {};
1150
1151 /* Likewise, a 1-based file name index.  */
1152 enum class file_name_index : unsigned int {};
1153
1154 struct file_entry
1155 {
1156   file_entry () = default;
1157
1158   file_entry (const char *name_, dir_index d_index_,
1159               unsigned int mod_time_, unsigned int length_)
1160     : name (name_),
1161       d_index (d_index_),
1162       mod_time (mod_time_),
1163       length (length_)
1164   {}
1165
1166   /* Return the include directory at D_INDEX stored in LH.  Returns
1167      NULL if D_INDEX is out of bounds.  */
1168   const char *include_dir (const line_header *lh) const;
1169
1170   /* The file name.  Note this is an observing pointer.  The memory is
1171      owned by debug_line_buffer.  */
1172   const char *name {};
1173
1174   /* The directory index (1-based).  */
1175   dir_index d_index {};
1176
1177   unsigned int mod_time {};
1178
1179   unsigned int length {};
1180
1181   /* True if referenced by the Line Number Program.  */
1182   bool included_p {};
1183
1184   /* The associated symbol table, if any.  */
1185   struct symtab *symtab {};
1186 };
1187
1188 /* The line number information for a compilation unit (found in the
1189    .debug_line section) begins with a "statement program header",
1190    which contains the following information.  */
1191 struct line_header
1192 {
1193   line_header ()
1194     : offset_in_dwz {}
1195   {}
1196
1197   /* Add an entry to the include directory table.  */
1198   void add_include_dir (const char *include_dir);
1199
1200   /* Add an entry to the file name table.  */
1201   void add_file_name (const char *name, dir_index d_index,
1202                       unsigned int mod_time, unsigned int length);
1203
1204   /* Return the include dir at INDEX (1-based).  Returns NULL if INDEX
1205      is out of bounds.  */
1206   const char *include_dir_at (dir_index index) const
1207   {
1208     /* Convert directory index number (1-based) to vector index
1209        (0-based).  */
1210     size_t vec_index = to_underlying (index) - 1;
1211
1212     if (vec_index >= include_dirs.size ())
1213       return NULL;
1214     return include_dirs[vec_index];
1215   }
1216
1217   /* Return the file name at INDEX (1-based).  Returns NULL if INDEX
1218      is out of bounds.  */
1219   file_entry *file_name_at (file_name_index index)
1220   {
1221     /* Convert file name index number (1-based) to vector index
1222        (0-based).  */
1223     size_t vec_index = to_underlying (index) - 1;
1224
1225     if (vec_index >= file_names.size ())
1226       return NULL;
1227     return &file_names[vec_index];
1228   }
1229
1230   /* Const version of the above.  */
1231   const file_entry *file_name_at (unsigned int index) const
1232   {
1233     if (index >= file_names.size ())
1234       return NULL;
1235     return &file_names[index];
1236   }
1237
1238   /* Offset of line number information in .debug_line section.  */
1239   sect_offset sect_off {};
1240
1241   /* OFFSET is for struct dwz_file associated with dwarf2_per_objfile.  */
1242   unsigned offset_in_dwz : 1; /* Can't initialize bitfields in-class.  */
1243
1244   unsigned int total_length {};
1245   unsigned short version {};
1246   unsigned int header_length {};
1247   unsigned char minimum_instruction_length {};
1248   unsigned char maximum_ops_per_instruction {};
1249   unsigned char default_is_stmt {};
1250   int line_base {};
1251   unsigned char line_range {};
1252   unsigned char opcode_base {};
1253
1254   /* standard_opcode_lengths[i] is the number of operands for the
1255      standard opcode whose value is i.  This means that
1256      standard_opcode_lengths[0] is unused, and the last meaningful
1257      element is standard_opcode_lengths[opcode_base - 1].  */
1258   std::unique_ptr<unsigned char[]> standard_opcode_lengths;
1259
1260   /* The include_directories table.  Note these are observing
1261      pointers.  The memory is owned by debug_line_buffer.  */
1262   std::vector<const char *> include_dirs;
1263
1264   /* The file_names table.  */
1265   std::vector<file_entry> file_names;
1266
1267   /* The start and end of the statement program following this
1268      header.  These point into dwarf2_per_objfile->line_buffer.  */
1269   const gdb_byte *statement_program_start {}, *statement_program_end {};
1270 };
1271
1272 typedef std::unique_ptr<line_header> line_header_up;
1273
1274 const char *
1275 file_entry::include_dir (const line_header *lh) const
1276 {
1277   return lh->include_dir_at (d_index);
1278 }
1279
1280 /* When we construct a partial symbol table entry we only
1281    need this much information.  */
1282 struct partial_die_info
1283   {
1284     /* Offset of this DIE.  */
1285     sect_offset sect_off;
1286
1287     /* DWARF-2 tag for this DIE.  */
1288     ENUM_BITFIELD(dwarf_tag) tag : 16;
1289
1290     /* Assorted flags describing the data found in this DIE.  */
1291     unsigned int has_children : 1;
1292     unsigned int is_external : 1;
1293     unsigned int is_declaration : 1;
1294     unsigned int has_type : 1;
1295     unsigned int has_specification : 1;
1296     unsigned int has_pc_info : 1;
1297     unsigned int may_be_inlined : 1;
1298
1299     /* This DIE has been marked DW_AT_main_subprogram.  */
1300     unsigned int main_subprogram : 1;
1301
1302     /* Flag set if the SCOPE field of this structure has been
1303        computed.  */
1304     unsigned int scope_set : 1;
1305
1306     /* Flag set if the DIE has a byte_size attribute.  */
1307     unsigned int has_byte_size : 1;
1308
1309     /* Flag set if the DIE has a DW_AT_const_value attribute.  */
1310     unsigned int has_const_value : 1;
1311
1312     /* Flag set if any of the DIE's children are template arguments.  */
1313     unsigned int has_template_arguments : 1;
1314
1315     /* Flag set if fixup_partial_die has been called on this die.  */
1316     unsigned int fixup_called : 1;
1317
1318     /* Flag set if DW_TAG_imported_unit uses DW_FORM_GNU_ref_alt.  */
1319     unsigned int is_dwz : 1;
1320
1321     /* Flag set if spec_offset uses DW_FORM_GNU_ref_alt.  */
1322     unsigned int spec_is_dwz : 1;
1323
1324     /* The name of this DIE.  Normally the value of DW_AT_name, but
1325        sometimes a default name for unnamed DIEs.  */
1326     const char *name;
1327
1328     /* The linkage name, if present.  */
1329     const char *linkage_name;
1330
1331     /* The scope to prepend to our children.  This is generally
1332        allocated on the comp_unit_obstack, so will disappear
1333        when this compilation unit leaves the cache.  */
1334     const char *scope;
1335
1336     /* Some data associated with the partial DIE.  The tag determines
1337        which field is live.  */
1338     union
1339     {
1340       /* The location description associated with this DIE, if any.  */
1341       struct dwarf_block *locdesc;
1342       /* The offset of an import, for DW_TAG_imported_unit.  */
1343       sect_offset sect_off;
1344     } d;
1345
1346     /* If HAS_PC_INFO, the PC range associated with this DIE.  */
1347     CORE_ADDR lowpc;
1348     CORE_ADDR highpc;
1349
1350     /* Pointer into the info_buffer (or types_buffer) pointing at the target of
1351        DW_AT_sibling, if any.  */
1352     /* NOTE: This member isn't strictly necessary, read_partial_die could
1353        return DW_AT_sibling values to its caller load_partial_dies.  */
1354     const gdb_byte *sibling;
1355
1356     /* If HAS_SPECIFICATION, the offset of the DIE referred to by
1357        DW_AT_specification (or DW_AT_abstract_origin or
1358        DW_AT_extension).  */
1359     sect_offset spec_offset;
1360
1361     /* Pointers to this DIE's parent, first child, and next sibling,
1362        if any.  */
1363     struct partial_die_info *die_parent, *die_child, *die_sibling;
1364   };
1365
1366 /* This data structure holds the information of an abbrev.  */
1367 struct abbrev_info
1368   {
1369     unsigned int number;        /* number identifying abbrev */
1370     enum dwarf_tag tag;         /* dwarf tag */
1371     unsigned short has_children;                /* boolean */
1372     unsigned short num_attrs;   /* number of attributes */
1373     struct attr_abbrev *attrs;  /* an array of attribute descriptions */
1374     struct abbrev_info *next;   /* next in chain */
1375   };
1376
1377 struct attr_abbrev
1378   {
1379     ENUM_BITFIELD(dwarf_attribute) name : 16;
1380     ENUM_BITFIELD(dwarf_form) form : 16;
1381
1382     /* It is valid only if FORM is DW_FORM_implicit_const.  */
1383     LONGEST implicit_const;
1384   };
1385
1386 /* Size of abbrev_table.abbrev_hash_table.  */
1387 #define ABBREV_HASH_SIZE 121
1388
1389 /* Top level data structure to contain an abbreviation table.  */
1390
1391 struct abbrev_table
1392 {
1393   /* Where the abbrev table came from.
1394      This is used as a sanity check when the table is used.  */
1395   sect_offset sect_off;
1396
1397   /* Storage for the abbrev table.  */
1398   struct obstack abbrev_obstack;
1399
1400   /* Hash table of abbrevs.
1401      This is an array of size ABBREV_HASH_SIZE allocated in abbrev_obstack.
1402      It could be statically allocated, but the previous code didn't so we
1403      don't either.  */
1404   struct abbrev_info **abbrevs;
1405 };
1406
1407 /* Attributes have a name and a value.  */
1408 struct attribute
1409   {
1410     ENUM_BITFIELD(dwarf_attribute) name : 16;
1411     ENUM_BITFIELD(dwarf_form) form : 15;
1412
1413     /* Has DW_STRING already been updated by dwarf2_canonicalize_name?  This
1414        field should be in u.str (existing only for DW_STRING) but it is kept
1415        here for better struct attribute alignment.  */
1416     unsigned int string_is_canonical : 1;
1417
1418     union
1419       {
1420         const char *str;
1421         struct dwarf_block *blk;
1422         ULONGEST unsnd;
1423         LONGEST snd;
1424         CORE_ADDR addr;
1425         ULONGEST signature;
1426       }
1427     u;
1428   };
1429
1430 /* This data structure holds a complete die structure.  */
1431 struct die_info
1432   {
1433     /* DWARF-2 tag for this DIE.  */
1434     ENUM_BITFIELD(dwarf_tag) tag : 16;
1435
1436     /* Number of attributes */
1437     unsigned char num_attrs;
1438
1439     /* True if we're presently building the full type name for the
1440        type derived from this DIE.  */
1441     unsigned char building_fullname : 1;
1442
1443     /* True if this die is in process.  PR 16581.  */
1444     unsigned char in_process : 1;
1445
1446     /* Abbrev number */
1447     unsigned int abbrev;
1448
1449     /* Offset in .debug_info or .debug_types section.  */
1450     sect_offset sect_off;
1451
1452     /* The dies in a compilation unit form an n-ary tree.  PARENT
1453        points to this die's parent; CHILD points to the first child of
1454        this node; and all the children of a given node are chained
1455        together via their SIBLING fields.  */
1456     struct die_info *child;     /* Its first child, if any.  */
1457     struct die_info *sibling;   /* Its next sibling, if any.  */
1458     struct die_info *parent;    /* Its parent, if any.  */
1459
1460     /* An array of attributes, with NUM_ATTRS elements.  There may be
1461        zero, but it's not common and zero-sized arrays are not
1462        sufficiently portable C.  */
1463     struct attribute attrs[1];
1464   };
1465
1466 /* Get at parts of an attribute structure.  */
1467
1468 #define DW_STRING(attr)    ((attr)->u.str)
1469 #define DW_STRING_IS_CANONICAL(attr) ((attr)->string_is_canonical)
1470 #define DW_UNSND(attr)     ((attr)->u.unsnd)
1471 #define DW_BLOCK(attr)     ((attr)->u.blk)
1472 #define DW_SND(attr)       ((attr)->u.snd)
1473 #define DW_ADDR(attr)      ((attr)->u.addr)
1474 #define DW_SIGNATURE(attr) ((attr)->u.signature)
1475
1476 /* Blocks are a bunch of untyped bytes.  */
1477 struct dwarf_block
1478   {
1479     size_t size;
1480
1481     /* Valid only if SIZE is not zero.  */
1482     const gdb_byte *data;
1483   };
1484
1485 #ifndef ATTR_ALLOC_CHUNK
1486 #define ATTR_ALLOC_CHUNK 4
1487 #endif
1488
1489 /* Allocate fields for structs, unions and enums in this size.  */
1490 #ifndef DW_FIELD_ALLOC_CHUNK
1491 #define DW_FIELD_ALLOC_CHUNK 4
1492 #endif
1493
1494 /* FIXME: We might want to set this from BFD via bfd_arch_bits_per_byte,
1495    but this would require a corresponding change in unpack_field_as_long
1496    and friends.  */
1497 static int bits_per_byte = 8;
1498
1499 struct nextfield
1500 {
1501   struct nextfield *next;
1502   int accessibility;
1503   int virtuality;
1504   struct field field;
1505 };
1506
1507 struct nextfnfield
1508 {
1509   struct nextfnfield *next;
1510   struct fn_field fnfield;
1511 };
1512
1513 struct fnfieldlist
1514 {
1515   const char *name;
1516   int length;
1517   struct nextfnfield *head;
1518 };
1519
1520 struct typedef_field_list
1521 {
1522   struct typedef_field field;
1523   struct typedef_field_list *next;
1524 };
1525
1526 /* The routines that read and process dies for a C struct or C++ class
1527    pass lists of data member fields and lists of member function fields
1528    in an instance of a field_info structure, as defined below.  */
1529 struct field_info
1530   {
1531     /* List of data member and baseclasses fields.  */
1532     struct nextfield *fields, *baseclasses;
1533
1534     /* Number of fields (including baseclasses).  */
1535     int nfields;
1536
1537     /* Number of baseclasses.  */
1538     int nbaseclasses;
1539
1540     /* Set if the accesibility of one of the fields is not public.  */
1541     int non_public_fields;
1542
1543     /* Member function fieldlist array, contains name of possibly overloaded
1544        member function, number of overloaded member functions and a pointer
1545        to the head of the member function field chain.  */
1546     struct fnfieldlist *fnfieldlists;
1547
1548     /* Number of entries in the fnfieldlists array.  */
1549     int nfnfields;
1550
1551     /* typedefs defined inside this class.  TYPEDEF_FIELD_LIST contains head of
1552        a NULL terminated list of TYPEDEF_FIELD_LIST_COUNT elements.  */
1553     struct typedef_field_list *typedef_field_list;
1554     unsigned typedef_field_list_count;
1555   };
1556
1557 /* One item on the queue of compilation units to read in full symbols
1558    for.  */
1559 struct dwarf2_queue_item
1560 {
1561   struct dwarf2_per_cu_data *per_cu;
1562   enum language pretend_language;
1563   struct dwarf2_queue_item *next;
1564 };
1565
1566 /* The current queue.  */
1567 static struct dwarf2_queue_item *dwarf2_queue, *dwarf2_queue_tail;
1568
1569 /* Loaded secondary compilation units are kept in memory until they
1570    have not been referenced for the processing of this many
1571    compilation units.  Set this to zero to disable caching.  Cache
1572    sizes of up to at least twenty will improve startup time for
1573    typical inter-CU-reference binaries, at an obvious memory cost.  */
1574 static int dwarf_max_cache_age = 5;
1575 static void
1576 show_dwarf_max_cache_age (struct ui_file *file, int from_tty,
1577                           struct cmd_list_element *c, const char *value)
1578 {
1579   fprintf_filtered (file, _("The upper bound on the age of cached "
1580                             "DWARF compilation units is %s.\n"),
1581                     value);
1582 }
1583 \f
1584 /* local function prototypes */
1585
1586 static const char *get_section_name (const struct dwarf2_section_info *);
1587
1588 static const char *get_section_file_name (const struct dwarf2_section_info *);
1589
1590 static void dwarf2_find_base_address (struct die_info *die,
1591                                       struct dwarf2_cu *cu);
1592
1593 static struct partial_symtab *create_partial_symtab
1594   (struct dwarf2_per_cu_data *per_cu, const char *name);
1595
1596 static void build_type_psymtabs_reader (const struct die_reader_specs *reader,
1597                                         const gdb_byte *info_ptr,
1598                                         struct die_info *type_unit_die,
1599                                         int has_children, void *data);
1600
1601 static void dwarf2_build_psymtabs_hard (struct objfile *);
1602
1603 static void scan_partial_symbols (struct partial_die_info *,
1604                                   CORE_ADDR *, CORE_ADDR *,
1605                                   int, struct dwarf2_cu *);
1606
1607 static void add_partial_symbol (struct partial_die_info *,
1608                                 struct dwarf2_cu *);
1609
1610 static void add_partial_namespace (struct partial_die_info *pdi,
1611                                    CORE_ADDR *lowpc, CORE_ADDR *highpc,
1612                                    int set_addrmap, struct dwarf2_cu *cu);
1613
1614 static void add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
1615                                 CORE_ADDR *highpc, int set_addrmap,
1616                                 struct dwarf2_cu *cu);
1617
1618 static void add_partial_enumeration (struct partial_die_info *enum_pdi,
1619                                      struct dwarf2_cu *cu);
1620
1621 static void add_partial_subprogram (struct partial_die_info *pdi,
1622                                     CORE_ADDR *lowpc, CORE_ADDR *highpc,
1623                                     int need_pc, struct dwarf2_cu *cu);
1624
1625 static void dwarf2_read_symtab (struct partial_symtab *,
1626                                 struct objfile *);
1627
1628 static void psymtab_to_symtab_1 (struct partial_symtab *);
1629
1630 static struct abbrev_info *abbrev_table_lookup_abbrev
1631   (const struct abbrev_table *, unsigned int);
1632
1633 static struct abbrev_table *abbrev_table_read_table
1634   (struct dwarf2_section_info *, sect_offset);
1635
1636 static void abbrev_table_free (struct abbrev_table *);
1637
1638 static void abbrev_table_free_cleanup (void *);
1639
1640 static void dwarf2_read_abbrevs (struct dwarf2_cu *,
1641                                  struct dwarf2_section_info *);
1642
1643 static void dwarf2_free_abbrev_table (void *);
1644
1645 static unsigned int peek_abbrev_code (bfd *, const gdb_byte *);
1646
1647 static struct partial_die_info *load_partial_dies
1648   (const struct die_reader_specs *, const gdb_byte *, int);
1649
1650 static const gdb_byte *read_partial_die (const struct die_reader_specs *,
1651                                          struct partial_die_info *,
1652                                          struct abbrev_info *,
1653                                          unsigned int,
1654                                          const gdb_byte *);
1655
1656 static struct partial_die_info *find_partial_die (sect_offset, int,
1657                                                   struct dwarf2_cu *);
1658
1659 static void fixup_partial_die (struct partial_die_info *,
1660                                struct dwarf2_cu *);
1661
1662 static const gdb_byte *read_attribute (const struct die_reader_specs *,
1663                                        struct attribute *, struct attr_abbrev *,
1664                                        const gdb_byte *);
1665
1666 static unsigned int read_1_byte (bfd *, const gdb_byte *);
1667
1668 static int read_1_signed_byte (bfd *, const gdb_byte *);
1669
1670 static unsigned int read_2_bytes (bfd *, const gdb_byte *);
1671
1672 static unsigned int read_4_bytes (bfd *, const gdb_byte *);
1673
1674 static ULONGEST read_8_bytes (bfd *, const gdb_byte *);
1675
1676 static CORE_ADDR read_address (bfd *, const gdb_byte *ptr, struct dwarf2_cu *,
1677                                unsigned int *);
1678
1679 static LONGEST read_initial_length (bfd *, const gdb_byte *, unsigned int *);
1680
1681 static LONGEST read_checked_initial_length_and_offset
1682   (bfd *, const gdb_byte *, const struct comp_unit_head *,
1683    unsigned int *, unsigned int *);
1684
1685 static LONGEST read_offset (bfd *, const gdb_byte *,
1686                             const struct comp_unit_head *,
1687                             unsigned int *);
1688
1689 static LONGEST read_offset_1 (bfd *, const gdb_byte *, unsigned int);
1690
1691 static sect_offset read_abbrev_offset (struct dwarf2_section_info *,
1692                                        sect_offset);
1693
1694 static const gdb_byte *read_n_bytes (bfd *, const gdb_byte *, unsigned int);
1695
1696 static const char *read_direct_string (bfd *, const gdb_byte *, unsigned int *);
1697
1698 static const char *read_indirect_string (bfd *, const gdb_byte *,
1699                                          const struct comp_unit_head *,
1700                                          unsigned int *);
1701
1702 static const char *read_indirect_line_string (bfd *, const gdb_byte *,
1703                                               const struct comp_unit_head *,
1704                                               unsigned int *);
1705
1706 static const char *read_indirect_string_from_dwz (struct dwz_file *, LONGEST);
1707
1708 static LONGEST read_signed_leb128 (bfd *, const gdb_byte *, unsigned int *);
1709
1710 static CORE_ADDR read_addr_index_from_leb128 (struct dwarf2_cu *,
1711                                               const gdb_byte *,
1712                                               unsigned int *);
1713
1714 static const char *read_str_index (const struct die_reader_specs *reader,
1715                                    ULONGEST str_index);
1716
1717 static void set_cu_language (unsigned int, struct dwarf2_cu *);
1718
1719 static struct attribute *dwarf2_attr (struct die_info *, unsigned int,
1720                                       struct dwarf2_cu *);
1721
1722 static struct attribute *dwarf2_attr_no_follow (struct die_info *,
1723                                                 unsigned int);
1724
1725 static const char *dwarf2_string_attr (struct die_info *die, unsigned int name,
1726                                        struct dwarf2_cu *cu);
1727
1728 static int dwarf2_flag_true_p (struct die_info *die, unsigned name,
1729                                struct dwarf2_cu *cu);
1730
1731 static int die_is_declaration (struct die_info *, struct dwarf2_cu *cu);
1732
1733 static struct die_info *die_specification (struct die_info *die,
1734                                            struct dwarf2_cu **);
1735
1736 static line_header_up dwarf_decode_line_header (sect_offset sect_off,
1737                                                 struct dwarf2_cu *cu);
1738
1739 static void dwarf_decode_lines (struct line_header *, const char *,
1740                                 struct dwarf2_cu *, struct partial_symtab *,
1741                                 CORE_ADDR, int decode_mapping);
1742
1743 static void dwarf2_start_subfile (const char *, const char *);
1744
1745 static struct compunit_symtab *dwarf2_start_symtab (struct dwarf2_cu *,
1746                                                     const char *, const char *,
1747                                                     CORE_ADDR);
1748
1749 static struct symbol *new_symbol (struct die_info *, struct type *,
1750                                   struct dwarf2_cu *);
1751
1752 static struct symbol *new_symbol_full (struct die_info *, struct type *,
1753                                        struct dwarf2_cu *, struct symbol *);
1754
1755 static void dwarf2_const_value (const struct attribute *, struct symbol *,
1756                                 struct dwarf2_cu *);
1757
1758 static void dwarf2_const_value_attr (const struct attribute *attr,
1759                                      struct type *type,
1760                                      const char *name,
1761                                      struct obstack *obstack,
1762                                      struct dwarf2_cu *cu, LONGEST *value,
1763                                      const gdb_byte **bytes,
1764                                      struct dwarf2_locexpr_baton **baton);
1765
1766 static struct type *die_type (struct die_info *, struct dwarf2_cu *);
1767
1768 static int need_gnat_info (struct dwarf2_cu *);
1769
1770 static struct type *die_descriptive_type (struct die_info *,
1771                                           struct dwarf2_cu *);
1772
1773 static void set_descriptive_type (struct type *, struct die_info *,
1774                                   struct dwarf2_cu *);
1775
1776 static struct type *die_containing_type (struct die_info *,
1777                                          struct dwarf2_cu *);
1778
1779 static struct type *lookup_die_type (struct die_info *, const struct attribute *,
1780                                      struct dwarf2_cu *);
1781
1782 static struct type *read_type_die (struct die_info *, struct dwarf2_cu *);
1783
1784 static struct type *read_type_die_1 (struct die_info *, struct dwarf2_cu *);
1785
1786 static const char *determine_prefix (struct die_info *die, struct dwarf2_cu *);
1787
1788 static char *typename_concat (struct obstack *obs, const char *prefix,
1789                               const char *suffix, int physname,
1790                               struct dwarf2_cu *cu);
1791
1792 static void read_file_scope (struct die_info *, struct dwarf2_cu *);
1793
1794 static void read_type_unit_scope (struct die_info *, struct dwarf2_cu *);
1795
1796 static void read_func_scope (struct die_info *, struct dwarf2_cu *);
1797
1798 static void read_lexical_block_scope (struct die_info *, struct dwarf2_cu *);
1799
1800 static void read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu);
1801
1802 static int dwarf2_ranges_read (unsigned, CORE_ADDR *, CORE_ADDR *,
1803                                struct dwarf2_cu *, struct partial_symtab *);
1804
1805 /* How dwarf2_get_pc_bounds constructed its *LOWPC and *HIGHPC return
1806    values.  Keep the items ordered with increasing constraints compliance.  */
1807 enum pc_bounds_kind
1808 {
1809   /* No attribute DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges was found.  */
1810   PC_BOUNDS_NOT_PRESENT,
1811
1812   /* Some of the attributes DW_AT_low_pc, DW_AT_high_pc or DW_AT_ranges
1813      were present but they do not form a valid range of PC addresses.  */
1814   PC_BOUNDS_INVALID,
1815
1816   /* Discontiguous range was found - that is DW_AT_ranges was found.  */
1817   PC_BOUNDS_RANGES,
1818
1819   /* Contiguous range was found - DW_AT_low_pc and DW_AT_high_pc were found.  */
1820   PC_BOUNDS_HIGH_LOW,
1821 };
1822
1823 static enum pc_bounds_kind dwarf2_get_pc_bounds (struct die_info *,
1824                                                  CORE_ADDR *, CORE_ADDR *,
1825                                                  struct dwarf2_cu *,
1826                                                  struct partial_symtab *);
1827
1828 static void get_scope_pc_bounds (struct die_info *,
1829                                  CORE_ADDR *, CORE_ADDR *,
1830                                  struct dwarf2_cu *);
1831
1832 static void dwarf2_record_block_ranges (struct die_info *, struct block *,
1833                                         CORE_ADDR, struct dwarf2_cu *);
1834
1835 static void dwarf2_add_field (struct field_info *, struct die_info *,
1836                               struct dwarf2_cu *);
1837
1838 static void dwarf2_attach_fields_to_type (struct field_info *,
1839                                           struct type *, struct dwarf2_cu *);
1840
1841 static void dwarf2_add_member_fn (struct field_info *,
1842                                   struct die_info *, struct type *,
1843                                   struct dwarf2_cu *);
1844
1845 static void dwarf2_attach_fn_fields_to_type (struct field_info *,
1846                                              struct type *,
1847                                              struct dwarf2_cu *);
1848
1849 static void process_structure_scope (struct die_info *, struct dwarf2_cu *);
1850
1851 static void read_common_block (struct die_info *, struct dwarf2_cu *);
1852
1853 static void read_namespace (struct die_info *die, struct dwarf2_cu *);
1854
1855 static void read_module (struct die_info *die, struct dwarf2_cu *cu);
1856
1857 static struct using_direct **using_directives (enum language);
1858
1859 static void read_import_statement (struct die_info *die, struct dwarf2_cu *);
1860
1861 static int read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu);
1862
1863 static struct type *read_module_type (struct die_info *die,
1864                                       struct dwarf2_cu *cu);
1865
1866 static const char *namespace_name (struct die_info *die,
1867                                    int *is_anonymous, struct dwarf2_cu *);
1868
1869 static void process_enumeration_scope (struct die_info *, struct dwarf2_cu *);
1870
1871 static CORE_ADDR decode_locdesc (struct dwarf_block *, struct dwarf2_cu *);
1872
1873 static enum dwarf_array_dim_ordering read_array_order (struct die_info *,
1874                                                        struct dwarf2_cu *);
1875
1876 static struct die_info *read_die_and_siblings_1
1877   (const struct die_reader_specs *, const gdb_byte *, const gdb_byte **,
1878    struct die_info *);
1879
1880 static struct die_info *read_die_and_siblings (const struct die_reader_specs *,
1881                                                const gdb_byte *info_ptr,
1882                                                const gdb_byte **new_info_ptr,
1883                                                struct die_info *parent);
1884
1885 static const gdb_byte *read_full_die_1 (const struct die_reader_specs *,
1886                                         struct die_info **, const gdb_byte *,
1887                                         int *, int);
1888
1889 static const gdb_byte *read_full_die (const struct die_reader_specs *,
1890                                       struct die_info **, const gdb_byte *,
1891                                       int *);
1892
1893 static void process_die (struct die_info *, struct dwarf2_cu *);
1894
1895 static const char *dwarf2_canonicalize_name (const char *, struct dwarf2_cu *,
1896                                              struct obstack *);
1897
1898 static const char *dwarf2_name (struct die_info *die, struct dwarf2_cu *);
1899
1900 static const char *dwarf2_full_name (const char *name,
1901                                      struct die_info *die,
1902                                      struct dwarf2_cu *cu);
1903
1904 static const char *dwarf2_physname (const char *name, struct die_info *die,
1905                                     struct dwarf2_cu *cu);
1906
1907 static struct die_info *dwarf2_extension (struct die_info *die,
1908                                           struct dwarf2_cu **);
1909
1910 static const char *dwarf_tag_name (unsigned int);
1911
1912 static const char *dwarf_attr_name (unsigned int);
1913
1914 static const char *dwarf_form_name (unsigned int);
1915
1916 static const char *dwarf_bool_name (unsigned int);
1917
1918 static const char *dwarf_type_encoding_name (unsigned int);
1919
1920 static struct die_info *sibling_die (struct die_info *);
1921
1922 static void dump_die_shallow (struct ui_file *, int indent, struct die_info *);
1923
1924 static void dump_die_for_error (struct die_info *);
1925
1926 static void dump_die_1 (struct ui_file *, int level, int max_level,
1927                         struct die_info *);
1928
1929 /*static*/ void dump_die (struct die_info *, int max_level);
1930
1931 static void store_in_ref_table (struct die_info *,
1932                                 struct dwarf2_cu *);
1933
1934 static sect_offset dwarf2_get_ref_die_offset (const struct attribute *);
1935
1936 static LONGEST dwarf2_get_attr_constant_value (const struct attribute *, int);
1937
1938 static struct die_info *follow_die_ref_or_sig (struct die_info *,
1939                                                const struct attribute *,
1940                                                struct dwarf2_cu **);
1941
1942 static struct die_info *follow_die_ref (struct die_info *,
1943                                         const struct attribute *,
1944                                         struct dwarf2_cu **);
1945
1946 static struct die_info *follow_die_sig (struct die_info *,
1947                                         const struct attribute *,
1948                                         struct dwarf2_cu **);
1949
1950 static struct type *get_signatured_type (struct die_info *, ULONGEST,
1951                                          struct dwarf2_cu *);
1952
1953 static struct type *get_DW_AT_signature_type (struct die_info *,
1954                                               const struct attribute *,
1955                                               struct dwarf2_cu *);
1956
1957 static void load_full_type_unit (struct dwarf2_per_cu_data *per_cu);
1958
1959 static void read_signatured_type (struct signatured_type *);
1960
1961 static int attr_to_dynamic_prop (const struct attribute *attr,
1962                                  struct die_info *die, struct dwarf2_cu *cu,
1963                                  struct dynamic_prop *prop);
1964
1965 /* memory allocation interface */
1966
1967 static struct dwarf_block *dwarf_alloc_block (struct dwarf2_cu *);
1968
1969 static struct die_info *dwarf_alloc_die (struct dwarf2_cu *, int);
1970
1971 static void dwarf_decode_macros (struct dwarf2_cu *, unsigned int, int);
1972
1973 static int attr_form_is_block (const struct attribute *);
1974
1975 static int attr_form_is_section_offset (const struct attribute *);
1976
1977 static int attr_form_is_constant (const struct attribute *);
1978
1979 static int attr_form_is_ref (const struct attribute *);
1980
1981 static void fill_in_loclist_baton (struct dwarf2_cu *cu,
1982                                    struct dwarf2_loclist_baton *baton,
1983                                    const struct attribute *attr);
1984
1985 static void dwarf2_symbol_mark_computed (const struct attribute *attr,
1986                                          struct symbol *sym,
1987                                          struct dwarf2_cu *cu,
1988                                          int is_block);
1989
1990 static const gdb_byte *skip_one_die (const struct die_reader_specs *reader,
1991                                      const gdb_byte *info_ptr,
1992                                      struct abbrev_info *abbrev);
1993
1994 static void free_stack_comp_unit (void *);
1995
1996 static hashval_t partial_die_hash (const void *item);
1997
1998 static int partial_die_eq (const void *item_lhs, const void *item_rhs);
1999
2000 static struct dwarf2_per_cu_data *dwarf2_find_containing_comp_unit
2001   (sect_offset sect_off, unsigned int offset_in_dwz, struct objfile *objfile);
2002
2003 static void init_one_comp_unit (struct dwarf2_cu *cu,
2004                                 struct dwarf2_per_cu_data *per_cu);
2005
2006 static void prepare_one_comp_unit (struct dwarf2_cu *cu,
2007                                    struct die_info *comp_unit_die,
2008                                    enum language pretend_language);
2009
2010 static void free_heap_comp_unit (void *);
2011
2012 static void free_cached_comp_units (void *);
2013
2014 static void age_cached_comp_units (void);
2015
2016 static void free_one_cached_comp_unit (struct dwarf2_per_cu_data *);
2017
2018 static struct type *set_die_type (struct die_info *, struct type *,
2019                                   struct dwarf2_cu *);
2020
2021 static void create_all_comp_units (struct objfile *);
2022
2023 static int create_all_type_units (struct objfile *);
2024
2025 static void load_full_comp_unit (struct dwarf2_per_cu_data *,
2026                                  enum language);
2027
2028 static void process_full_comp_unit (struct dwarf2_per_cu_data *,
2029                                     enum language);
2030
2031 static void process_full_type_unit (struct dwarf2_per_cu_data *,
2032                                     enum language);
2033
2034 static void dwarf2_add_dependence (struct dwarf2_cu *,
2035                                    struct dwarf2_per_cu_data *);
2036
2037 static void dwarf2_mark (struct dwarf2_cu *);
2038
2039 static void dwarf2_clear_marks (struct dwarf2_per_cu_data *);
2040
2041 static struct type *get_die_type_at_offset (sect_offset,
2042                                             struct dwarf2_per_cu_data *);
2043
2044 static struct type *get_die_type (struct die_info *die, struct dwarf2_cu *cu);
2045
2046 static void dwarf2_release_queue (void *dummy);
2047
2048 static void queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
2049                              enum language pretend_language);
2050
2051 static void process_queue (void);
2052
2053 /* The return type of find_file_and_directory.  Note, the enclosed
2054    string pointers are only valid while this object is valid.  */
2055
2056 struct file_and_directory
2057 {
2058   /* The filename.  This is never NULL.  */
2059   const char *name;
2060
2061   /* The compilation directory.  NULL if not known.  If we needed to
2062      compute a new string, this points to COMP_DIR_STORAGE, otherwise,
2063      points directly to the DW_AT_comp_dir string attribute owned by
2064      the obstack that owns the DIE.  */
2065   const char *comp_dir;
2066
2067   /* If we needed to build a new string for comp_dir, this is what
2068      owns the storage.  */
2069   std::string comp_dir_storage;
2070 };
2071
2072 static file_and_directory find_file_and_directory (struct die_info *die,
2073                                                    struct dwarf2_cu *cu);
2074
2075 static char *file_full_name (int file, struct line_header *lh,
2076                              const char *comp_dir);
2077
2078 /* Expected enum dwarf_unit_type for read_comp_unit_head.  */
2079 enum class rcuh_kind { COMPILE, TYPE };
2080
2081 static const gdb_byte *read_and_check_comp_unit_head
2082   (struct comp_unit_head *header,
2083    struct dwarf2_section_info *section,
2084    struct dwarf2_section_info *abbrev_section, const gdb_byte *info_ptr,
2085    rcuh_kind section_kind);
2086
2087 static void init_cutu_and_read_dies
2088   (struct dwarf2_per_cu_data *this_cu, struct abbrev_table *abbrev_table,
2089    int use_existing_cu, int keep,
2090    die_reader_func_ftype *die_reader_func, void *data);
2091
2092 static void init_cutu_and_read_dies_simple
2093   (struct dwarf2_per_cu_data *this_cu,
2094    die_reader_func_ftype *die_reader_func, void *data);
2095
2096 static htab_t allocate_signatured_type_table (struct objfile *objfile);
2097
2098 static htab_t allocate_dwo_unit_table (struct objfile *objfile);
2099
2100 static struct dwo_unit *lookup_dwo_unit_in_dwp
2101   (struct dwp_file *dwp_file, const char *comp_dir,
2102    ULONGEST signature, int is_debug_types);
2103
2104 static struct dwp_file *get_dwp_file (void);
2105
2106 static struct dwo_unit *lookup_dwo_comp_unit
2107   (struct dwarf2_per_cu_data *, const char *, const char *, ULONGEST);
2108
2109 static struct dwo_unit *lookup_dwo_type_unit
2110   (struct signatured_type *, const char *, const char *);
2111
2112 static void queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *);
2113
2114 static void free_dwo_file_cleanup (void *);
2115
2116 static void process_cu_includes (void);
2117
2118 static void check_producer (struct dwarf2_cu *cu);
2119
2120 static void free_line_header_voidp (void *arg);
2121 \f
2122 /* Various complaints about symbol reading that don't abort the process.  */
2123
2124 static void
2125 dwarf2_statement_list_fits_in_line_number_section_complaint (void)
2126 {
2127   complaint (&symfile_complaints,
2128              _("statement list doesn't fit in .debug_line section"));
2129 }
2130
2131 static void
2132 dwarf2_debug_line_missing_file_complaint (void)
2133 {
2134   complaint (&symfile_complaints,
2135              _(".debug_line section has line data without a file"));
2136 }
2137
2138 static void
2139 dwarf2_debug_line_missing_end_sequence_complaint (void)
2140 {
2141   complaint (&symfile_complaints,
2142              _(".debug_line section has line "
2143                "program sequence without an end"));
2144 }
2145
2146 static void
2147 dwarf2_complex_location_expr_complaint (void)
2148 {
2149   complaint (&symfile_complaints, _("location expression too complex"));
2150 }
2151
2152 static void
2153 dwarf2_const_value_length_mismatch_complaint (const char *arg1, int arg2,
2154                                               int arg3)
2155 {
2156   complaint (&symfile_complaints,
2157              _("const value length mismatch for '%s', got %d, expected %d"),
2158              arg1, arg2, arg3);
2159 }
2160
2161 static void
2162 dwarf2_section_buffer_overflow_complaint (struct dwarf2_section_info *section)
2163 {
2164   complaint (&symfile_complaints,
2165              _("debug info runs off end of %s section"
2166                " [in module %s]"),
2167              get_section_name (section),
2168              get_section_file_name (section));
2169 }
2170
2171 static void
2172 dwarf2_macro_malformed_definition_complaint (const char *arg1)
2173 {
2174   complaint (&symfile_complaints,
2175              _("macro debug info contains a "
2176                "malformed macro definition:\n`%s'"),
2177              arg1);
2178 }
2179
2180 static void
2181 dwarf2_invalid_attrib_class_complaint (const char *arg1, const char *arg2)
2182 {
2183   complaint (&symfile_complaints,
2184              _("invalid attribute class or form for '%s' in '%s'"),
2185              arg1, arg2);
2186 }
2187
2188 /* Hash function for line_header_hash.  */
2189
2190 static hashval_t
2191 line_header_hash (const struct line_header *ofs)
2192 {
2193   return to_underlying (ofs->sect_off) ^ ofs->offset_in_dwz;
2194 }
2195
2196 /* Hash function for htab_create_alloc_ex for line_header_hash.  */
2197
2198 static hashval_t
2199 line_header_hash_voidp (const void *item)
2200 {
2201   const struct line_header *ofs = (const struct line_header *) item;
2202
2203   return line_header_hash (ofs);
2204 }
2205
2206 /* Equality function for line_header_hash.  */
2207
2208 static int
2209 line_header_eq_voidp (const void *item_lhs, const void *item_rhs)
2210 {
2211   const struct line_header *ofs_lhs = (const struct line_header *) item_lhs;
2212   const struct line_header *ofs_rhs = (const struct line_header *) item_rhs;
2213
2214   return (ofs_lhs->sect_off == ofs_rhs->sect_off
2215           && ofs_lhs->offset_in_dwz == ofs_rhs->offset_in_dwz);
2216 }
2217
2218 \f
2219
2220 /* Read the given attribute value as an address, taking the attribute's
2221    form into account.  */
2222
2223 static CORE_ADDR
2224 attr_value_as_address (struct attribute *attr)
2225 {
2226   CORE_ADDR addr;
2227
2228   if (attr->form != DW_FORM_addr && attr->form != DW_FORM_GNU_addr_index)
2229     {
2230       /* Aside from a few clearly defined exceptions, attributes that
2231          contain an address must always be in DW_FORM_addr form.
2232          Unfortunately, some compilers happen to be violating this
2233          requirement by encoding addresses using other forms, such
2234          as DW_FORM_data4 for example.  For those broken compilers,
2235          we try to do our best, without any guarantee of success,
2236          to interpret the address correctly.  It would also be nice
2237          to generate a complaint, but that would require us to maintain
2238          a list of legitimate cases where a non-address form is allowed,
2239          as well as update callers to pass in at least the CU's DWARF
2240          version.  This is more overhead than what we're willing to
2241          expand for a pretty rare case.  */
2242       addr = DW_UNSND (attr);
2243     }
2244   else
2245     addr = DW_ADDR (attr);
2246
2247   return addr;
2248 }
2249
2250 /* The suffix for an index file.  */
2251 #define INDEX_SUFFIX ".gdb-index"
2252
2253 /* See declaration.  */
2254
2255 dwarf2_per_objfile::dwarf2_per_objfile (struct objfile *objfile_,
2256                                         const dwarf2_debug_sections *names)
2257   : objfile (objfile_)
2258 {
2259   if (names == NULL)
2260     names = &dwarf2_elf_names;
2261
2262   bfd *obfd = objfile->obfd;
2263
2264   for (asection *sec = obfd->sections; sec != NULL; sec = sec->next)
2265     locate_sections (obfd, sec, *names);
2266 }
2267
2268 dwarf2_per_objfile::~dwarf2_per_objfile ()
2269 {
2270   /* Cached DIE trees use xmalloc and the comp_unit_obstack.  */
2271   free_cached_comp_units ();
2272
2273   if (quick_file_names_table)
2274     htab_delete (quick_file_names_table);
2275
2276   if (line_header_hash)
2277     htab_delete (line_header_hash);
2278
2279   /* Everything else should be on the objfile obstack.  */
2280 }
2281
2282 /* See declaration.  */
2283
2284 void
2285 dwarf2_per_objfile::free_cached_comp_units ()
2286 {
2287   dwarf2_per_cu_data *per_cu = read_in_chain;
2288   dwarf2_per_cu_data **last_chain = &read_in_chain;
2289   while (per_cu != NULL)
2290     {
2291       dwarf2_per_cu_data *next_cu = per_cu->cu->read_in_chain;
2292
2293       free_heap_comp_unit (per_cu->cu);
2294       *last_chain = next_cu;
2295       per_cu = next_cu;
2296     }
2297 }
2298
2299 /* Try to locate the sections we need for DWARF 2 debugging
2300    information and return true if we have enough to do something.
2301    NAMES points to the dwarf2 section names, or is NULL if the standard
2302    ELF names are used.  */
2303
2304 int
2305 dwarf2_has_info (struct objfile *objfile,
2306                  const struct dwarf2_debug_sections *names)
2307 {
2308   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
2309                         objfile_data (objfile, dwarf2_objfile_data_key));
2310   if (!dwarf2_per_objfile)
2311     {
2312       /* Initialize per-objfile state.  */
2313       struct dwarf2_per_objfile *data
2314         = XOBNEW (&objfile->objfile_obstack, struct dwarf2_per_objfile);
2315
2316       dwarf2_per_objfile = new (data) struct dwarf2_per_objfile (objfile, names);
2317       set_objfile_data (objfile, dwarf2_objfile_data_key, dwarf2_per_objfile);
2318     }
2319   return (!dwarf2_per_objfile->info.is_virtual
2320           && dwarf2_per_objfile->info.s.section != NULL
2321           && !dwarf2_per_objfile->abbrev.is_virtual
2322           && dwarf2_per_objfile->abbrev.s.section != NULL);
2323 }
2324
2325 /* Return the containing section of virtual section SECTION.  */
2326
2327 static struct dwarf2_section_info *
2328 get_containing_section (const struct dwarf2_section_info *section)
2329 {
2330   gdb_assert (section->is_virtual);
2331   return section->s.containing_section;
2332 }
2333
2334 /* Return the bfd owner of SECTION.  */
2335
2336 static struct bfd *
2337 get_section_bfd_owner (const struct dwarf2_section_info *section)
2338 {
2339   if (section->is_virtual)
2340     {
2341       section = get_containing_section (section);
2342       gdb_assert (!section->is_virtual);
2343     }
2344   return section->s.section->owner;
2345 }
2346
2347 /* Return the bfd section of SECTION.
2348    Returns NULL if the section is not present.  */
2349
2350 static asection *
2351 get_section_bfd_section (const struct dwarf2_section_info *section)
2352 {
2353   if (section->is_virtual)
2354     {
2355       section = get_containing_section (section);
2356       gdb_assert (!section->is_virtual);
2357     }
2358   return section->s.section;
2359 }
2360
2361 /* Return the name of SECTION.  */
2362
2363 static const char *
2364 get_section_name (const struct dwarf2_section_info *section)
2365 {
2366   asection *sectp = get_section_bfd_section (section);
2367
2368   gdb_assert (sectp != NULL);
2369   return bfd_section_name (get_section_bfd_owner (section), sectp);
2370 }
2371
2372 /* Return the name of the file SECTION is in.  */
2373
2374 static const char *
2375 get_section_file_name (const struct dwarf2_section_info *section)
2376 {
2377   bfd *abfd = get_section_bfd_owner (section);
2378
2379   return bfd_get_filename (abfd);
2380 }
2381
2382 /* Return the id of SECTION.
2383    Returns 0 if SECTION doesn't exist.  */
2384
2385 static int
2386 get_section_id (const struct dwarf2_section_info *section)
2387 {
2388   asection *sectp = get_section_bfd_section (section);
2389
2390   if (sectp == NULL)
2391     return 0;
2392   return sectp->id;
2393 }
2394
2395 /* Return the flags of SECTION.
2396    SECTION (or containing section if this is a virtual section) must exist.  */
2397
2398 static int
2399 get_section_flags (const struct dwarf2_section_info *section)
2400 {
2401   asection *sectp = get_section_bfd_section (section);
2402
2403   gdb_assert (sectp != NULL);
2404   return bfd_get_section_flags (sectp->owner, sectp);
2405 }
2406
2407 /* When loading sections, we look either for uncompressed section or for
2408    compressed section names.  */
2409
2410 static int
2411 section_is_p (const char *section_name,
2412               const struct dwarf2_section_names *names)
2413 {
2414   if (names->normal != NULL
2415       && strcmp (section_name, names->normal) == 0)
2416     return 1;
2417   if (names->compressed != NULL
2418       && strcmp (section_name, names->compressed) == 0)
2419     return 1;
2420   return 0;
2421 }
2422
2423 /* See declaration.  */
2424
2425 void
2426 dwarf2_per_objfile::locate_sections (bfd *abfd, asection *sectp,
2427                                      const dwarf2_debug_sections &names)
2428 {
2429   flagword aflag = bfd_get_section_flags (abfd, sectp);
2430
2431   if ((aflag & SEC_HAS_CONTENTS) == 0)
2432     {
2433     }
2434   else if (section_is_p (sectp->name, &names.info))
2435     {
2436       this->info.s.section = sectp;
2437       this->info.size = bfd_get_section_size (sectp);
2438     }
2439   else if (section_is_p (sectp->name, &names.abbrev))
2440     {
2441       this->abbrev.s.section = sectp;
2442       this->abbrev.size = bfd_get_section_size (sectp);
2443     }
2444   else if (section_is_p (sectp->name, &names.line))
2445     {
2446       this->line.s.section = sectp;
2447       this->line.size = bfd_get_section_size (sectp);
2448     }
2449   else if (section_is_p (sectp->name, &names.loc))
2450     {
2451       this->loc.s.section = sectp;
2452       this->loc.size = bfd_get_section_size (sectp);
2453     }
2454   else if (section_is_p (sectp->name, &names.loclists))
2455     {
2456       this->loclists.s.section = sectp;
2457       this->loclists.size = bfd_get_section_size (sectp);
2458     }
2459   else if (section_is_p (sectp->name, &names.macinfo))
2460     {
2461       this->macinfo.s.section = sectp;
2462       this->macinfo.size = bfd_get_section_size (sectp);
2463     }
2464   else if (section_is_p (sectp->name, &names.macro))
2465     {
2466       this->macro.s.section = sectp;
2467       this->macro.size = bfd_get_section_size (sectp);
2468     }
2469   else if (section_is_p (sectp->name, &names.str))
2470     {
2471       this->str.s.section = sectp;
2472       this->str.size = bfd_get_section_size (sectp);
2473     }
2474   else if (section_is_p (sectp->name, &names.line_str))
2475     {
2476       this->line_str.s.section = sectp;
2477       this->line_str.size = bfd_get_section_size (sectp);
2478     }
2479   else if (section_is_p (sectp->name, &names.addr))
2480     {
2481       this->addr.s.section = sectp;
2482       this->addr.size = bfd_get_section_size (sectp);
2483     }
2484   else if (section_is_p (sectp->name, &names.frame))
2485     {
2486       this->frame.s.section = sectp;
2487       this->frame.size = bfd_get_section_size (sectp);
2488     }
2489   else if (section_is_p (sectp->name, &names.eh_frame))
2490     {
2491       this->eh_frame.s.section = sectp;
2492       this->eh_frame.size = bfd_get_section_size (sectp);
2493     }
2494   else if (section_is_p (sectp->name, &names.ranges))
2495     {
2496       this->ranges.s.section = sectp;
2497       this->ranges.size = bfd_get_section_size (sectp);
2498     }
2499   else if (section_is_p (sectp->name, &names.rnglists))
2500     {
2501       this->rnglists.s.section = sectp;
2502       this->rnglists.size = bfd_get_section_size (sectp);
2503     }
2504   else if (section_is_p (sectp->name, &names.types))
2505     {
2506       struct dwarf2_section_info type_section;
2507
2508       memset (&type_section, 0, sizeof (type_section));
2509       type_section.s.section = sectp;
2510       type_section.size = bfd_get_section_size (sectp);
2511
2512       VEC_safe_push (dwarf2_section_info_def, this->types,
2513                      &type_section);
2514     }
2515   else if (section_is_p (sectp->name, &names.gdb_index))
2516     {
2517       this->gdb_index.s.section = sectp;
2518       this->gdb_index.size = bfd_get_section_size (sectp);
2519     }
2520
2521   if ((bfd_get_section_flags (abfd, sectp) & (SEC_LOAD | SEC_ALLOC))
2522       && bfd_section_vma (abfd, sectp) == 0)
2523     this->has_section_at_zero = true;
2524 }
2525
2526 /* A helper function that decides whether a section is empty,
2527    or not present.  */
2528
2529 static int
2530 dwarf2_section_empty_p (const struct dwarf2_section_info *section)
2531 {
2532   if (section->is_virtual)
2533     return section->size == 0;
2534   return section->s.section == NULL || section->size == 0;
2535 }
2536
2537 /* Read the contents of the section INFO.
2538    OBJFILE is the main object file, but not necessarily the file where
2539    the section comes from.  E.g., for DWO files the bfd of INFO is the bfd
2540    of the DWO file.
2541    If the section is compressed, uncompress it before returning.  */
2542
2543 static void
2544 dwarf2_read_section (struct objfile *objfile, struct dwarf2_section_info *info)
2545 {
2546   asection *sectp;
2547   bfd *abfd;
2548   gdb_byte *buf, *retbuf;
2549
2550   if (info->readin)
2551     return;
2552   info->buffer = NULL;
2553   info->readin = 1;
2554
2555   if (dwarf2_section_empty_p (info))
2556     return;
2557
2558   sectp = get_section_bfd_section (info);
2559
2560   /* If this is a virtual section we need to read in the real one first.  */
2561   if (info->is_virtual)
2562     {
2563       struct dwarf2_section_info *containing_section =
2564         get_containing_section (info);
2565
2566       gdb_assert (sectp != NULL);
2567       if ((sectp->flags & SEC_RELOC) != 0)
2568         {
2569           error (_("Dwarf Error: DWP format V2 with relocations is not"
2570                    " supported in section %s [in module %s]"),
2571                  get_section_name (info), get_section_file_name (info));
2572         }
2573       dwarf2_read_section (objfile, containing_section);
2574       /* Other code should have already caught virtual sections that don't
2575          fit.  */
2576       gdb_assert (info->virtual_offset + info->size
2577                   <= containing_section->size);
2578       /* If the real section is empty or there was a problem reading the
2579          section we shouldn't get here.  */
2580       gdb_assert (containing_section->buffer != NULL);
2581       info->buffer = containing_section->buffer + info->virtual_offset;
2582       return;
2583     }
2584
2585   /* If the section has relocations, we must read it ourselves.
2586      Otherwise we attach it to the BFD.  */
2587   if ((sectp->flags & SEC_RELOC) == 0)
2588     {
2589       info->buffer = gdb_bfd_map_section (sectp, &info->size);
2590       return;
2591     }
2592
2593   buf = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, info->size);
2594   info->buffer = buf;
2595
2596   /* When debugging .o files, we may need to apply relocations; see
2597      http://sourceware.org/ml/gdb-patches/2002-04/msg00136.html .
2598      We never compress sections in .o files, so we only need to
2599      try this when the section is not compressed.  */
2600   retbuf = symfile_relocate_debug_section (objfile, sectp, buf);
2601   if (retbuf != NULL)
2602     {
2603       info->buffer = retbuf;
2604       return;
2605     }
2606
2607   abfd = get_section_bfd_owner (info);
2608   gdb_assert (abfd != NULL);
2609
2610   if (bfd_seek (abfd, sectp->filepos, SEEK_SET) != 0
2611       || bfd_bread (buf, info->size, abfd) != info->size)
2612     {
2613       error (_("Dwarf Error: Can't read DWARF data"
2614                " in section %s [in module %s]"),
2615              bfd_section_name (abfd, sectp), bfd_get_filename (abfd));
2616     }
2617 }
2618
2619 /* A helper function that returns the size of a section in a safe way.
2620    If you are positive that the section has been read before using the
2621    size, then it is safe to refer to the dwarf2_section_info object's
2622    "size" field directly.  In other cases, you must call this
2623    function, because for compressed sections the size field is not set
2624    correctly until the section has been read.  */
2625
2626 static bfd_size_type
2627 dwarf2_section_size (struct objfile *objfile,
2628                      struct dwarf2_section_info *info)
2629 {
2630   if (!info->readin)
2631     dwarf2_read_section (objfile, info);
2632   return info->size;
2633 }
2634
2635 /* Fill in SECTP, BUFP and SIZEP with section info, given OBJFILE and
2636    SECTION_NAME.  */
2637
2638 void
2639 dwarf2_get_section_info (struct objfile *objfile,
2640                          enum dwarf2_section_enum sect,
2641                          asection **sectp, const gdb_byte **bufp,
2642                          bfd_size_type *sizep)
2643 {
2644   struct dwarf2_per_objfile *data
2645     = (struct dwarf2_per_objfile *) objfile_data (objfile,
2646                                                   dwarf2_objfile_data_key);
2647   struct dwarf2_section_info *info;
2648
2649   /* We may see an objfile without any DWARF, in which case we just
2650      return nothing.  */
2651   if (data == NULL)
2652     {
2653       *sectp = NULL;
2654       *bufp = NULL;
2655       *sizep = 0;
2656       return;
2657     }
2658   switch (sect)
2659     {
2660     case DWARF2_DEBUG_FRAME:
2661       info = &data->frame;
2662       break;
2663     case DWARF2_EH_FRAME:
2664       info = &data->eh_frame;
2665       break;
2666     default:
2667       gdb_assert_not_reached ("unexpected section");
2668     }
2669
2670   dwarf2_read_section (objfile, info);
2671
2672   *sectp = get_section_bfd_section (info);
2673   *bufp = info->buffer;
2674   *sizep = info->size;
2675 }
2676
2677 /* A helper function to find the sections for a .dwz file.  */
2678
2679 static void
2680 locate_dwz_sections (bfd *abfd, asection *sectp, void *arg)
2681 {
2682   struct dwz_file *dwz_file = (struct dwz_file *) arg;
2683
2684   /* Note that we only support the standard ELF names, because .dwz
2685      is ELF-only (at the time of writing).  */
2686   if (section_is_p (sectp->name, &dwarf2_elf_names.abbrev))
2687     {
2688       dwz_file->abbrev.s.section = sectp;
2689       dwz_file->abbrev.size = bfd_get_section_size (sectp);
2690     }
2691   else if (section_is_p (sectp->name, &dwarf2_elf_names.info))
2692     {
2693       dwz_file->info.s.section = sectp;
2694       dwz_file->info.size = bfd_get_section_size (sectp);
2695     }
2696   else if (section_is_p (sectp->name, &dwarf2_elf_names.str))
2697     {
2698       dwz_file->str.s.section = sectp;
2699       dwz_file->str.size = bfd_get_section_size (sectp);
2700     }
2701   else if (section_is_p (sectp->name, &dwarf2_elf_names.line))
2702     {
2703       dwz_file->line.s.section = sectp;
2704       dwz_file->line.size = bfd_get_section_size (sectp);
2705     }
2706   else if (section_is_p (sectp->name, &dwarf2_elf_names.macro))
2707     {
2708       dwz_file->macro.s.section = sectp;
2709       dwz_file->macro.size = bfd_get_section_size (sectp);
2710     }
2711   else if (section_is_p (sectp->name, &dwarf2_elf_names.gdb_index))
2712     {
2713       dwz_file->gdb_index.s.section = sectp;
2714       dwz_file->gdb_index.size = bfd_get_section_size (sectp);
2715     }
2716 }
2717
2718 /* Open the separate '.dwz' debug file, if needed.  Return NULL if
2719    there is no .gnu_debugaltlink section in the file.  Error if there
2720    is such a section but the file cannot be found.  */
2721
2722 static struct dwz_file *
2723 dwarf2_get_dwz_file (void)
2724 {
2725   const char *filename;
2726   struct dwz_file *result;
2727   bfd_size_type buildid_len_arg;
2728   size_t buildid_len;
2729   bfd_byte *buildid;
2730
2731   if (dwarf2_per_objfile->dwz_file != NULL)
2732     return dwarf2_per_objfile->dwz_file;
2733
2734   bfd_set_error (bfd_error_no_error);
2735   gdb::unique_xmalloc_ptr<char> data
2736     (bfd_get_alt_debug_link_info (dwarf2_per_objfile->objfile->obfd,
2737                                   &buildid_len_arg, &buildid));
2738   if (data == NULL)
2739     {
2740       if (bfd_get_error () == bfd_error_no_error)
2741         return NULL;
2742       error (_("could not read '.gnu_debugaltlink' section: %s"),
2743              bfd_errmsg (bfd_get_error ()));
2744     }
2745
2746   gdb::unique_xmalloc_ptr<bfd_byte> buildid_holder (buildid);
2747
2748   buildid_len = (size_t) buildid_len_arg;
2749
2750   filename = data.get ();
2751
2752   std::string abs_storage;
2753   if (!IS_ABSOLUTE_PATH (filename))
2754     {
2755       gdb::unique_xmalloc_ptr<char> abs
2756         = gdb_realpath (objfile_name (dwarf2_per_objfile->objfile));
2757
2758       abs_storage = ldirname (abs.get ()) + SLASH_STRING + filename;
2759       filename = abs_storage.c_str ();
2760     }
2761
2762   /* First try the file name given in the section.  If that doesn't
2763      work, try to use the build-id instead.  */
2764   gdb_bfd_ref_ptr dwz_bfd (gdb_bfd_open (filename, gnutarget, -1));
2765   if (dwz_bfd != NULL)
2766     {
2767       if (!build_id_verify (dwz_bfd.get (), buildid_len, buildid))
2768         dwz_bfd.release ();
2769     }
2770
2771   if (dwz_bfd == NULL)
2772     dwz_bfd = build_id_to_debug_bfd (buildid_len, buildid);
2773
2774   if (dwz_bfd == NULL)
2775     error (_("could not find '.gnu_debugaltlink' file for %s"),
2776            objfile_name (dwarf2_per_objfile->objfile));
2777
2778   result = OBSTACK_ZALLOC (&dwarf2_per_objfile->objfile->objfile_obstack,
2779                            struct dwz_file);
2780   result->dwz_bfd = dwz_bfd.release ();
2781
2782   bfd_map_over_sections (result->dwz_bfd, locate_dwz_sections, result);
2783
2784   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, result->dwz_bfd);
2785   dwarf2_per_objfile->dwz_file = result;
2786   return result;
2787 }
2788 \f
2789 /* DWARF quick_symbols_functions support.  */
2790
2791 /* TUs can share .debug_line entries, and there can be a lot more TUs than
2792    unique line tables, so we maintain a separate table of all .debug_line
2793    derived entries to support the sharing.
2794    All the quick functions need is the list of file names.  We discard the
2795    line_header when we're done and don't need to record it here.  */
2796 struct quick_file_names
2797 {
2798   /* The data used to construct the hash key.  */
2799   struct stmt_list_hash hash;
2800
2801   /* The number of entries in file_names, real_names.  */
2802   unsigned int num_file_names;
2803
2804   /* The file names from the line table, after being run through
2805      file_full_name.  */
2806   const char **file_names;
2807
2808   /* The file names from the line table after being run through
2809      gdb_realpath.  These are computed lazily.  */
2810   const char **real_names;
2811 };
2812
2813 /* When using the index (and thus not using psymtabs), each CU has an
2814    object of this type.  This is used to hold information needed by
2815    the various "quick" methods.  */
2816 struct dwarf2_per_cu_quick_data
2817 {
2818   /* The file table.  This can be NULL if there was no file table
2819      or it's currently not read in.
2820      NOTE: This points into dwarf2_per_objfile->quick_file_names_table.  */
2821   struct quick_file_names *file_names;
2822
2823   /* The corresponding symbol table.  This is NULL if symbols for this
2824      CU have not yet been read.  */
2825   struct compunit_symtab *compunit_symtab;
2826
2827   /* A temporary mark bit used when iterating over all CUs in
2828      expand_symtabs_matching.  */
2829   unsigned int mark : 1;
2830
2831   /* True if we've tried to read the file table and found there isn't one.
2832      There will be no point in trying to read it again next time.  */
2833   unsigned int no_file_data : 1;
2834 };
2835
2836 /* Utility hash function for a stmt_list_hash.  */
2837
2838 static hashval_t
2839 hash_stmt_list_entry (const struct stmt_list_hash *stmt_list_hash)
2840 {
2841   hashval_t v = 0;
2842
2843   if (stmt_list_hash->dwo_unit != NULL)
2844     v += (uintptr_t) stmt_list_hash->dwo_unit->dwo_file;
2845   v += to_underlying (stmt_list_hash->line_sect_off);
2846   return v;
2847 }
2848
2849 /* Utility equality function for a stmt_list_hash.  */
2850
2851 static int
2852 eq_stmt_list_entry (const struct stmt_list_hash *lhs,
2853                     const struct stmt_list_hash *rhs)
2854 {
2855   if ((lhs->dwo_unit != NULL) != (rhs->dwo_unit != NULL))
2856     return 0;
2857   if (lhs->dwo_unit != NULL
2858       && lhs->dwo_unit->dwo_file != rhs->dwo_unit->dwo_file)
2859     return 0;
2860
2861   return lhs->line_sect_off == rhs->line_sect_off;
2862 }
2863
2864 /* Hash function for a quick_file_names.  */
2865
2866 static hashval_t
2867 hash_file_name_entry (const void *e)
2868 {
2869   const struct quick_file_names *file_data
2870     = (const struct quick_file_names *) e;
2871
2872   return hash_stmt_list_entry (&file_data->hash);
2873 }
2874
2875 /* Equality function for a quick_file_names.  */
2876
2877 static int
2878 eq_file_name_entry (const void *a, const void *b)
2879 {
2880   const struct quick_file_names *ea = (const struct quick_file_names *) a;
2881   const struct quick_file_names *eb = (const struct quick_file_names *) b;
2882
2883   return eq_stmt_list_entry (&ea->hash, &eb->hash);
2884 }
2885
2886 /* Delete function for a quick_file_names.  */
2887
2888 static void
2889 delete_file_name_entry (void *e)
2890 {
2891   struct quick_file_names *file_data = (struct quick_file_names *) e;
2892   int i;
2893
2894   for (i = 0; i < file_data->num_file_names; ++i)
2895     {
2896       xfree ((void*) file_data->file_names[i]);
2897       if (file_data->real_names)
2898         xfree ((void*) file_data->real_names[i]);
2899     }
2900
2901   /* The space for the struct itself lives on objfile_obstack,
2902      so we don't free it here.  */
2903 }
2904
2905 /* Create a quick_file_names hash table.  */
2906
2907 static htab_t
2908 create_quick_file_names_table (unsigned int nr_initial_entries)
2909 {
2910   return htab_create_alloc (nr_initial_entries,
2911                             hash_file_name_entry, eq_file_name_entry,
2912                             delete_file_name_entry, xcalloc, xfree);
2913 }
2914
2915 /* Read in PER_CU->CU.  This function is unrelated to symtabs, symtab would
2916    have to be created afterwards.  You should call age_cached_comp_units after
2917    processing PER_CU->CU.  dw2_setup must have been already called.  */
2918
2919 static void
2920 load_cu (struct dwarf2_per_cu_data *per_cu)
2921 {
2922   if (per_cu->is_debug_types)
2923     load_full_type_unit (per_cu);
2924   else
2925     load_full_comp_unit (per_cu, language_minimal);
2926
2927   if (per_cu->cu == NULL)
2928     return;  /* Dummy CU.  */
2929
2930   dwarf2_find_base_address (per_cu->cu->dies, per_cu->cu);
2931 }
2932
2933 /* Read in the symbols for PER_CU.  */
2934
2935 static void
2936 dw2_do_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2937 {
2938   struct cleanup *back_to;
2939
2940   /* Skip type_unit_groups, reading the type units they contain
2941      is handled elsewhere.  */
2942   if (IS_TYPE_UNIT_GROUP (per_cu))
2943     return;
2944
2945   back_to = make_cleanup (dwarf2_release_queue, NULL);
2946
2947   if (dwarf2_per_objfile->using_index
2948       ? per_cu->v.quick->compunit_symtab == NULL
2949       : (per_cu->v.psymtab == NULL || !per_cu->v.psymtab->readin))
2950     {
2951       queue_comp_unit (per_cu, language_minimal);
2952       load_cu (per_cu);
2953
2954       /* If we just loaded a CU from a DWO, and we're working with an index
2955          that may badly handle TUs, load all the TUs in that DWO as well.
2956          http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
2957       if (!per_cu->is_debug_types
2958           && per_cu->cu != NULL
2959           && per_cu->cu->dwo_unit != NULL
2960           && dwarf2_per_objfile->index_table != NULL
2961           && dwarf2_per_objfile->index_table->version <= 7
2962           /* DWP files aren't supported yet.  */
2963           && get_dwp_file () == NULL)
2964         queue_and_load_all_dwo_tus (per_cu);
2965     }
2966
2967   process_queue ();
2968
2969   /* Age the cache, releasing compilation units that have not
2970      been used recently.  */
2971   age_cached_comp_units ();
2972
2973   do_cleanups (back_to);
2974 }
2975
2976 /* Ensure that the symbols for PER_CU have been read in.  OBJFILE is
2977    the objfile from which this CU came.  Returns the resulting symbol
2978    table.  */
2979
2980 static struct compunit_symtab *
2981 dw2_instantiate_symtab (struct dwarf2_per_cu_data *per_cu)
2982 {
2983   gdb_assert (dwarf2_per_objfile->using_index);
2984   if (!per_cu->v.quick->compunit_symtab)
2985     {
2986       struct cleanup *back_to = make_cleanup (free_cached_comp_units, NULL);
2987       scoped_restore decrementer = increment_reading_symtab ();
2988       dw2_do_instantiate_symtab (per_cu);
2989       process_cu_includes ();
2990       do_cleanups (back_to);
2991     }
2992
2993   return per_cu->v.quick->compunit_symtab;
2994 }
2995
2996 /* Return the CU/TU given its index.
2997
2998    This is intended for loops like:
2999
3000    for (i = 0; i < (dwarf2_per_objfile->n_comp_units
3001                     + dwarf2_per_objfile->n_type_units); ++i)
3002      {
3003        struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3004
3005        ...;
3006      }
3007 */
3008
3009 static struct dwarf2_per_cu_data *
3010 dw2_get_cutu (int index)
3011 {
3012   if (index >= dwarf2_per_objfile->n_comp_units)
3013     {
3014       index -= dwarf2_per_objfile->n_comp_units;
3015       gdb_assert (index < dwarf2_per_objfile->n_type_units);
3016       return &dwarf2_per_objfile->all_type_units[index]->per_cu;
3017     }
3018
3019   return dwarf2_per_objfile->all_comp_units[index];
3020 }
3021
3022 /* Return the CU given its index.
3023    This differs from dw2_get_cutu in that it's for when you know INDEX
3024    refers to a CU.  */
3025
3026 static struct dwarf2_per_cu_data *
3027 dw2_get_cu (int index)
3028 {
3029   gdb_assert (index >= 0 && index < dwarf2_per_objfile->n_comp_units);
3030
3031   return dwarf2_per_objfile->all_comp_units[index];
3032 }
3033
3034 /* A helper for create_cus_from_index that handles a given list of
3035    CUs.  */
3036
3037 static void
3038 create_cus_from_index_list (struct objfile *objfile,
3039                             const gdb_byte *cu_list, offset_type n_elements,
3040                             struct dwarf2_section_info *section,
3041                             int is_dwz,
3042                             int base_offset)
3043 {
3044   offset_type i;
3045
3046   for (i = 0; i < n_elements; i += 2)
3047     {
3048       gdb_static_assert (sizeof (ULONGEST) >= 8);
3049
3050       sect_offset sect_off
3051         = (sect_offset) extract_unsigned_integer (cu_list, 8, BFD_ENDIAN_LITTLE);
3052       ULONGEST length = extract_unsigned_integer (cu_list + 8, 8, BFD_ENDIAN_LITTLE);
3053       cu_list += 2 * 8;
3054
3055       dwarf2_per_cu_data *the_cu
3056         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3057                           struct dwarf2_per_cu_data);
3058       the_cu->sect_off = sect_off;
3059       the_cu->length = length;
3060       the_cu->objfile = objfile;
3061       the_cu->section = section;
3062       the_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3063                                         struct dwarf2_per_cu_quick_data);
3064       the_cu->is_dwz = is_dwz;
3065       dwarf2_per_objfile->all_comp_units[base_offset + i / 2] = the_cu;
3066     }
3067 }
3068
3069 /* Read the CU list from the mapped index, and use it to create all
3070    the CU objects for this objfile.  */
3071
3072 static void
3073 create_cus_from_index (struct objfile *objfile,
3074                        const gdb_byte *cu_list, offset_type cu_list_elements,
3075                        const gdb_byte *dwz_list, offset_type dwz_elements)
3076 {
3077   struct dwz_file *dwz;
3078
3079   dwarf2_per_objfile->n_comp_units = (cu_list_elements + dwz_elements) / 2;
3080   dwarf2_per_objfile->all_comp_units =
3081     XOBNEWVEC (&objfile->objfile_obstack, struct dwarf2_per_cu_data *,
3082                dwarf2_per_objfile->n_comp_units);
3083
3084   create_cus_from_index_list (objfile, cu_list, cu_list_elements,
3085                               &dwarf2_per_objfile->info, 0, 0);
3086
3087   if (dwz_elements == 0)
3088     return;
3089
3090   dwz = dwarf2_get_dwz_file ();
3091   create_cus_from_index_list (objfile, dwz_list, dwz_elements, &dwz->info, 1,
3092                               cu_list_elements / 2);
3093 }
3094
3095 /* Create the signatured type hash table from the index.  */
3096
3097 static void
3098 create_signatured_type_table_from_index (struct objfile *objfile,
3099                                          struct dwarf2_section_info *section,
3100                                          const gdb_byte *bytes,
3101                                          offset_type elements)
3102 {
3103   offset_type i;
3104   htab_t sig_types_hash;
3105
3106   dwarf2_per_objfile->n_type_units
3107     = dwarf2_per_objfile->n_allocated_type_units
3108     = elements / 3;
3109   dwarf2_per_objfile->all_type_units =
3110     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
3111
3112   sig_types_hash = allocate_signatured_type_table (objfile);
3113
3114   for (i = 0; i < elements; i += 3)
3115     {
3116       struct signatured_type *sig_type;
3117       ULONGEST signature;
3118       void **slot;
3119       cu_offset type_offset_in_tu;
3120
3121       gdb_static_assert (sizeof (ULONGEST) >= 8);
3122       sect_offset sect_off
3123         = (sect_offset) extract_unsigned_integer (bytes, 8, BFD_ENDIAN_LITTLE);
3124       type_offset_in_tu
3125         = (cu_offset) extract_unsigned_integer (bytes + 8, 8,
3126                                                 BFD_ENDIAN_LITTLE);
3127       signature = extract_unsigned_integer (bytes + 16, 8, BFD_ENDIAN_LITTLE);
3128       bytes += 3 * 8;
3129
3130       sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3131                                  struct signatured_type);
3132       sig_type->signature = signature;
3133       sig_type->type_offset_in_tu = type_offset_in_tu;
3134       sig_type->per_cu.is_debug_types = 1;
3135       sig_type->per_cu.section = section;
3136       sig_type->per_cu.sect_off = sect_off;
3137       sig_type->per_cu.objfile = objfile;
3138       sig_type->per_cu.v.quick
3139         = OBSTACK_ZALLOC (&objfile->objfile_obstack,
3140                           struct dwarf2_per_cu_quick_data);
3141
3142       slot = htab_find_slot (sig_types_hash, sig_type, INSERT);
3143       *slot = sig_type;
3144
3145       dwarf2_per_objfile->all_type_units[i / 3] = sig_type;
3146     }
3147
3148   dwarf2_per_objfile->signatured_types = sig_types_hash;
3149 }
3150
3151 /* Read the address map data from the mapped index, and use it to
3152    populate the objfile's psymtabs_addrmap.  */
3153
3154 static void
3155 create_addrmap_from_index (struct objfile *objfile, struct mapped_index *index)
3156 {
3157   struct gdbarch *gdbarch = get_objfile_arch (objfile);
3158   const gdb_byte *iter, *end;
3159   struct addrmap *mutable_map;
3160   CORE_ADDR baseaddr;
3161
3162   auto_obstack temp_obstack;
3163
3164   mutable_map = addrmap_create_mutable (&temp_obstack);
3165
3166   iter = index->address_table;
3167   end = iter + index->address_table_size;
3168
3169   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
3170
3171   while (iter < end)
3172     {
3173       ULONGEST hi, lo, cu_index;
3174       lo = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3175       iter += 8;
3176       hi = extract_unsigned_integer (iter, 8, BFD_ENDIAN_LITTLE);
3177       iter += 8;
3178       cu_index = extract_unsigned_integer (iter, 4, BFD_ENDIAN_LITTLE);
3179       iter += 4;
3180
3181       if (lo > hi)
3182         {
3183           complaint (&symfile_complaints,
3184                      _(".gdb_index address table has invalid range (%s - %s)"),
3185                      hex_string (lo), hex_string (hi));
3186           continue;
3187         }
3188
3189       if (cu_index >= dwarf2_per_objfile->n_comp_units)
3190         {
3191           complaint (&symfile_complaints,
3192                      _(".gdb_index address table has invalid CU number %u"),
3193                      (unsigned) cu_index);
3194           continue;
3195         }
3196
3197       lo = gdbarch_adjust_dwarf2_addr (gdbarch, lo + baseaddr);
3198       hi = gdbarch_adjust_dwarf2_addr (gdbarch, hi + baseaddr);
3199       addrmap_set_empty (mutable_map, lo, hi - 1, dw2_get_cutu (cu_index));
3200     }
3201
3202   objfile->psymtabs_addrmap = addrmap_create_fixed (mutable_map,
3203                                                     &objfile->objfile_obstack);
3204 }
3205
3206 /* The hash function for strings in the mapped index.  This is the same as
3207    SYMBOL_HASH_NEXT, but we keep a separate copy to maintain control over the
3208    implementation.  This is necessary because the hash function is tied to the
3209    format of the mapped index file.  The hash values do not have to match with
3210    SYMBOL_HASH_NEXT.
3211    
3212    Use INT_MAX for INDEX_VERSION if you generate the current index format.  */
3213
3214 static hashval_t
3215 mapped_index_string_hash (int index_version, const void *p)
3216 {
3217   const unsigned char *str = (const unsigned char *) p;
3218   hashval_t r = 0;
3219   unsigned char c;
3220
3221   while ((c = *str++) != 0)
3222     {
3223       if (index_version >= 5)
3224         c = tolower (c);
3225       r = r * 67 + c - 113;
3226     }
3227
3228   return r;
3229 }
3230
3231 /* Find a slot in the mapped index INDEX for the object named NAME.
3232    If NAME is found, set *VEC_OUT to point to the CU vector in the
3233    constant pool and return true.  If NAME cannot be found, return
3234    false.  */
3235
3236 static bool
3237 find_slot_in_mapped_hash (struct mapped_index *index, const char *name,
3238                           offset_type **vec_out)
3239 {
3240   offset_type hash;
3241   offset_type slot, step;
3242   int (*cmp) (const char *, const char *);
3243
3244   gdb::unique_xmalloc_ptr<char> without_params;
3245   if (current_language->la_language == language_cplus
3246       || current_language->la_language == language_fortran
3247       || current_language->la_language == language_d)
3248     {
3249       /* NAME is already canonical.  Drop any qualifiers as .gdb_index does
3250          not contain any.  */
3251
3252       if (strchr (name, '(') != NULL)
3253         {
3254           without_params = cp_remove_params (name);
3255
3256           if (without_params != NULL)
3257             name = without_params.get ();
3258         }
3259     }
3260
3261   /* Index version 4 did not support case insensitive searches.  But the
3262      indices for case insensitive languages are built in lowercase, therefore
3263      simulate our NAME being searched is also lowercased.  */
3264   hash = mapped_index_string_hash ((index->version == 4
3265                                     && case_sensitivity == case_sensitive_off
3266                                     ? 5 : index->version),
3267                                    name);
3268
3269   slot = hash & (index->symbol_table_slots - 1);
3270   step = ((hash * 17) & (index->symbol_table_slots - 1)) | 1;
3271   cmp = (case_sensitivity == case_sensitive_on ? strcmp : strcasecmp);
3272
3273   for (;;)
3274     {
3275       /* Convert a slot number to an offset into the table.  */
3276       offset_type i = 2 * slot;
3277       const char *str;
3278       if (index->symbol_table[i] == 0 && index->symbol_table[i + 1] == 0)
3279         return false;
3280
3281       str = index->constant_pool + MAYBE_SWAP (index->symbol_table[i]);
3282       if (!cmp (name, str))
3283         {
3284           *vec_out = (offset_type *) (index->constant_pool
3285                                       + MAYBE_SWAP (index->symbol_table[i + 1]));
3286           return true;
3287         }
3288
3289       slot = (slot + step) & (index->symbol_table_slots - 1);
3290     }
3291 }
3292
3293 /* A helper function that reads the .gdb_index from SECTION and fills
3294    in MAP.  FILENAME is the name of the file containing the section;
3295    it is used for error reporting.  DEPRECATED_OK is nonzero if it is
3296    ok to use deprecated sections.
3297
3298    CU_LIST, CU_LIST_ELEMENTS, TYPES_LIST, and TYPES_LIST_ELEMENTS are
3299    out parameters that are filled in with information about the CU and
3300    TU lists in the section.
3301
3302    Returns 1 if all went well, 0 otherwise.  */
3303
3304 static int
3305 read_index_from_section (struct objfile *objfile,
3306                          const char *filename,
3307                          int deprecated_ok,
3308                          struct dwarf2_section_info *section,
3309                          struct mapped_index *map,
3310                          const gdb_byte **cu_list,
3311                          offset_type *cu_list_elements,
3312                          const gdb_byte **types_list,
3313                          offset_type *types_list_elements)
3314 {
3315   const gdb_byte *addr;
3316   offset_type version;
3317   offset_type *metadata;
3318   int i;
3319
3320   if (dwarf2_section_empty_p (section))
3321     return 0;
3322
3323   /* Older elfutils strip versions could keep the section in the main
3324      executable while splitting it for the separate debug info file.  */
3325   if ((get_section_flags (section) & SEC_HAS_CONTENTS) == 0)
3326     return 0;
3327
3328   dwarf2_read_section (objfile, section);
3329
3330   addr = section->buffer;
3331   /* Version check.  */
3332   version = MAYBE_SWAP (*(offset_type *) addr);
3333   /* Versions earlier than 3 emitted every copy of a psymbol.  This
3334      causes the index to behave very poorly for certain requests.  Version 3
3335      contained incomplete addrmap.  So, it seems better to just ignore such
3336      indices.  */
3337   if (version < 4)
3338     {
3339       static int warning_printed = 0;
3340       if (!warning_printed)
3341         {
3342           warning (_("Skipping obsolete .gdb_index section in %s."),
3343                    filename);
3344           warning_printed = 1;
3345         }
3346       return 0;
3347     }
3348   /* Index version 4 uses a different hash function than index version
3349      5 and later.
3350
3351      Versions earlier than 6 did not emit psymbols for inlined
3352      functions.  Using these files will cause GDB not to be able to
3353      set breakpoints on inlined functions by name, so we ignore these
3354      indices unless the user has done
3355      "set use-deprecated-index-sections on".  */
3356   if (version < 6 && !deprecated_ok)
3357     {
3358       static int warning_printed = 0;
3359       if (!warning_printed)
3360         {
3361           warning (_("\
3362 Skipping deprecated .gdb_index section in %s.\n\
3363 Do \"set use-deprecated-index-sections on\" before the file is read\n\
3364 to use the section anyway."),
3365                    filename);
3366           warning_printed = 1;
3367         }
3368       return 0;
3369     }
3370   /* Version 7 indices generated by gold refer to the CU for a symbol instead
3371      of the TU (for symbols coming from TUs),
3372      http://sourceware.org/bugzilla/show_bug.cgi?id=15021.
3373      Plus gold-generated indices can have duplicate entries for global symbols,
3374      http://sourceware.org/bugzilla/show_bug.cgi?id=15646.
3375      These are just performance bugs, and we can't distinguish gdb-generated
3376      indices from gold-generated ones, so issue no warning here.  */
3377
3378   /* Indexes with higher version than the one supported by GDB may be no
3379      longer backward compatible.  */
3380   if (version > 8)
3381     return 0;
3382
3383   map->version = version;
3384   map->total_size = section->size;
3385
3386   metadata = (offset_type *) (addr + sizeof (offset_type));
3387
3388   i = 0;
3389   *cu_list = addr + MAYBE_SWAP (metadata[i]);
3390   *cu_list_elements = ((MAYBE_SWAP (metadata[i + 1]) - MAYBE_SWAP (metadata[i]))
3391                        / 8);
3392   ++i;
3393
3394   *types_list = addr + MAYBE_SWAP (metadata[i]);
3395   *types_list_elements = ((MAYBE_SWAP (metadata[i + 1])
3396                            - MAYBE_SWAP (metadata[i]))
3397                           / 8);
3398   ++i;
3399
3400   map->address_table = addr + MAYBE_SWAP (metadata[i]);
3401   map->address_table_size = (MAYBE_SWAP (metadata[i + 1])
3402                              - MAYBE_SWAP (metadata[i]));
3403   ++i;
3404
3405   map->symbol_table = (offset_type *) (addr + MAYBE_SWAP (metadata[i]));
3406   map->symbol_table_slots = ((MAYBE_SWAP (metadata[i + 1])
3407                               - MAYBE_SWAP (metadata[i]))
3408                              / (2 * sizeof (offset_type)));
3409   ++i;
3410
3411   map->constant_pool = (char *) (addr + MAYBE_SWAP (metadata[i]));
3412
3413   return 1;
3414 }
3415
3416
3417 /* Read the index file.  If everything went ok, initialize the "quick"
3418    elements of all the CUs and return 1.  Otherwise, return 0.  */
3419
3420 static int
3421 dwarf2_read_index (struct objfile *objfile)
3422 {
3423   struct mapped_index local_map, *map;
3424   const gdb_byte *cu_list, *types_list, *dwz_list = NULL;
3425   offset_type cu_list_elements, types_list_elements, dwz_list_elements = 0;
3426   struct dwz_file *dwz;
3427
3428   if (!read_index_from_section (objfile, objfile_name (objfile),
3429                                 use_deprecated_index_sections,
3430                                 &dwarf2_per_objfile->gdb_index, &local_map,
3431                                 &cu_list, &cu_list_elements,
3432                                 &types_list, &types_list_elements))
3433     return 0;
3434
3435   /* Don't use the index if it's empty.  */
3436   if (local_map.symbol_table_slots == 0)
3437     return 0;
3438
3439   /* If there is a .dwz file, read it so we can get its CU list as
3440      well.  */
3441   dwz = dwarf2_get_dwz_file ();
3442   if (dwz != NULL)
3443     {
3444       struct mapped_index dwz_map;
3445       const gdb_byte *dwz_types_ignore;
3446       offset_type dwz_types_elements_ignore;
3447
3448       if (!read_index_from_section (objfile, bfd_get_filename (dwz->dwz_bfd),
3449                                     1,
3450                                     &dwz->gdb_index, &dwz_map,
3451                                     &dwz_list, &dwz_list_elements,
3452                                     &dwz_types_ignore,
3453                                     &dwz_types_elements_ignore))
3454         {
3455           warning (_("could not read '.gdb_index' section from %s; skipping"),
3456                    bfd_get_filename (dwz->dwz_bfd));
3457           return 0;
3458         }
3459     }
3460
3461   create_cus_from_index (objfile, cu_list, cu_list_elements, dwz_list,
3462                          dwz_list_elements);
3463
3464   if (types_list_elements)
3465     {
3466       struct dwarf2_section_info *section;
3467
3468       /* We can only handle a single .debug_types when we have an
3469          index.  */
3470       if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) != 1)
3471         return 0;
3472
3473       section = VEC_index (dwarf2_section_info_def,
3474                            dwarf2_per_objfile->types, 0);
3475
3476       create_signatured_type_table_from_index (objfile, section, types_list,
3477                                                types_list_elements);
3478     }
3479
3480   create_addrmap_from_index (objfile, &local_map);
3481
3482   map = XOBNEW (&objfile->objfile_obstack, struct mapped_index);
3483   map = new (map) mapped_index ();
3484   *map = local_map;
3485
3486   dwarf2_per_objfile->index_table = map;
3487   dwarf2_per_objfile->using_index = 1;
3488   dwarf2_per_objfile->quick_file_names_table =
3489     create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
3490
3491   return 1;
3492 }
3493
3494 /* A helper for the "quick" functions which sets the global
3495    dwarf2_per_objfile according to OBJFILE.  */
3496
3497 static void
3498 dw2_setup (struct objfile *objfile)
3499 {
3500   dwarf2_per_objfile = ((struct dwarf2_per_objfile *)
3501                         objfile_data (objfile, dwarf2_objfile_data_key));
3502   gdb_assert (dwarf2_per_objfile);
3503 }
3504
3505 /* die_reader_func for dw2_get_file_names.  */
3506
3507 static void
3508 dw2_get_file_names_reader (const struct die_reader_specs *reader,
3509                            const gdb_byte *info_ptr,
3510                            struct die_info *comp_unit_die,
3511                            int has_children,
3512                            void *data)
3513 {
3514   struct dwarf2_cu *cu = reader->cu;
3515   struct dwarf2_per_cu_data *this_cu = cu->per_cu;  
3516   struct objfile *objfile = dwarf2_per_objfile->objfile;
3517   struct dwarf2_per_cu_data *lh_cu;
3518   struct attribute *attr;
3519   int i;
3520   void **slot;
3521   struct quick_file_names *qfn;
3522
3523   gdb_assert (! this_cu->is_debug_types);
3524
3525   /* Our callers never want to match partial units -- instead they
3526      will match the enclosing full CU.  */
3527   if (comp_unit_die->tag == DW_TAG_partial_unit)
3528     {
3529       this_cu->v.quick->no_file_data = 1;
3530       return;
3531     }
3532
3533   lh_cu = this_cu;
3534   slot = NULL;
3535
3536   line_header_up lh;
3537   sect_offset line_offset {};
3538
3539   attr = dwarf2_attr (comp_unit_die, DW_AT_stmt_list, cu);
3540   if (attr)
3541     {
3542       struct quick_file_names find_entry;
3543
3544       line_offset = (sect_offset) DW_UNSND (attr);
3545
3546       /* We may have already read in this line header (TU line header sharing).
3547          If we have we're done.  */
3548       find_entry.hash.dwo_unit = cu->dwo_unit;
3549       find_entry.hash.line_sect_off = line_offset;
3550       slot = htab_find_slot (dwarf2_per_objfile->quick_file_names_table,
3551                              &find_entry, INSERT);
3552       if (*slot != NULL)
3553         {
3554           lh_cu->v.quick->file_names = (struct quick_file_names *) *slot;
3555           return;
3556         }
3557
3558       lh = dwarf_decode_line_header (line_offset, cu);
3559     }
3560   if (lh == NULL)
3561     {
3562       lh_cu->v.quick->no_file_data = 1;
3563       return;
3564     }
3565
3566   qfn = XOBNEW (&objfile->objfile_obstack, struct quick_file_names);
3567   qfn->hash.dwo_unit = cu->dwo_unit;
3568   qfn->hash.line_sect_off = line_offset;
3569   gdb_assert (slot != NULL);
3570   *slot = qfn;
3571
3572   file_and_directory fnd = find_file_and_directory (comp_unit_die, cu);
3573
3574   qfn->num_file_names = lh->file_names.size ();
3575   qfn->file_names =
3576     XOBNEWVEC (&objfile->objfile_obstack, const char *, lh->file_names.size ());
3577   for (i = 0; i < lh->file_names.size (); ++i)
3578     qfn->file_names[i] = file_full_name (i + 1, lh.get (), fnd.comp_dir);
3579   qfn->real_names = NULL;
3580
3581   lh_cu->v.quick->file_names = qfn;
3582 }
3583
3584 /* A helper for the "quick" functions which attempts to read the line
3585    table for THIS_CU.  */
3586
3587 static struct quick_file_names *
3588 dw2_get_file_names (struct dwarf2_per_cu_data *this_cu)
3589 {
3590   /* This should never be called for TUs.  */
3591   gdb_assert (! this_cu->is_debug_types);
3592   /* Nor type unit groups.  */
3593   gdb_assert (! IS_TYPE_UNIT_GROUP (this_cu));
3594
3595   if (this_cu->v.quick->file_names != NULL)
3596     return this_cu->v.quick->file_names;
3597   /* If we know there is no line data, no point in looking again.  */
3598   if (this_cu->v.quick->no_file_data)
3599     return NULL;
3600
3601   init_cutu_and_read_dies_simple (this_cu, dw2_get_file_names_reader, NULL);
3602
3603   if (this_cu->v.quick->no_file_data)
3604     return NULL;
3605   return this_cu->v.quick->file_names;
3606 }
3607
3608 /* A helper for the "quick" functions which computes and caches the
3609    real path for a given file name from the line table.  */
3610
3611 static const char *
3612 dw2_get_real_path (struct objfile *objfile,
3613                    struct quick_file_names *qfn, int index)
3614 {
3615   if (qfn->real_names == NULL)
3616     qfn->real_names = OBSTACK_CALLOC (&objfile->objfile_obstack,
3617                                       qfn->num_file_names, const char *);
3618
3619   if (qfn->real_names[index] == NULL)
3620     qfn->real_names[index] = gdb_realpath (qfn->file_names[index]).release ();
3621
3622   return qfn->real_names[index];
3623 }
3624
3625 static struct symtab *
3626 dw2_find_last_source_symtab (struct objfile *objfile)
3627 {
3628   struct compunit_symtab *cust;
3629   int index;
3630
3631   dw2_setup (objfile);
3632   index = dwarf2_per_objfile->n_comp_units - 1;
3633   cust = dw2_instantiate_symtab (dw2_get_cutu (index));
3634   if (cust == NULL)
3635     return NULL;
3636   return compunit_primary_filetab (cust);
3637 }
3638
3639 /* Traversal function for dw2_forget_cached_source_info.  */
3640
3641 static int
3642 dw2_free_cached_file_names (void **slot, void *info)
3643 {
3644   struct quick_file_names *file_data = (struct quick_file_names *) *slot;
3645
3646   if (file_data->real_names)
3647     {
3648       int i;
3649
3650       for (i = 0; i < file_data->num_file_names; ++i)
3651         {
3652           xfree ((void*) file_data->real_names[i]);
3653           file_data->real_names[i] = NULL;
3654         }
3655     }
3656
3657   return 1;
3658 }
3659
3660 static void
3661 dw2_forget_cached_source_info (struct objfile *objfile)
3662 {
3663   dw2_setup (objfile);
3664
3665   htab_traverse_noresize (dwarf2_per_objfile->quick_file_names_table,
3666                           dw2_free_cached_file_names, NULL);
3667 }
3668
3669 /* Helper function for dw2_map_symtabs_matching_filename that expands
3670    the symtabs and calls the iterator.  */
3671
3672 static int
3673 dw2_map_expand_apply (struct objfile *objfile,
3674                       struct dwarf2_per_cu_data *per_cu,
3675                       const char *name, const char *real_path,
3676                       gdb::function_view<bool (symtab *)> callback)
3677 {
3678   struct compunit_symtab *last_made = objfile->compunit_symtabs;
3679
3680   /* Don't visit already-expanded CUs.  */
3681   if (per_cu->v.quick->compunit_symtab)
3682     return 0;
3683
3684   /* This may expand more than one symtab, and we want to iterate over
3685      all of them.  */
3686   dw2_instantiate_symtab (per_cu);
3687
3688   return iterate_over_some_symtabs (name, real_path, objfile->compunit_symtabs,
3689                                     last_made, callback);
3690 }
3691
3692 /* Implementation of the map_symtabs_matching_filename method.  */
3693
3694 static bool
3695 dw2_map_symtabs_matching_filename
3696   (struct objfile *objfile, const char *name, const char *real_path,
3697    gdb::function_view<bool (symtab *)> callback)
3698 {
3699   int i;
3700   const char *name_basename = lbasename (name);
3701
3702   dw2_setup (objfile);
3703
3704   /* The rule is CUs specify all the files, including those used by
3705      any TU, so there's no need to scan TUs here.  */
3706
3707   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
3708     {
3709       int j;
3710       struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
3711       struct quick_file_names *file_data;
3712
3713       /* We only need to look at symtabs not already expanded.  */
3714       if (per_cu->v.quick->compunit_symtab)
3715         continue;
3716
3717       file_data = dw2_get_file_names (per_cu);
3718       if (file_data == NULL)
3719         continue;
3720
3721       for (j = 0; j < file_data->num_file_names; ++j)
3722         {
3723           const char *this_name = file_data->file_names[j];
3724           const char *this_real_name;
3725
3726           if (compare_filenames_for_search (this_name, name))
3727             {
3728               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3729                                         callback))
3730                 return true;
3731               continue;
3732             }
3733
3734           /* Before we invoke realpath, which can get expensive when many
3735              files are involved, do a quick comparison of the basenames.  */
3736           if (! basenames_may_differ
3737               && FILENAME_CMP (lbasename (this_name), name_basename) != 0)
3738             continue;
3739
3740           this_real_name = dw2_get_real_path (objfile, file_data, j);
3741           if (compare_filenames_for_search (this_real_name, name))
3742             {
3743               if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3744                                         callback))
3745                 return true;
3746               continue;
3747             }
3748
3749           if (real_path != NULL)
3750             {
3751               gdb_assert (IS_ABSOLUTE_PATH (real_path));
3752               gdb_assert (IS_ABSOLUTE_PATH (name));
3753               if (this_real_name != NULL
3754                   && FILENAME_CMP (real_path, this_real_name) == 0)
3755                 {
3756                   if (dw2_map_expand_apply (objfile, per_cu, name, real_path,
3757                                             callback))
3758                     return true;
3759                   continue;
3760                 }
3761             }
3762         }
3763     }
3764
3765   return false;
3766 }
3767
3768 /* Struct used to manage iterating over all CUs looking for a symbol.  */
3769
3770 struct dw2_symtab_iterator
3771 {
3772   /* The internalized form of .gdb_index.  */
3773   struct mapped_index *index;
3774   /* If non-zero, only look for symbols that match BLOCK_INDEX.  */
3775   int want_specific_block;
3776   /* One of GLOBAL_BLOCK or STATIC_BLOCK.
3777      Unused if !WANT_SPECIFIC_BLOCK.  */
3778   int block_index;
3779   /* The kind of symbol we're looking for.  */
3780   domain_enum domain;
3781   /* The list of CUs from the index entry of the symbol,
3782      or NULL if not found.  */
3783   offset_type *vec;
3784   /* The next element in VEC to look at.  */
3785   int next;
3786   /* The number of elements in VEC, or zero if there is no match.  */
3787   int length;
3788   /* Have we seen a global version of the symbol?
3789      If so we can ignore all further global instances.
3790      This is to work around gold/15646, inefficient gold-generated
3791      indices.  */
3792   int global_seen;
3793 };
3794
3795 /* Initialize the index symtab iterator ITER.
3796    If WANT_SPECIFIC_BLOCK is non-zero, only look for symbols
3797    in block BLOCK_INDEX.  Otherwise BLOCK_INDEX is ignored.  */
3798
3799 static void
3800 dw2_symtab_iter_init (struct dw2_symtab_iterator *iter,
3801                       struct mapped_index *index,
3802                       int want_specific_block,
3803                       int block_index,
3804                       domain_enum domain,
3805                       const char *name)
3806 {
3807   iter->index = index;
3808   iter->want_specific_block = want_specific_block;
3809   iter->block_index = block_index;
3810   iter->domain = domain;
3811   iter->next = 0;
3812   iter->global_seen = 0;
3813
3814   if (find_slot_in_mapped_hash (index, name, &iter->vec))
3815     iter->length = MAYBE_SWAP (*iter->vec);
3816   else
3817     {
3818       iter->vec = NULL;
3819       iter->length = 0;
3820     }
3821 }
3822
3823 /* Return the next matching CU or NULL if there are no more.  */
3824
3825 static struct dwarf2_per_cu_data *
3826 dw2_symtab_iter_next (struct dw2_symtab_iterator *iter)
3827 {
3828   for ( ; iter->next < iter->length; ++iter->next)
3829     {
3830       offset_type cu_index_and_attrs =
3831         MAYBE_SWAP (iter->vec[iter->next + 1]);
3832       offset_type cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
3833       struct dwarf2_per_cu_data *per_cu;
3834       int want_static = iter->block_index != GLOBAL_BLOCK;
3835       /* This value is only valid for index versions >= 7.  */
3836       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
3837       gdb_index_symbol_kind symbol_kind =
3838         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
3839       /* Only check the symbol attributes if they're present.
3840          Indices prior to version 7 don't record them,
3841          and indices >= 7 may elide them for certain symbols
3842          (gold does this).  */
3843       int attrs_valid =
3844         (iter->index->version >= 7
3845          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
3846
3847       /* Don't crash on bad data.  */
3848       if (cu_index >= (dwarf2_per_objfile->n_comp_units
3849                        + dwarf2_per_objfile->n_type_units))
3850         {
3851           complaint (&symfile_complaints,
3852                      _(".gdb_index entry has bad CU index"
3853                        " [in module %s]"),
3854                      objfile_name (dwarf2_per_objfile->objfile));
3855           continue;
3856         }
3857
3858       per_cu = dw2_get_cutu (cu_index);
3859
3860       /* Skip if already read in.  */
3861       if (per_cu->v.quick->compunit_symtab)
3862         continue;
3863
3864       /* Check static vs global.  */
3865       if (attrs_valid)
3866         {
3867           if (iter->want_specific_block
3868               && want_static != is_static)
3869             continue;
3870           /* Work around gold/15646.  */
3871           if (!is_static && iter->global_seen)
3872             continue;
3873           if (!is_static)
3874             iter->global_seen = 1;
3875         }
3876
3877       /* Only check the symbol's kind if it has one.  */
3878       if (attrs_valid)
3879         {
3880           switch (iter->domain)
3881             {
3882             case VAR_DOMAIN:
3883               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE
3884                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION
3885                   /* Some types are also in VAR_DOMAIN.  */
3886                   && symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3887                 continue;
3888               break;
3889             case STRUCT_DOMAIN:
3890               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
3891                 continue;
3892               break;
3893             case LABEL_DOMAIN:
3894               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_OTHER)
3895                 continue;
3896               break;
3897             default:
3898               break;
3899             }
3900         }
3901
3902       ++iter->next;
3903       return per_cu;
3904     }
3905
3906   return NULL;
3907 }
3908
3909 static struct compunit_symtab *
3910 dw2_lookup_symbol (struct objfile *objfile, int block_index,
3911                    const char *name, domain_enum domain)
3912 {
3913   struct compunit_symtab *stab_best = NULL;
3914   struct mapped_index *index;
3915
3916   dw2_setup (objfile);
3917
3918   lookup_name_info lookup_name (name, symbol_name_match_type::FULL);
3919
3920   index = dwarf2_per_objfile->index_table;
3921
3922   /* index is NULL if OBJF_READNOW.  */
3923   if (index)
3924     {
3925       struct dw2_symtab_iterator iter;
3926       struct dwarf2_per_cu_data *per_cu;
3927
3928       dw2_symtab_iter_init (&iter, index, 1, block_index, domain, name);
3929
3930       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
3931         {
3932           struct symbol *sym, *with_opaque = NULL;
3933           struct compunit_symtab *stab = dw2_instantiate_symtab (per_cu);
3934           const struct blockvector *bv = COMPUNIT_BLOCKVECTOR (stab);
3935           struct block *block = BLOCKVECTOR_BLOCK (bv, block_index);
3936
3937           sym = block_find_symbol (block, name, domain,
3938                                    block_find_non_opaque_type_preferred,
3939                                    &with_opaque);
3940
3941           /* Some caution must be observed with overloaded functions
3942              and methods, since the index will not contain any overload
3943              information (but NAME might contain it).  */
3944
3945           if (sym != NULL
3946               && SYMBOL_MATCHES_SEARCH_NAME (sym, lookup_name))
3947             return stab;
3948           if (with_opaque != NULL
3949               && SYMBOL_MATCHES_SEARCH_NAME (with_opaque, lookup_name))
3950             stab_best = stab;
3951
3952           /* Keep looking through other CUs.  */
3953         }
3954     }
3955
3956   return stab_best;
3957 }
3958
3959 static void
3960 dw2_print_stats (struct objfile *objfile)
3961 {
3962   int i, total, count;
3963
3964   dw2_setup (objfile);
3965   total = dwarf2_per_objfile->n_comp_units + dwarf2_per_objfile->n_type_units;
3966   count = 0;
3967   for (i = 0; i < total; ++i)
3968     {
3969       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
3970
3971       if (!per_cu->v.quick->compunit_symtab)
3972         ++count;
3973     }
3974   printf_filtered (_("  Number of read CUs: %d\n"), total - count);
3975   printf_filtered (_("  Number of unread CUs: %d\n"), count);
3976 }
3977
3978 /* This dumps minimal information about the index.
3979    It is called via "mt print objfiles".
3980    One use is to verify .gdb_index has been loaded by the
3981    gdb.dwarf2/gdb-index.exp testcase.  */
3982
3983 static void
3984 dw2_dump (struct objfile *objfile)
3985 {
3986   dw2_setup (objfile);
3987   gdb_assert (dwarf2_per_objfile->using_index);
3988   printf_filtered (".gdb_index:");
3989   if (dwarf2_per_objfile->index_table != NULL)
3990     {
3991       printf_filtered (" version %d\n",
3992                        dwarf2_per_objfile->index_table->version);
3993     }
3994   else
3995     printf_filtered (" faked for \"readnow\"\n");
3996   printf_filtered ("\n");
3997 }
3998
3999 static void
4000 dw2_relocate (struct objfile *objfile,
4001               const struct section_offsets *new_offsets,
4002               const struct section_offsets *delta)
4003 {
4004   /* There's nothing to relocate here.  */
4005 }
4006
4007 static void
4008 dw2_expand_symtabs_for_function (struct objfile *objfile,
4009                                  const char *func_name)
4010 {
4011   struct mapped_index *index;
4012
4013   dw2_setup (objfile);
4014
4015   index = dwarf2_per_objfile->index_table;
4016
4017   /* index is NULL if OBJF_READNOW.  */
4018   if (index)
4019     {
4020       struct dw2_symtab_iterator iter;
4021       struct dwarf2_per_cu_data *per_cu;
4022
4023       /* Note: It doesn't matter what we pass for block_index here.  */
4024       dw2_symtab_iter_init (&iter, index, 0, GLOBAL_BLOCK, VAR_DOMAIN,
4025                             func_name);
4026
4027       while ((per_cu = dw2_symtab_iter_next (&iter)) != NULL)
4028         dw2_instantiate_symtab (per_cu);
4029     }
4030 }
4031
4032 static void
4033 dw2_expand_all_symtabs (struct objfile *objfile)
4034 {
4035   int i;
4036
4037   dw2_setup (objfile);
4038
4039   for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4040                    + dwarf2_per_objfile->n_type_units); ++i)
4041     {
4042       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4043
4044       dw2_instantiate_symtab (per_cu);
4045     }
4046 }
4047
4048 static void
4049 dw2_expand_symtabs_with_fullname (struct objfile *objfile,
4050                                   const char *fullname)
4051 {
4052   int i;
4053
4054   dw2_setup (objfile);
4055
4056   /* We don't need to consider type units here.
4057      This is only called for examining code, e.g. expand_line_sal.
4058      There can be an order of magnitude (or more) more type units
4059      than comp units, and we avoid them if we can.  */
4060
4061   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4062     {
4063       int j;
4064       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4065       struct quick_file_names *file_data;
4066
4067       /* We only need to look at symtabs not already expanded.  */
4068       if (per_cu->v.quick->compunit_symtab)
4069         continue;
4070
4071       file_data = dw2_get_file_names (per_cu);
4072       if (file_data == NULL)
4073         continue;
4074
4075       for (j = 0; j < file_data->num_file_names; ++j)
4076         {
4077           const char *this_fullname = file_data->file_names[j];
4078
4079           if (filename_cmp (this_fullname, fullname) == 0)
4080             {
4081               dw2_instantiate_symtab (per_cu);
4082               break;
4083             }
4084         }
4085     }
4086 }
4087
4088 static void
4089 dw2_map_matching_symbols (struct objfile *objfile,
4090                           const char * name, domain_enum domain,
4091                           int global,
4092                           int (*callback) (struct block *,
4093                                            struct symbol *, void *),
4094                           void *data, symbol_name_match_type match,
4095                           symbol_compare_ftype *ordered_compare)
4096 {
4097   /* Currently unimplemented; used for Ada.  The function can be called if the
4098      current language is Ada for a non-Ada objfile using GNU index.  As Ada
4099      does not look for non-Ada symbols this function should just return.  */
4100 }
4101
4102 /* Symbol name matcher for .gdb_index names.
4103
4104    Symbol names in .gdb_index have a few particularities:
4105
4106    - There's no indication of which is the language of each symbol.
4107
4108      Since each language has its own symbol name matching algorithm,
4109      and we don't know which language is the right one, we must match
4110      each symbol against all languages.  This would be a potential
4111      performance problem if it were not mitigated by the
4112      mapped_index::name_components lookup table, which significantly
4113      reduces the number of times we need to call into this matcher,
4114      making it a non-issue.
4115
4116    - Symbol names in the index have no overload (parameter)
4117      information.  I.e., in C++, "foo(int)" and "foo(long)" both
4118      appear as "foo" in the index, for example.
4119
4120      This means that the lookup names passed to the symbol name
4121      matcher functions must have no parameter information either
4122      because (e.g.) symbol search name "foo" does not match
4123      lookup-name "foo(int)" [while swapping search name for lookup
4124      name would match].
4125 */
4126 class gdb_index_symbol_name_matcher
4127 {
4128 public:
4129   /* Prepares the vector of comparison functions for LOOKUP_NAME.  */
4130   gdb_index_symbol_name_matcher (const lookup_name_info &lookup_name);
4131
4132   /* Walk all the matcher routines and match SYMBOL_NAME against them.
4133      Returns true if any matcher matches.  */
4134   bool matches (const char *symbol_name);
4135
4136 private:
4137   /* A reference to the lookup name we're matching against.  */
4138   const lookup_name_info &m_lookup_name;
4139
4140   /* A vector holding all the different symbol name matchers, for all
4141      languages.  */
4142   std::vector<symbol_name_matcher_ftype *> m_symbol_name_matcher_funcs;
4143 };
4144
4145 gdb_index_symbol_name_matcher::gdb_index_symbol_name_matcher
4146   (const lookup_name_info &lookup_name)
4147     : m_lookup_name (lookup_name)
4148 {
4149   /* Prepare the vector of comparison functions upfront, to avoid
4150      doing the same work for each symbol.  Care is taken to avoid
4151      matching with the same matcher more than once if/when multiple
4152      languages use the same matcher function.  */
4153   auto &matchers = m_symbol_name_matcher_funcs;
4154   matchers.reserve (nr_languages);
4155
4156   matchers.push_back (default_symbol_name_matcher);
4157
4158   for (int i = 0; i < nr_languages; i++)
4159     {
4160       const language_defn *lang = language_def ((enum language) i);
4161       if (lang->la_get_symbol_name_matcher != NULL)
4162         {
4163           symbol_name_matcher_ftype *name_matcher
4164             = lang->la_get_symbol_name_matcher (m_lookup_name);
4165
4166           /* Don't insert the same comparison routine more than once.
4167              Note that we do this linear walk instead of a cheaper
4168              sorted insert, or use a std::set or something like that,
4169              because relative order of function addresses is not
4170              stable.  This is not a problem in practice because the
4171              number of supported languages is low, and the cost here
4172              is tiny compared to the number of searches we'll do
4173              afterwards using this object.  */
4174           if (std::find (matchers.begin (), matchers.end (), name_matcher)
4175               == matchers.end ())
4176             matchers.push_back (name_matcher);
4177         }
4178     }
4179 }
4180
4181 bool
4182 gdb_index_symbol_name_matcher::matches (const char *symbol_name)
4183 {
4184   for (auto matches_name : m_symbol_name_matcher_funcs)
4185     if (matches_name (symbol_name, m_lookup_name, NULL))
4186       return true;
4187
4188   return false;
4189 }
4190
4191 /* Helper for dw2_expand_symtabs_matching that works with a
4192    mapped_index instead of the containing objfile.  This is split to a
4193    separate function in order to be able to unit test the
4194    name_components matching using a mock mapped_index.  For each
4195    symbol name that matches, calls MATCH_CALLBACK, passing it the
4196    symbol's index in the mapped_index symbol table.  */
4197
4198 static void
4199 dw2_expand_symtabs_matching_symbol
4200   (mapped_index &index,
4201    const lookup_name_info &lookup_name,
4202    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4203    enum search_domain kind,
4204    gdb::function_view<void (offset_type)> match_callback)
4205 {
4206   gdb_index_symbol_name_matcher lookup_name_matcher
4207     (lookup_name);
4208
4209   auto *name_cmp = case_sensitivity == case_sensitive_on ? strcmp : strcasecmp;
4210
4211   /* Build the symbol name component sorted vector, if we haven't yet.
4212      The code below only knows how to break apart components of C++
4213      symbol names (and other languages that use '::' as
4214      namespace/module separator).  If we add support for wild matching
4215      to some language that uses some other operator (E.g., Ada, Go and
4216      D use '.'), then we'll need to try splitting the symbol name
4217      according to that language too.  Note that Ada does support wild
4218      matching, but doesn't currently support .gdb_index.  */
4219   if (index.name_components.empty ())
4220     {
4221       for (size_t iter = 0; iter < index.symbol_table_slots; ++iter)
4222         {
4223           offset_type idx = 2 * iter;
4224
4225           if (index.symbol_table[idx] == 0
4226               && index.symbol_table[idx + 1] == 0)
4227             continue;
4228
4229           const char *name = index.symbol_name_at (idx);
4230
4231           /* Add each name component to the name component table.  */
4232           unsigned int previous_len = 0;
4233           for (unsigned int current_len = cp_find_first_component (name);
4234                name[current_len] != '\0';
4235                current_len += cp_find_first_component (name + current_len))
4236             {
4237               gdb_assert (name[current_len] == ':');
4238               index.name_components.push_back ({previous_len, idx});
4239               /* Skip the '::'.  */
4240               current_len += 2;
4241               previous_len = current_len;
4242             }
4243           index.name_components.push_back ({previous_len, idx});
4244         }
4245
4246       /* Sort name_components elements by name.  */
4247       auto name_comp_compare = [&] (const name_component &left,
4248                                     const name_component &right)
4249         {
4250           const char *left_qualified = index.symbol_name_at (left.idx);
4251           const char *right_qualified = index.symbol_name_at (right.idx);
4252
4253           const char *left_name = left_qualified + left.name_offset;
4254           const char *right_name = right_qualified + right.name_offset;
4255
4256           return name_cmp (left_name, right_name) < 0;
4257         };
4258
4259       std::sort (index.name_components.begin (),
4260                  index.name_components.end (),
4261                  name_comp_compare);
4262     }
4263
4264   const char *cplus
4265     = lookup_name.cplus ().lookup_name ().c_str ();
4266
4267   /* Comparison function object for lower_bound that matches against a
4268      given symbol name.  */
4269   auto lookup_compare_lower = [&] (const name_component &elem,
4270                                    const char *name)
4271     {
4272       const char *elem_qualified = index.symbol_name_at (elem.idx);
4273       const char *elem_name = elem_qualified + elem.name_offset;
4274       return name_cmp (elem_name, name) < 0;
4275     };
4276
4277   /* Comparison function object for upper_bound that matches against a
4278      given symbol name.  */
4279   auto lookup_compare_upper = [&] (const char *name,
4280                                    const name_component &elem)
4281     {
4282       const char *elem_qualified = index.symbol_name_at (elem.idx);
4283       const char *elem_name = elem_qualified + elem.name_offset;
4284       return name_cmp (name, elem_name) < 0;
4285     };
4286
4287   auto begin = index.name_components.begin ();
4288   auto end = index.name_components.end ();
4289
4290   /* Find the lower bound.  */
4291   auto lower = [&] ()
4292     {
4293       if (lookup_name.completion_mode () && cplus[0] == '\0')
4294         return begin;
4295       else
4296         return std::lower_bound (begin, end, cplus, lookup_compare_lower);
4297     } ();
4298
4299   /* Find the upper bound.  */
4300   auto upper = [&] ()
4301     {
4302       if (lookup_name.completion_mode ())
4303         {
4304           /* The string frobbing below won't work if the string is
4305              empty.  We don't need it then, anyway -- if we're
4306              completing an empty string, then we want to iterate over
4307              the whole range.  */
4308           if (cplus[0] == '\0')
4309             return end;
4310
4311           /* In completion mode, increment the last character because
4312              we want UPPER to point past all symbols names that have
4313              the same prefix.  */
4314           std::string after = cplus;
4315
4316           gdb_assert (after.back () != 0xff);
4317           after.back ()++;
4318
4319           return std::upper_bound (lower, end, after.c_str (),
4320                                    lookup_compare_upper);
4321         }
4322       else
4323         return std::upper_bound (lower, end, cplus, lookup_compare_upper);
4324     } ();
4325
4326   /* Now for each symbol name in range, check to see if we have a name
4327      match, and if so, call the MATCH_CALLBACK callback.  */
4328
4329   /* The same symbol may appear more than once in the range though.
4330      E.g., if we're looking for symbols that complete "w", and we have
4331      a symbol named "w1::w2", we'll find the two name components for
4332      that same symbol in the range.  To be sure we only call the
4333      callback once per symbol, we first collect the symbol name
4334      indexes that matched in a temporary vector and ignore
4335      duplicates.  */
4336   std::vector<offset_type> matches;
4337   matches.reserve (std::distance (lower, upper));
4338
4339   for (;lower != upper; ++lower)
4340     {
4341       const char *qualified = index.symbol_name_at (lower->idx);
4342
4343       if (!lookup_name_matcher.matches (qualified)
4344           || (symbol_matcher != NULL && !symbol_matcher (qualified)))
4345         continue;
4346
4347       matches.push_back (lower->idx);
4348     }
4349
4350   std::sort (matches.begin (), matches.end ());
4351
4352   /* Finally call the callback, once per match.  */
4353   ULONGEST prev = -1;
4354   for (offset_type idx : matches)
4355     {
4356       if (prev != idx)
4357         {
4358           match_callback (idx);
4359           prev = idx;
4360         }
4361     }
4362
4363   /* Above we use a type wider than idx's for 'prev', since 0 and
4364      (offset_type)-1 are both possible values.  */
4365   static_assert (sizeof (prev) > sizeof (offset_type), "");
4366 }
4367
4368 /* Helper for dw2_expand_matching symtabs.  Called on each symbol
4369    matched, to expand corresponding CUs that were marked.  IDX is the
4370    index of the symbol name that matched.  */
4371
4372 static void
4373 dw2_expand_marked_cus
4374   (mapped_index &index, offset_type idx,
4375    struct objfile *objfile,
4376    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4377    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4378    search_domain kind)
4379 {
4380   const char *name;
4381   offset_type *vec, vec_len, vec_idx;
4382   bool global_seen = false;
4383
4384   vec = (offset_type *) (index.constant_pool
4385                          + MAYBE_SWAP (index.symbol_table[idx + 1]));
4386   vec_len = MAYBE_SWAP (vec[0]);
4387   for (vec_idx = 0; vec_idx < vec_len; ++vec_idx)
4388     {
4389       struct dwarf2_per_cu_data *per_cu;
4390       offset_type cu_index_and_attrs = MAYBE_SWAP (vec[vec_idx + 1]);
4391       /* This value is only valid for index versions >= 7.  */
4392       int is_static = GDB_INDEX_SYMBOL_STATIC_VALUE (cu_index_and_attrs);
4393       gdb_index_symbol_kind symbol_kind =
4394         GDB_INDEX_SYMBOL_KIND_VALUE (cu_index_and_attrs);
4395       int cu_index = GDB_INDEX_CU_VALUE (cu_index_and_attrs);
4396       /* Only check the symbol attributes if they're present.
4397          Indices prior to version 7 don't record them,
4398          and indices >= 7 may elide them for certain symbols
4399          (gold does this).  */
4400       int attrs_valid =
4401         (index.version >= 7
4402          && symbol_kind != GDB_INDEX_SYMBOL_KIND_NONE);
4403
4404       /* Work around gold/15646.  */
4405       if (attrs_valid)
4406         {
4407           if (!is_static && global_seen)
4408             continue;
4409           if (!is_static)
4410             global_seen = true;
4411         }
4412
4413       /* Only check the symbol's kind if it has one.  */
4414       if (attrs_valid)
4415         {
4416           switch (kind)
4417             {
4418             case VARIABLES_DOMAIN:
4419               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_VARIABLE)
4420                 continue;
4421               break;
4422             case FUNCTIONS_DOMAIN:
4423               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_FUNCTION)
4424                 continue;
4425               break;
4426             case TYPES_DOMAIN:
4427               if (symbol_kind != GDB_INDEX_SYMBOL_KIND_TYPE)
4428                 continue;
4429               break;
4430             default:
4431               break;
4432             }
4433         }
4434
4435       /* Don't crash on bad data.  */
4436       if (cu_index >= (dwarf2_per_objfile->n_comp_units
4437                        + dwarf2_per_objfile->n_type_units))
4438         {
4439           complaint (&symfile_complaints,
4440                      _(".gdb_index entry has bad CU index"
4441                        " [in module %s]"), objfile_name (objfile));
4442           continue;
4443         }
4444
4445       per_cu = dw2_get_cutu (cu_index);
4446       if (file_matcher == NULL || per_cu->v.quick->mark)
4447         {
4448           int symtab_was_null =
4449             (per_cu->v.quick->compunit_symtab == NULL);
4450
4451           dw2_instantiate_symtab (per_cu);
4452
4453           if (expansion_notify != NULL
4454               && symtab_was_null
4455               && per_cu->v.quick->compunit_symtab != NULL)
4456             expansion_notify (per_cu->v.quick->compunit_symtab);
4457         }
4458     }
4459 }
4460
4461 static void
4462 dw2_expand_symtabs_matching
4463   (struct objfile *objfile,
4464    gdb::function_view<expand_symtabs_file_matcher_ftype> file_matcher,
4465    const lookup_name_info &lookup_name,
4466    gdb::function_view<expand_symtabs_symbol_matcher_ftype> symbol_matcher,
4467    gdb::function_view<expand_symtabs_exp_notify_ftype> expansion_notify,
4468    enum search_domain kind)
4469 {
4470   int i;
4471   offset_type iter;
4472
4473   dw2_setup (objfile);
4474
4475   /* index_table is NULL if OBJF_READNOW.  */
4476   if (!dwarf2_per_objfile->index_table)
4477     return;
4478
4479   if (file_matcher != NULL)
4480     {
4481       htab_up visited_found (htab_create_alloc (10, htab_hash_pointer,
4482                                                 htab_eq_pointer,
4483                                                 NULL, xcalloc, xfree));
4484       htab_up visited_not_found (htab_create_alloc (10, htab_hash_pointer,
4485                                                     htab_eq_pointer,
4486                                                     NULL, xcalloc, xfree));
4487
4488       /* The rule is CUs specify all the files, including those used by
4489          any TU, so there's no need to scan TUs here.  */
4490
4491       for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4492         {
4493           int j;
4494           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4495           struct quick_file_names *file_data;
4496           void **slot;
4497
4498           QUIT;
4499
4500           per_cu->v.quick->mark = 0;
4501
4502           /* We only need to look at symtabs not already expanded.  */
4503           if (per_cu->v.quick->compunit_symtab)
4504             continue;
4505
4506           file_data = dw2_get_file_names (per_cu);
4507           if (file_data == NULL)
4508             continue;
4509
4510           if (htab_find (visited_not_found.get (), file_data) != NULL)
4511             continue;
4512           else if (htab_find (visited_found.get (), file_data) != NULL)
4513             {
4514               per_cu->v.quick->mark = 1;
4515               continue;
4516             }
4517
4518           for (j = 0; j < file_data->num_file_names; ++j)
4519             {
4520               const char *this_real_name;
4521
4522               if (file_matcher (file_data->file_names[j], false))
4523                 {
4524                   per_cu->v.quick->mark = 1;
4525                   break;
4526                 }
4527
4528               /* Before we invoke realpath, which can get expensive when many
4529                  files are involved, do a quick comparison of the basenames.  */
4530               if (!basenames_may_differ
4531                   && !file_matcher (lbasename (file_data->file_names[j]),
4532                                     true))
4533                 continue;
4534
4535               this_real_name = dw2_get_real_path (objfile, file_data, j);
4536               if (file_matcher (this_real_name, false))
4537                 {
4538                   per_cu->v.quick->mark = 1;
4539                   break;
4540                 }
4541             }
4542
4543           slot = htab_find_slot (per_cu->v.quick->mark
4544                                  ? visited_found.get ()
4545                                  : visited_not_found.get (),
4546                                  file_data, INSERT);
4547           *slot = file_data;
4548         }
4549     }
4550
4551   mapped_index &index = *dwarf2_per_objfile->index_table;
4552
4553   dw2_expand_symtabs_matching_symbol (index, lookup_name,
4554                                       symbol_matcher,
4555                                       kind, [&] (offset_type idx)
4556     {
4557       dw2_expand_marked_cus (index, idx, objfile, file_matcher,
4558                              expansion_notify, kind);
4559     });
4560 }
4561
4562 /* A helper for dw2_find_pc_sect_compunit_symtab which finds the most specific
4563    symtab.  */
4564
4565 static struct compunit_symtab *
4566 recursively_find_pc_sect_compunit_symtab (struct compunit_symtab *cust,
4567                                           CORE_ADDR pc)
4568 {
4569   int i;
4570
4571   if (COMPUNIT_BLOCKVECTOR (cust) != NULL
4572       && blockvector_contains_pc (COMPUNIT_BLOCKVECTOR (cust), pc))
4573     return cust;
4574
4575   if (cust->includes == NULL)
4576     return NULL;
4577
4578   for (i = 0; cust->includes[i]; ++i)
4579     {
4580       struct compunit_symtab *s = cust->includes[i];
4581
4582       s = recursively_find_pc_sect_compunit_symtab (s, pc);
4583       if (s != NULL)
4584         return s;
4585     }
4586
4587   return NULL;
4588 }
4589
4590 static struct compunit_symtab *
4591 dw2_find_pc_sect_compunit_symtab (struct objfile *objfile,
4592                                   struct bound_minimal_symbol msymbol,
4593                                   CORE_ADDR pc,
4594                                   struct obj_section *section,
4595                                   int warn_if_readin)
4596 {
4597   struct dwarf2_per_cu_data *data;
4598   struct compunit_symtab *result;
4599
4600   dw2_setup (objfile);
4601
4602   if (!objfile->psymtabs_addrmap)
4603     return NULL;
4604
4605   data = (struct dwarf2_per_cu_data *) addrmap_find (objfile->psymtabs_addrmap,
4606                                                      pc);
4607   if (!data)
4608     return NULL;
4609
4610   if (warn_if_readin && data->v.quick->compunit_symtab)
4611     warning (_("(Internal error: pc %s in read in CU, but not in symtab.)"),
4612              paddress (get_objfile_arch (objfile), pc));
4613
4614   result
4615     = recursively_find_pc_sect_compunit_symtab (dw2_instantiate_symtab (data),
4616                                                 pc);
4617   gdb_assert (result != NULL);
4618   return result;
4619 }
4620
4621 static void
4622 dw2_map_symbol_filenames (struct objfile *objfile, symbol_filename_ftype *fun,
4623                           void *data, int need_fullname)
4624 {
4625   dw2_setup (objfile);
4626
4627   if (!dwarf2_per_objfile->filenames_cache)
4628     {
4629       dwarf2_per_objfile->filenames_cache.emplace ();
4630
4631       htab_up visited (htab_create_alloc (10,
4632                                           htab_hash_pointer, htab_eq_pointer,
4633                                           NULL, xcalloc, xfree));
4634
4635       /* The rule is CUs specify all the files, including those used
4636          by any TU, so there's no need to scan TUs here.  We can
4637          ignore file names coming from already-expanded CUs.  */
4638
4639       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4640         {
4641           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4642
4643           if (per_cu->v.quick->compunit_symtab)
4644             {
4645               void **slot = htab_find_slot (visited.get (),
4646                                             per_cu->v.quick->file_names,
4647                                             INSERT);
4648
4649               *slot = per_cu->v.quick->file_names;
4650             }
4651         }
4652
4653       for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
4654         {
4655           int j;
4656           struct dwarf2_per_cu_data *per_cu = dw2_get_cu (i);
4657           struct quick_file_names *file_data;
4658           void **slot;
4659
4660           /* We only need to look at symtabs not already expanded.  */
4661           if (per_cu->v.quick->compunit_symtab)
4662             continue;
4663
4664           file_data = dw2_get_file_names (per_cu);
4665           if (file_data == NULL)
4666             continue;
4667
4668           slot = htab_find_slot (visited.get (), file_data, INSERT);
4669           if (*slot)
4670             {
4671               /* Already visited.  */
4672               continue;
4673             }
4674           *slot = file_data;
4675
4676           for (int j = 0; j < file_data->num_file_names; ++j)
4677             {
4678               const char *filename = file_data->file_names[j];
4679               dwarf2_per_objfile->filenames_cache->seen (filename);
4680             }
4681         }
4682     }
4683
4684   dwarf2_per_objfile->filenames_cache->traverse ([&] (const char *filename)
4685     {
4686       gdb::unique_xmalloc_ptr<char> this_real_name;
4687
4688       if (need_fullname)
4689         this_real_name = gdb_realpath (filename);
4690       (*fun) (filename, this_real_name.get (), data);
4691     });
4692 }
4693
4694 static int
4695 dw2_has_symbols (struct objfile *objfile)
4696 {
4697   return 1;
4698 }
4699
4700 const struct quick_symbol_functions dwarf2_gdb_index_functions =
4701 {
4702   dw2_has_symbols,
4703   dw2_find_last_source_symtab,
4704   dw2_forget_cached_source_info,
4705   dw2_map_symtabs_matching_filename,
4706   dw2_lookup_symbol,
4707   dw2_print_stats,
4708   dw2_dump,
4709   dw2_relocate,
4710   dw2_expand_symtabs_for_function,
4711   dw2_expand_all_symtabs,
4712   dw2_expand_symtabs_with_fullname,
4713   dw2_map_matching_symbols,
4714   dw2_expand_symtabs_matching,
4715   dw2_find_pc_sect_compunit_symtab,
4716   dw2_map_symbol_filenames
4717 };
4718
4719 /* Initialize for reading DWARF for this objfile.  Return 0 if this
4720    file will use psymtabs, or 1 if using the GNU index.  */
4721
4722 int
4723 dwarf2_initialize_objfile (struct objfile *objfile)
4724 {
4725   /* If we're about to read full symbols, don't bother with the
4726      indices.  In this case we also don't care if some other debug
4727      format is making psymtabs, because they are all about to be
4728      expanded anyway.  */
4729   if ((objfile->flags & OBJF_READNOW))
4730     {
4731       int i;
4732
4733       dwarf2_per_objfile->using_index = 1;
4734       create_all_comp_units (objfile);
4735       create_all_type_units (objfile);
4736       dwarf2_per_objfile->quick_file_names_table =
4737         create_quick_file_names_table (dwarf2_per_objfile->n_comp_units);
4738
4739       for (i = 0; i < (dwarf2_per_objfile->n_comp_units
4740                        + dwarf2_per_objfile->n_type_units); ++i)
4741         {
4742           struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
4743
4744           per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
4745                                             struct dwarf2_per_cu_quick_data);
4746         }
4747
4748       /* Return 1 so that gdb sees the "quick" functions.  However,
4749          these functions will be no-ops because we will have expanded
4750          all symtabs.  */
4751       return 1;
4752     }
4753
4754   if (dwarf2_read_index (objfile))
4755     return 1;
4756
4757   return 0;
4758 }
4759
4760 \f
4761
4762 /* Build a partial symbol table.  */
4763
4764 void
4765 dwarf2_build_psymtabs (struct objfile *objfile)
4766 {
4767
4768   if (objfile->global_psymbols.capacity () == 0
4769       && objfile->static_psymbols.capacity () == 0)
4770     init_psymbol_list (objfile, 1024);
4771
4772   TRY
4773     {
4774       /* This isn't really ideal: all the data we allocate on the
4775          objfile's obstack is still uselessly kept around.  However,
4776          freeing it seems unsafe.  */
4777       psymtab_discarder psymtabs (objfile);
4778       dwarf2_build_psymtabs_hard (objfile);
4779       psymtabs.keep ();
4780     }
4781   CATCH (except, RETURN_MASK_ERROR)
4782     {
4783       exception_print (gdb_stderr, except);
4784     }
4785   END_CATCH
4786 }
4787
4788 /* Return the total length of the CU described by HEADER.  */
4789
4790 static unsigned int
4791 get_cu_length (const struct comp_unit_head *header)
4792 {
4793   return header->initial_length_size + header->length;
4794 }
4795
4796 /* Return TRUE if SECT_OFF is within CU_HEADER.  */
4797
4798 static inline bool
4799 offset_in_cu_p (const comp_unit_head *cu_header, sect_offset sect_off)
4800 {
4801   sect_offset bottom = cu_header->sect_off;
4802   sect_offset top = cu_header->sect_off + get_cu_length (cu_header);
4803
4804   return sect_off >= bottom && sect_off < top;
4805 }
4806
4807 /* Find the base address of the compilation unit for range lists and
4808    location lists.  It will normally be specified by DW_AT_low_pc.
4809    In DWARF-3 draft 4, the base address could be overridden by
4810    DW_AT_entry_pc.  It's been removed, but GCC still uses this for
4811    compilation units with discontinuous ranges.  */
4812
4813 static void
4814 dwarf2_find_base_address (struct die_info *die, struct dwarf2_cu *cu)
4815 {
4816   struct attribute *attr;
4817
4818   cu->base_known = 0;
4819   cu->base_address = 0;
4820
4821   attr = dwarf2_attr (die, DW_AT_entry_pc, cu);
4822   if (attr)
4823     {
4824       cu->base_address = attr_value_as_address (attr);
4825       cu->base_known = 1;
4826     }
4827   else
4828     {
4829       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
4830       if (attr)
4831         {
4832           cu->base_address = attr_value_as_address (attr);
4833           cu->base_known = 1;
4834         }
4835     }
4836 }
4837
4838 /* Read in the comp unit header information from the debug_info at info_ptr.
4839    Use rcuh_kind::COMPILE as the default type if not known by the caller.
4840    NOTE: This leaves members offset, first_die_offset to be filled in
4841    by the caller.  */
4842
4843 static const gdb_byte *
4844 read_comp_unit_head (struct comp_unit_head *cu_header,
4845                      const gdb_byte *info_ptr,
4846                      struct dwarf2_section_info *section,
4847                      rcuh_kind section_kind)
4848 {
4849   int signed_addr;
4850   unsigned int bytes_read;
4851   const char *filename = get_section_file_name (section);
4852   bfd *abfd = get_section_bfd_owner (section);
4853
4854   cu_header->length = read_initial_length (abfd, info_ptr, &bytes_read);
4855   cu_header->initial_length_size = bytes_read;
4856   cu_header->offset_size = (bytes_read == 4) ? 4 : 8;
4857   info_ptr += bytes_read;
4858   cu_header->version = read_2_bytes (abfd, info_ptr);
4859   info_ptr += 2;
4860   if (cu_header->version < 5)
4861     switch (section_kind)
4862       {
4863       case rcuh_kind::COMPILE:
4864         cu_header->unit_type = DW_UT_compile;
4865         break;
4866       case rcuh_kind::TYPE:
4867         cu_header->unit_type = DW_UT_type;
4868         break;
4869       default:
4870         internal_error (__FILE__, __LINE__,
4871                         _("read_comp_unit_head: invalid section_kind"));
4872       }
4873   else
4874     {
4875       cu_header->unit_type = static_cast<enum dwarf_unit_type>
4876                                                  (read_1_byte (abfd, info_ptr));
4877       info_ptr += 1;
4878       switch (cu_header->unit_type)
4879         {
4880         case DW_UT_compile:
4881           if (section_kind != rcuh_kind::COMPILE)
4882             error (_("Dwarf Error: wrong unit_type in compilation unit header "
4883                    "(is DW_UT_compile, should be DW_UT_type) [in module %s]"),
4884                    filename);
4885           break;
4886         case DW_UT_type:
4887           section_kind = rcuh_kind::TYPE;
4888           break;
4889         default:
4890           error (_("Dwarf Error: wrong unit_type in compilation unit header "
4891                  "(is %d, should be %d or %d) [in module %s]"),
4892                  cu_header->unit_type, DW_UT_compile, DW_UT_type, filename);
4893         }
4894
4895       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4896       info_ptr += 1;
4897     }
4898   cu_header->abbrev_sect_off = (sect_offset) read_offset (abfd, info_ptr,
4899                                                           cu_header,
4900                                                           &bytes_read);
4901   info_ptr += bytes_read;
4902   if (cu_header->version < 5)
4903     {
4904       cu_header->addr_size = read_1_byte (abfd, info_ptr);
4905       info_ptr += 1;
4906     }
4907   signed_addr = bfd_get_sign_extend_vma (abfd);
4908   if (signed_addr < 0)
4909     internal_error (__FILE__, __LINE__,
4910                     _("read_comp_unit_head: dwarf from non elf file"));
4911   cu_header->signed_addr_p = signed_addr;
4912
4913   if (section_kind == rcuh_kind::TYPE)
4914     {
4915       LONGEST type_offset;
4916
4917       cu_header->signature = read_8_bytes (abfd, info_ptr);
4918       info_ptr += 8;
4919
4920       type_offset = read_offset (abfd, info_ptr, cu_header, &bytes_read);
4921       info_ptr += bytes_read;
4922       cu_header->type_cu_offset_in_tu = (cu_offset) type_offset;
4923       if (to_underlying (cu_header->type_cu_offset_in_tu) != type_offset)
4924         error (_("Dwarf Error: Too big type_offset in compilation unit "
4925                "header (is %s) [in module %s]"), plongest (type_offset),
4926                filename);
4927     }
4928
4929   return info_ptr;
4930 }
4931
4932 /* Helper function that returns the proper abbrev section for
4933    THIS_CU.  */
4934
4935 static struct dwarf2_section_info *
4936 get_abbrev_section_for_cu (struct dwarf2_per_cu_data *this_cu)
4937 {
4938   struct dwarf2_section_info *abbrev;
4939
4940   if (this_cu->is_dwz)
4941     abbrev = &dwarf2_get_dwz_file ()->abbrev;
4942   else
4943     abbrev = &dwarf2_per_objfile->abbrev;
4944
4945   return abbrev;
4946 }
4947
4948 /* Subroutine of read_and_check_comp_unit_head and
4949    read_and_check_type_unit_head to simplify them.
4950    Perform various error checking on the header.  */
4951
4952 static void
4953 error_check_comp_unit_head (struct comp_unit_head *header,
4954                             struct dwarf2_section_info *section,
4955                             struct dwarf2_section_info *abbrev_section)
4956 {
4957   const char *filename = get_section_file_name (section);
4958
4959   if (header->version < 2 || header->version > 5)
4960     error (_("Dwarf Error: wrong version in compilation unit header "
4961            "(is %d, should be 2, 3, 4 or 5) [in module %s]"), header->version,
4962            filename);
4963
4964   if (to_underlying (header->abbrev_sect_off)
4965       >= dwarf2_section_size (dwarf2_per_objfile->objfile, abbrev_section))
4966     error (_("Dwarf Error: bad offset (0x%x) in compilation unit header "
4967            "(offset 0x%x + 6) [in module %s]"),
4968            to_underlying (header->abbrev_sect_off),
4969            to_underlying (header->sect_off),
4970            filename);
4971
4972   /* Cast to ULONGEST to use 64-bit arithmetic when possible to
4973      avoid potential 32-bit overflow.  */
4974   if (((ULONGEST) header->sect_off + get_cu_length (header))
4975       > section->size)
4976     error (_("Dwarf Error: bad length (0x%x) in compilation unit header "
4977            "(offset 0x%x + 0) [in module %s]"),
4978            header->length, to_underlying (header->sect_off),
4979            filename);
4980 }
4981
4982 /* Read in a CU/TU header and perform some basic error checking.
4983    The contents of the header are stored in HEADER.
4984    The result is a pointer to the start of the first DIE.  */
4985
4986 static const gdb_byte *
4987 read_and_check_comp_unit_head (struct comp_unit_head *header,
4988                                struct dwarf2_section_info *section,
4989                                struct dwarf2_section_info *abbrev_section,
4990                                const gdb_byte *info_ptr,
4991                                rcuh_kind section_kind)
4992 {
4993   const gdb_byte *beg_of_comp_unit = info_ptr;
4994   bfd *abfd = get_section_bfd_owner (section);
4995
4996   header->sect_off = (sect_offset) (beg_of_comp_unit - section->buffer);
4997
4998   info_ptr = read_comp_unit_head (header, info_ptr, section, section_kind);
4999
5000   header->first_die_cu_offset = (cu_offset) (info_ptr - beg_of_comp_unit);
5001
5002   error_check_comp_unit_head (header, section, abbrev_section);
5003
5004   return info_ptr;
5005 }
5006
5007 /* Fetch the abbreviation table offset from a comp or type unit header.  */
5008
5009 static sect_offset
5010 read_abbrev_offset (struct dwarf2_section_info *section,
5011                     sect_offset sect_off)
5012 {
5013   bfd *abfd = get_section_bfd_owner (section);
5014   const gdb_byte *info_ptr;
5015   unsigned int initial_length_size, offset_size;
5016   uint16_t version;
5017
5018   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
5019   info_ptr = section->buffer + to_underlying (sect_off);
5020   read_initial_length (abfd, info_ptr, &initial_length_size);
5021   offset_size = initial_length_size == 4 ? 4 : 8;
5022   info_ptr += initial_length_size;
5023
5024   version = read_2_bytes (abfd, info_ptr);
5025   info_ptr += 2;
5026   if (version >= 5)
5027     {
5028       /* Skip unit type and address size.  */
5029       info_ptr += 2;
5030     }
5031
5032   return (sect_offset) read_offset_1 (abfd, info_ptr, offset_size);
5033 }
5034
5035 /* Allocate a new partial symtab for file named NAME and mark this new
5036    partial symtab as being an include of PST.  */
5037
5038 static void
5039 dwarf2_create_include_psymtab (const char *name, struct partial_symtab *pst,
5040                                struct objfile *objfile)
5041 {
5042   struct partial_symtab *subpst = allocate_psymtab (name, objfile);
5043
5044   if (!IS_ABSOLUTE_PATH (subpst->filename))
5045     {
5046       /* It shares objfile->objfile_obstack.  */
5047       subpst->dirname = pst->dirname;
5048     }
5049
5050   subpst->textlow = 0;
5051   subpst->texthigh = 0;
5052
5053   subpst->dependencies
5054     = XOBNEW (&objfile->objfile_obstack, struct partial_symtab *);
5055   subpst->dependencies[0] = pst;
5056   subpst->number_of_dependencies = 1;
5057
5058   subpst->globals_offset = 0;
5059   subpst->n_global_syms = 0;
5060   subpst->statics_offset = 0;
5061   subpst->n_static_syms = 0;
5062   subpst->compunit_symtab = NULL;
5063   subpst->read_symtab = pst->read_symtab;
5064   subpst->readin = 0;
5065
5066   /* No private part is necessary for include psymtabs.  This property
5067      can be used to differentiate between such include psymtabs and
5068      the regular ones.  */
5069   subpst->read_symtab_private = NULL;
5070 }
5071
5072 /* Read the Line Number Program data and extract the list of files
5073    included by the source file represented by PST.  Build an include
5074    partial symtab for each of these included files.  */
5075
5076 static void
5077 dwarf2_build_include_psymtabs (struct dwarf2_cu *cu,
5078                                struct die_info *die,
5079                                struct partial_symtab *pst)
5080 {
5081   line_header_up lh;
5082   struct attribute *attr;
5083
5084   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
5085   if (attr)
5086     lh = dwarf_decode_line_header ((sect_offset) DW_UNSND (attr), cu);
5087   if (lh == NULL)
5088     return;  /* No linetable, so no includes.  */
5089
5090   /* NOTE: pst->dirname is DW_AT_comp_dir (if present).  */
5091   dwarf_decode_lines (lh.get (), pst->dirname, cu, pst, pst->textlow, 1);
5092 }
5093
5094 static hashval_t
5095 hash_signatured_type (const void *item)
5096 {
5097   const struct signatured_type *sig_type
5098     = (const struct signatured_type *) item;
5099
5100   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
5101   return sig_type->signature;
5102 }
5103
5104 static int
5105 eq_signatured_type (const void *item_lhs, const void *item_rhs)
5106 {
5107   const struct signatured_type *lhs = (const struct signatured_type *) item_lhs;
5108   const struct signatured_type *rhs = (const struct signatured_type *) item_rhs;
5109
5110   return lhs->signature == rhs->signature;
5111 }
5112
5113 /* Allocate a hash table for signatured types.  */
5114
5115 static htab_t
5116 allocate_signatured_type_table (struct objfile *objfile)
5117 {
5118   return htab_create_alloc_ex (41,
5119                                hash_signatured_type,
5120                                eq_signatured_type,
5121                                NULL,
5122                                &objfile->objfile_obstack,
5123                                hashtab_obstack_allocate,
5124                                dummy_obstack_deallocate);
5125 }
5126
5127 /* A helper function to add a signatured type CU to a table.  */
5128
5129 static int
5130 add_signatured_type_cu_to_table (void **slot, void *datum)
5131 {
5132   struct signatured_type *sigt = (struct signatured_type *) *slot;
5133   struct signatured_type ***datap = (struct signatured_type ***) datum;
5134
5135   **datap = sigt;
5136   ++*datap;
5137
5138   return 1;
5139 }
5140
5141 /* A helper for create_debug_types_hash_table.  Read types from SECTION
5142    and fill them into TYPES_HTAB.  It will process only type units,
5143    therefore DW_UT_type.  */
5144
5145 static void
5146 create_debug_type_hash_table (struct dwo_file *dwo_file,
5147                               dwarf2_section_info *section, htab_t &types_htab,
5148                               rcuh_kind section_kind)
5149 {
5150   struct objfile *objfile = dwarf2_per_objfile->objfile;
5151   struct dwarf2_section_info *abbrev_section;
5152   bfd *abfd;
5153   const gdb_byte *info_ptr, *end_ptr;
5154
5155   abbrev_section = (dwo_file != NULL
5156                     ? &dwo_file->sections.abbrev
5157                     : &dwarf2_per_objfile->abbrev);
5158
5159   if (dwarf_read_debug)
5160     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
5161                         get_section_name (section),
5162                         get_section_file_name (abbrev_section));
5163
5164   dwarf2_read_section (objfile, section);
5165   info_ptr = section->buffer;
5166
5167   if (info_ptr == NULL)
5168     return;
5169
5170   /* We can't set abfd until now because the section may be empty or
5171      not present, in which case the bfd is unknown.  */
5172   abfd = get_section_bfd_owner (section);
5173
5174   /* We don't use init_cutu_and_read_dies_simple, or some such, here
5175      because we don't need to read any dies: the signature is in the
5176      header.  */
5177
5178   end_ptr = info_ptr + section->size;
5179   while (info_ptr < end_ptr)
5180     {
5181       struct signatured_type *sig_type;
5182       struct dwo_unit *dwo_tu;
5183       void **slot;
5184       const gdb_byte *ptr = info_ptr;
5185       struct comp_unit_head header;
5186       unsigned int length;
5187
5188       sect_offset sect_off = (sect_offset) (ptr - section->buffer);
5189
5190       /* Initialize it due to a false compiler warning.  */
5191       header.signature = -1;
5192       header.type_cu_offset_in_tu = (cu_offset) -1;
5193
5194       /* We need to read the type's signature in order to build the hash
5195          table, but we don't need anything else just yet.  */
5196
5197       ptr = read_and_check_comp_unit_head (&header, section,
5198                                            abbrev_section, ptr, section_kind);
5199
5200       length = get_cu_length (&header);
5201
5202       /* Skip dummy type units.  */
5203       if (ptr >= info_ptr + length
5204           || peek_abbrev_code (abfd, ptr) == 0
5205           || header.unit_type != DW_UT_type)
5206         {
5207           info_ptr += length;
5208           continue;
5209         }
5210
5211       if (types_htab == NULL)
5212         {
5213           if (dwo_file)
5214             types_htab = allocate_dwo_unit_table (objfile);
5215           else
5216             types_htab = allocate_signatured_type_table (objfile);
5217         }
5218
5219       if (dwo_file)
5220         {
5221           sig_type = NULL;
5222           dwo_tu = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5223                                    struct dwo_unit);
5224           dwo_tu->dwo_file = dwo_file;
5225           dwo_tu->signature = header.signature;
5226           dwo_tu->type_offset_in_tu = header.type_cu_offset_in_tu;
5227           dwo_tu->section = section;
5228           dwo_tu->sect_off = sect_off;
5229           dwo_tu->length = length;
5230         }
5231       else
5232         {
5233           /* N.B.: type_offset is not usable if this type uses a DWO file.
5234              The real type_offset is in the DWO file.  */
5235           dwo_tu = NULL;
5236           sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5237                                      struct signatured_type);
5238           sig_type->signature = header.signature;
5239           sig_type->type_offset_in_tu = header.type_cu_offset_in_tu;
5240           sig_type->per_cu.objfile = objfile;
5241           sig_type->per_cu.is_debug_types = 1;
5242           sig_type->per_cu.section = section;
5243           sig_type->per_cu.sect_off = sect_off;
5244           sig_type->per_cu.length = length;
5245         }
5246
5247       slot = htab_find_slot (types_htab,
5248                              dwo_file ? (void*) dwo_tu : (void *) sig_type,
5249                              INSERT);
5250       gdb_assert (slot != NULL);
5251       if (*slot != NULL)
5252         {
5253           sect_offset dup_sect_off;
5254
5255           if (dwo_file)
5256             {
5257               const struct dwo_unit *dup_tu
5258                 = (const struct dwo_unit *) *slot;
5259
5260               dup_sect_off = dup_tu->sect_off;
5261             }
5262           else
5263             {
5264               const struct signatured_type *dup_tu
5265                 = (const struct signatured_type *) *slot;
5266
5267               dup_sect_off = dup_tu->per_cu.sect_off;
5268             }
5269
5270           complaint (&symfile_complaints,
5271                      _("debug type entry at offset 0x%x is duplicate to"
5272                        " the entry at offset 0x%x, signature %s"),
5273                      to_underlying (sect_off), to_underlying (dup_sect_off),
5274                      hex_string (header.signature));
5275         }
5276       *slot = dwo_file ? (void *) dwo_tu : (void *) sig_type;
5277
5278       if (dwarf_read_debug > 1)
5279         fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, signature %s\n",
5280                             to_underlying (sect_off),
5281                             hex_string (header.signature));
5282
5283       info_ptr += length;
5284     }
5285 }
5286
5287 /* Create the hash table of all entries in the .debug_types
5288    (or .debug_types.dwo) section(s).
5289    If reading a DWO file, then DWO_FILE is a pointer to the DWO file object,
5290    otherwise it is NULL.
5291
5292    The result is a pointer to the hash table or NULL if there are no types.
5293
5294    Note: This function processes DWO files only, not DWP files.  */
5295
5296 static void
5297 create_debug_types_hash_table (struct dwo_file *dwo_file,
5298                                VEC (dwarf2_section_info_def) *types,
5299                                htab_t &types_htab)
5300 {
5301   int ix;
5302   struct dwarf2_section_info *section;
5303
5304   if (VEC_empty (dwarf2_section_info_def, types))
5305     return;
5306
5307   for (ix = 0;
5308        VEC_iterate (dwarf2_section_info_def, types, ix, section);
5309        ++ix)
5310     create_debug_type_hash_table (dwo_file, section, types_htab,
5311                                   rcuh_kind::TYPE);
5312 }
5313
5314 /* Create the hash table of all entries in the .debug_types section,
5315    and initialize all_type_units.
5316    The result is zero if there is an error (e.g. missing .debug_types section),
5317    otherwise non-zero.  */
5318
5319 static int
5320 create_all_type_units (struct objfile *objfile)
5321 {
5322   htab_t types_htab = NULL;
5323   struct signatured_type **iter;
5324
5325   create_debug_type_hash_table (NULL, &dwarf2_per_objfile->info, types_htab,
5326                                 rcuh_kind::COMPILE);
5327   create_debug_types_hash_table (NULL, dwarf2_per_objfile->types, types_htab);
5328   if (types_htab == NULL)
5329     {
5330       dwarf2_per_objfile->signatured_types = NULL;
5331       return 0;
5332     }
5333
5334   dwarf2_per_objfile->signatured_types = types_htab;
5335
5336   dwarf2_per_objfile->n_type_units
5337     = dwarf2_per_objfile->n_allocated_type_units
5338     = htab_elements (types_htab);
5339   dwarf2_per_objfile->all_type_units =
5340     XNEWVEC (struct signatured_type *, dwarf2_per_objfile->n_type_units);
5341   iter = &dwarf2_per_objfile->all_type_units[0];
5342   htab_traverse_noresize (types_htab, add_signatured_type_cu_to_table, &iter);
5343   gdb_assert (iter - &dwarf2_per_objfile->all_type_units[0]
5344               == dwarf2_per_objfile->n_type_units);
5345
5346   return 1;
5347 }
5348
5349 /* Add an entry for signature SIG to dwarf2_per_objfile->signatured_types.
5350    If SLOT is non-NULL, it is the entry to use in the hash table.
5351    Otherwise we find one.  */
5352
5353 static struct signatured_type *
5354 add_type_unit (ULONGEST sig, void **slot)
5355 {
5356   struct objfile *objfile = dwarf2_per_objfile->objfile;
5357   int n_type_units = dwarf2_per_objfile->n_type_units;
5358   struct signatured_type *sig_type;
5359
5360   gdb_assert (n_type_units <= dwarf2_per_objfile->n_allocated_type_units);
5361   ++n_type_units;
5362   if (n_type_units > dwarf2_per_objfile->n_allocated_type_units)
5363     {
5364       if (dwarf2_per_objfile->n_allocated_type_units == 0)
5365         dwarf2_per_objfile->n_allocated_type_units = 1;
5366       dwarf2_per_objfile->n_allocated_type_units *= 2;
5367       dwarf2_per_objfile->all_type_units
5368         = XRESIZEVEC (struct signatured_type *,
5369                       dwarf2_per_objfile->all_type_units,
5370                       dwarf2_per_objfile->n_allocated_type_units);
5371       ++dwarf2_per_objfile->tu_stats.nr_all_type_units_reallocs;
5372     }
5373   dwarf2_per_objfile->n_type_units = n_type_units;
5374
5375   sig_type = OBSTACK_ZALLOC (&objfile->objfile_obstack,
5376                              struct signatured_type);
5377   dwarf2_per_objfile->all_type_units[n_type_units - 1] = sig_type;
5378   sig_type->signature = sig;
5379   sig_type->per_cu.is_debug_types = 1;
5380   if (dwarf2_per_objfile->using_index)
5381     {
5382       sig_type->per_cu.v.quick =
5383         OBSTACK_ZALLOC (&objfile->objfile_obstack,
5384                         struct dwarf2_per_cu_quick_data);
5385     }
5386
5387   if (slot == NULL)
5388     {
5389       slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5390                              sig_type, INSERT);
5391     }
5392   gdb_assert (*slot == NULL);
5393   *slot = sig_type;
5394   /* The rest of sig_type must be filled in by the caller.  */
5395   return sig_type;
5396 }
5397
5398 /* Subroutine of lookup_dwo_signatured_type and lookup_dwp_signatured_type.
5399    Fill in SIG_ENTRY with DWO_ENTRY.  */
5400
5401 static void
5402 fill_in_sig_entry_from_dwo_entry (struct objfile *objfile,
5403                                   struct signatured_type *sig_entry,
5404                                   struct dwo_unit *dwo_entry)
5405 {
5406   /* Make sure we're not clobbering something we don't expect to.  */
5407   gdb_assert (! sig_entry->per_cu.queued);
5408   gdb_assert (sig_entry->per_cu.cu == NULL);
5409   if (dwarf2_per_objfile->using_index)
5410     {
5411       gdb_assert (sig_entry->per_cu.v.quick != NULL);
5412       gdb_assert (sig_entry->per_cu.v.quick->compunit_symtab == NULL);
5413     }
5414   else
5415       gdb_assert (sig_entry->per_cu.v.psymtab == NULL);
5416   gdb_assert (sig_entry->signature == dwo_entry->signature);
5417   gdb_assert (to_underlying (sig_entry->type_offset_in_section) == 0);
5418   gdb_assert (sig_entry->type_unit_group == NULL);
5419   gdb_assert (sig_entry->dwo_unit == NULL);
5420
5421   sig_entry->per_cu.section = dwo_entry->section;
5422   sig_entry->per_cu.sect_off = dwo_entry->sect_off;
5423   sig_entry->per_cu.length = dwo_entry->length;
5424   sig_entry->per_cu.reading_dwo_directly = 1;
5425   sig_entry->per_cu.objfile = objfile;
5426   sig_entry->type_offset_in_tu = dwo_entry->type_offset_in_tu;
5427   sig_entry->dwo_unit = dwo_entry;
5428 }
5429
5430 /* Subroutine of lookup_signatured_type.
5431    If we haven't read the TU yet, create the signatured_type data structure
5432    for a TU to be read in directly from a DWO file, bypassing the stub.
5433    This is the "Stay in DWO Optimization": When there is no DWP file and we're
5434    using .gdb_index, then when reading a CU we want to stay in the DWO file
5435    containing that CU.  Otherwise we could end up reading several other DWO
5436    files (due to comdat folding) to process the transitive closure of all the
5437    mentioned TUs, and that can be slow.  The current DWO file will have every
5438    type signature that it needs.
5439    We only do this for .gdb_index because in the psymtab case we already have
5440    to read all the DWOs to build the type unit groups.  */
5441
5442 static struct signatured_type *
5443 lookup_dwo_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5444 {
5445   struct objfile *objfile = dwarf2_per_objfile->objfile;
5446   struct dwo_file *dwo_file;
5447   struct dwo_unit find_dwo_entry, *dwo_entry;
5448   struct signatured_type find_sig_entry, *sig_entry;
5449   void **slot;
5450
5451   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5452
5453   /* If TU skeletons have been removed then we may not have read in any
5454      TUs yet.  */
5455   if (dwarf2_per_objfile->signatured_types == NULL)
5456     {
5457       dwarf2_per_objfile->signatured_types
5458         = allocate_signatured_type_table (objfile);
5459     }
5460
5461   /* We only ever need to read in one copy of a signatured type.
5462      Use the global signatured_types array to do our own comdat-folding
5463      of types.  If this is the first time we're reading this TU, and
5464      the TU has an entry in .gdb_index, replace the recorded data from
5465      .gdb_index with this TU.  */
5466
5467   find_sig_entry.signature = sig;
5468   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5469                          &find_sig_entry, INSERT);
5470   sig_entry = (struct signatured_type *) *slot;
5471
5472   /* We can get here with the TU already read, *or* in the process of being
5473      read.  Don't reassign the global entry to point to this DWO if that's
5474      the case.  Also note that if the TU is already being read, it may not
5475      have come from a DWO, the program may be a mix of Fission-compiled
5476      code and non-Fission-compiled code.  */
5477
5478   /* Have we already tried to read this TU?
5479      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5480      needn't exist in the global table yet).  */
5481   if (sig_entry != NULL && sig_entry->per_cu.tu_read)
5482     return sig_entry;
5483
5484   /* Note: cu->dwo_unit is the dwo_unit that references this TU, not the
5485      dwo_unit of the TU itself.  */
5486   dwo_file = cu->dwo_unit->dwo_file;
5487
5488   /* Ok, this is the first time we're reading this TU.  */
5489   if (dwo_file->tus == NULL)
5490     return NULL;
5491   find_dwo_entry.signature = sig;
5492   dwo_entry = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_entry);
5493   if (dwo_entry == NULL)
5494     return NULL;
5495
5496   /* If the global table doesn't have an entry for this TU, add one.  */
5497   if (sig_entry == NULL)
5498     sig_entry = add_type_unit (sig, slot);
5499
5500   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5501   sig_entry->per_cu.tu_read = 1;
5502   return sig_entry;
5503 }
5504
5505 /* Subroutine of lookup_signatured_type.
5506    Look up the type for signature SIG, and if we can't find SIG in .gdb_index
5507    then try the DWP file.  If the TU stub (skeleton) has been removed then
5508    it won't be in .gdb_index.  */
5509
5510 static struct signatured_type *
5511 lookup_dwp_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5512 {
5513   struct objfile *objfile = dwarf2_per_objfile->objfile;
5514   struct dwp_file *dwp_file = get_dwp_file ();
5515   struct dwo_unit *dwo_entry;
5516   struct signatured_type find_sig_entry, *sig_entry;
5517   void **slot;
5518
5519   gdb_assert (cu->dwo_unit && dwarf2_per_objfile->using_index);
5520   gdb_assert (dwp_file != NULL);
5521
5522   /* If TU skeletons have been removed then we may not have read in any
5523      TUs yet.  */
5524   if (dwarf2_per_objfile->signatured_types == NULL)
5525     {
5526       dwarf2_per_objfile->signatured_types
5527         = allocate_signatured_type_table (objfile);
5528     }
5529
5530   find_sig_entry.signature = sig;
5531   slot = htab_find_slot (dwarf2_per_objfile->signatured_types,
5532                          &find_sig_entry, INSERT);
5533   sig_entry = (struct signatured_type *) *slot;
5534
5535   /* Have we already tried to read this TU?
5536      Note: sig_entry can be NULL if the skeleton TU was removed (thus it
5537      needn't exist in the global table yet).  */
5538   if (sig_entry != NULL)
5539     return sig_entry;
5540
5541   if (dwp_file->tus == NULL)
5542     return NULL;
5543   dwo_entry = lookup_dwo_unit_in_dwp (dwp_file, NULL,
5544                                       sig, 1 /* is_debug_types */);
5545   if (dwo_entry == NULL)
5546     return NULL;
5547
5548   sig_entry = add_type_unit (sig, slot);
5549   fill_in_sig_entry_from_dwo_entry (objfile, sig_entry, dwo_entry);
5550
5551   return sig_entry;
5552 }
5553
5554 /* Lookup a signature based type for DW_FORM_ref_sig8.
5555    Returns NULL if signature SIG is not present in the table.
5556    It is up to the caller to complain about this.  */
5557
5558 static struct signatured_type *
5559 lookup_signatured_type (struct dwarf2_cu *cu, ULONGEST sig)
5560 {
5561   if (cu->dwo_unit
5562       && dwarf2_per_objfile->using_index)
5563     {
5564       /* We're in a DWO/DWP file, and we're using .gdb_index.
5565          These cases require special processing.  */
5566       if (get_dwp_file () == NULL)
5567         return lookup_dwo_signatured_type (cu, sig);
5568       else
5569         return lookup_dwp_signatured_type (cu, sig);
5570     }
5571   else
5572     {
5573       struct signatured_type find_entry, *entry;
5574
5575       if (dwarf2_per_objfile->signatured_types == NULL)
5576         return NULL;
5577       find_entry.signature = sig;
5578       entry = ((struct signatured_type *)
5579                htab_find (dwarf2_per_objfile->signatured_types, &find_entry));
5580       return entry;
5581     }
5582 }
5583 \f
5584 /* Low level DIE reading support.  */
5585
5586 /* Initialize a die_reader_specs struct from a dwarf2_cu struct.  */
5587
5588 static void
5589 init_cu_die_reader (struct die_reader_specs *reader,
5590                     struct dwarf2_cu *cu,
5591                     struct dwarf2_section_info *section,
5592                     struct dwo_file *dwo_file)
5593 {
5594   gdb_assert (section->readin && section->buffer != NULL);
5595   reader->abfd = get_section_bfd_owner (section);
5596   reader->cu = cu;
5597   reader->dwo_file = dwo_file;
5598   reader->die_section = section;
5599   reader->buffer = section->buffer;
5600   reader->buffer_end = section->buffer + section->size;
5601   reader->comp_dir = NULL;
5602 }
5603
5604 /* Subroutine of init_cutu_and_read_dies to simplify it.
5605    Read in the rest of a CU/TU top level DIE from DWO_UNIT.
5606    There's just a lot of work to do, and init_cutu_and_read_dies is big enough
5607    already.
5608
5609    STUB_COMP_UNIT_DIE is for the stub DIE, we copy over certain attributes
5610    from it to the DIE in the DWO.  If NULL we are skipping the stub.
5611    STUB_COMP_DIR is similar to STUB_COMP_UNIT_DIE: When reading a TU directly
5612    from the DWO file, bypassing the stub, it contains the DW_AT_comp_dir
5613    attribute of the referencing CU.  At most one of STUB_COMP_UNIT_DIE and
5614    STUB_COMP_DIR may be non-NULL.
5615    *RESULT_READER,*RESULT_INFO_PTR,*RESULT_COMP_UNIT_DIE,*RESULT_HAS_CHILDREN
5616    are filled in with the info of the DIE from the DWO file.
5617    ABBREV_TABLE_PROVIDED is non-zero if the caller of init_cutu_and_read_dies
5618    provided an abbrev table to use.
5619    The result is non-zero if a valid (non-dummy) DIE was found.  */
5620
5621 static int
5622 read_cutu_die_from_dwo (struct dwarf2_per_cu_data *this_cu,
5623                         struct dwo_unit *dwo_unit,
5624                         int abbrev_table_provided,
5625                         struct die_info *stub_comp_unit_die,
5626                         const char *stub_comp_dir,
5627                         struct die_reader_specs *result_reader,
5628                         const gdb_byte **result_info_ptr,
5629                         struct die_info **result_comp_unit_die,
5630                         int *result_has_children)
5631 {
5632   struct objfile *objfile = dwarf2_per_objfile->objfile;
5633   struct dwarf2_cu *cu = this_cu->cu;
5634   struct dwarf2_section_info *section;
5635   bfd *abfd;
5636   const gdb_byte *begin_info_ptr, *info_ptr;
5637   ULONGEST signature; /* Or dwo_id.  */
5638   struct attribute *comp_dir, *stmt_list, *low_pc, *high_pc, *ranges;
5639   int i,num_extra_attrs;
5640   struct dwarf2_section_info *dwo_abbrev_section;
5641   struct attribute *attr;
5642   struct die_info *comp_unit_die;
5643
5644   /* At most one of these may be provided.  */
5645   gdb_assert ((stub_comp_unit_die != NULL) + (stub_comp_dir != NULL) <= 1);
5646
5647   /* These attributes aren't processed until later:
5648      DW_AT_stmt_list, DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges.
5649      DW_AT_comp_dir is used now, to find the DWO file, but it is also
5650      referenced later.  However, these attributes are found in the stub
5651      which we won't have later.  In order to not impose this complication
5652      on the rest of the code, we read them here and copy them to the
5653      DWO CU/TU die.  */
5654
5655   stmt_list = NULL;
5656   low_pc = NULL;
5657   high_pc = NULL;
5658   ranges = NULL;
5659   comp_dir = NULL;
5660
5661   if (stub_comp_unit_die != NULL)
5662     {
5663       /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
5664          DWO file.  */
5665       if (! this_cu->is_debug_types)
5666         stmt_list = dwarf2_attr (stub_comp_unit_die, DW_AT_stmt_list, cu);
5667       low_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_low_pc, cu);
5668       high_pc = dwarf2_attr (stub_comp_unit_die, DW_AT_high_pc, cu);
5669       ranges = dwarf2_attr (stub_comp_unit_die, DW_AT_ranges, cu);
5670       comp_dir = dwarf2_attr (stub_comp_unit_die, DW_AT_comp_dir, cu);
5671
5672       /* There should be a DW_AT_addr_base attribute here (if needed).
5673          We need the value before we can process DW_FORM_GNU_addr_index.  */
5674       cu->addr_base = 0;
5675       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_addr_base, cu);
5676       if (attr)
5677         cu->addr_base = DW_UNSND (attr);
5678
5679       /* There should be a DW_AT_ranges_base attribute here (if needed).
5680          We need the value before we can process DW_AT_ranges.  */
5681       cu->ranges_base = 0;
5682       attr = dwarf2_attr (stub_comp_unit_die, DW_AT_GNU_ranges_base, cu);
5683       if (attr)
5684         cu->ranges_base = DW_UNSND (attr);
5685     }
5686   else if (stub_comp_dir != NULL)
5687     {
5688       /* Reconstruct the comp_dir attribute to simplify the code below.  */
5689       comp_dir = XOBNEW (&cu->comp_unit_obstack, struct attribute);
5690       comp_dir->name = DW_AT_comp_dir;
5691       comp_dir->form = DW_FORM_string;
5692       DW_STRING_IS_CANONICAL (comp_dir) = 0;
5693       DW_STRING (comp_dir) = stub_comp_dir;
5694     }
5695
5696   /* Set up for reading the DWO CU/TU.  */
5697   cu->dwo_unit = dwo_unit;
5698   section = dwo_unit->section;
5699   dwarf2_read_section (objfile, section);
5700   abfd = get_section_bfd_owner (section);
5701   begin_info_ptr = info_ptr = (section->buffer
5702                                + to_underlying (dwo_unit->sect_off));
5703   dwo_abbrev_section = &dwo_unit->dwo_file->sections.abbrev;
5704   init_cu_die_reader (result_reader, cu, section, dwo_unit->dwo_file);
5705
5706   if (this_cu->is_debug_types)
5707     {
5708       struct signatured_type *sig_type = (struct signatured_type *) this_cu;
5709
5710       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5711                                                 dwo_abbrev_section,
5712                                                 info_ptr, rcuh_kind::TYPE);
5713       /* This is not an assert because it can be caused by bad debug info.  */
5714       if (sig_type->signature != cu->header.signature)
5715         {
5716           error (_("Dwarf Error: signature mismatch %s vs %s while reading"
5717                    " TU at offset 0x%x [in module %s]"),
5718                  hex_string (sig_type->signature),
5719                  hex_string (cu->header.signature),
5720                  to_underlying (dwo_unit->sect_off),
5721                  bfd_get_filename (abfd));
5722         }
5723       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5724       /* For DWOs coming from DWP files, we don't know the CU length
5725          nor the type's offset in the TU until now.  */
5726       dwo_unit->length = get_cu_length (&cu->header);
5727       dwo_unit->type_offset_in_tu = cu->header.type_cu_offset_in_tu;
5728
5729       /* Establish the type offset that can be used to lookup the type.
5730          For DWO files, we don't know it until now.  */
5731       sig_type->type_offset_in_section
5732         = dwo_unit->sect_off + to_underlying (dwo_unit->type_offset_in_tu);
5733     }
5734   else
5735     {
5736       info_ptr = read_and_check_comp_unit_head (&cu->header, section,
5737                                                 dwo_abbrev_section,
5738                                                 info_ptr, rcuh_kind::COMPILE);
5739       gdb_assert (dwo_unit->sect_off == cu->header.sect_off);
5740       /* For DWOs coming from DWP files, we don't know the CU length
5741          until now.  */
5742       dwo_unit->length = get_cu_length (&cu->header);
5743     }
5744
5745   /* Replace the CU's original abbrev table with the DWO's.
5746      Reminder: We can't read the abbrev table until we've read the header.  */
5747   if (abbrev_table_provided)
5748     {
5749       /* Don't free the provided abbrev table, the caller of
5750          init_cutu_and_read_dies owns it.  */
5751       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5752       /* Ensure the DWO abbrev table gets freed.  */
5753       make_cleanup (dwarf2_free_abbrev_table, cu);
5754     }
5755   else
5756     {
5757       dwarf2_free_abbrev_table (cu);
5758       dwarf2_read_abbrevs (cu, dwo_abbrev_section);
5759       /* Leave any existing abbrev table cleanup as is.  */
5760     }
5761
5762   /* Read in the die, but leave space to copy over the attributes
5763      from the stub.  This has the benefit of simplifying the rest of
5764      the code - all the work to maintain the illusion of a single
5765      DW_TAG_{compile,type}_unit DIE is done here.  */
5766   num_extra_attrs = ((stmt_list != NULL)
5767                      + (low_pc != NULL)
5768                      + (high_pc != NULL)
5769                      + (ranges != NULL)
5770                      + (comp_dir != NULL));
5771   info_ptr = read_full_die_1 (result_reader, result_comp_unit_die, info_ptr,
5772                               result_has_children, num_extra_attrs);
5773
5774   /* Copy over the attributes from the stub to the DIE we just read in.  */
5775   comp_unit_die = *result_comp_unit_die;
5776   i = comp_unit_die->num_attrs;
5777   if (stmt_list != NULL)
5778     comp_unit_die->attrs[i++] = *stmt_list;
5779   if (low_pc != NULL)
5780     comp_unit_die->attrs[i++] = *low_pc;
5781   if (high_pc != NULL)
5782     comp_unit_die->attrs[i++] = *high_pc;
5783   if (ranges != NULL)
5784     comp_unit_die->attrs[i++] = *ranges;
5785   if (comp_dir != NULL)
5786     comp_unit_die->attrs[i++] = *comp_dir;
5787   comp_unit_die->num_attrs += num_extra_attrs;
5788
5789   if (dwarf_die_debug)
5790     {
5791       fprintf_unfiltered (gdb_stdlog,
5792                           "Read die from %s@0x%x of %s:\n",
5793                           get_section_name (section),
5794                           (unsigned) (begin_info_ptr - section->buffer),
5795                           bfd_get_filename (abfd));
5796       dump_die (comp_unit_die, dwarf_die_debug);
5797     }
5798
5799   /* Save the comp_dir attribute.  If there is no DWP file then we'll read
5800      TUs by skipping the stub and going directly to the entry in the DWO file.
5801      However, skipping the stub means we won't get DW_AT_comp_dir, so we have
5802      to get it via circuitous means.  Blech.  */
5803   if (comp_dir != NULL)
5804     result_reader->comp_dir = DW_STRING (comp_dir);
5805
5806   /* Skip dummy compilation units.  */
5807   if (info_ptr >= begin_info_ptr + dwo_unit->length
5808       || peek_abbrev_code (abfd, info_ptr) == 0)
5809     return 0;
5810
5811   *result_info_ptr = info_ptr;
5812   return 1;
5813 }
5814
5815 /* Subroutine of init_cutu_and_read_dies to simplify it.
5816    Look up the DWO unit specified by COMP_UNIT_DIE of THIS_CU.
5817    Returns NULL if the specified DWO unit cannot be found.  */
5818
5819 static struct dwo_unit *
5820 lookup_dwo_unit (struct dwarf2_per_cu_data *this_cu,
5821                  struct die_info *comp_unit_die)
5822 {
5823   struct dwarf2_cu *cu = this_cu->cu;
5824   struct attribute *attr;
5825   ULONGEST signature;
5826   struct dwo_unit *dwo_unit;
5827   const char *comp_dir, *dwo_name;
5828
5829   gdb_assert (cu != NULL);
5830
5831   /* Yeah, we look dwo_name up again, but it simplifies the code.  */
5832   dwo_name = dwarf2_string_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
5833   comp_dir = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
5834
5835   if (this_cu->is_debug_types)
5836     {
5837       struct signatured_type *sig_type;
5838
5839       /* Since this_cu is the first member of struct signatured_type,
5840          we can go from a pointer to one to a pointer to the other.  */
5841       sig_type = (struct signatured_type *) this_cu;
5842       signature = sig_type->signature;
5843       dwo_unit = lookup_dwo_type_unit (sig_type, dwo_name, comp_dir);
5844     }
5845   else
5846     {
5847       struct attribute *attr;
5848
5849       attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
5850       if (! attr)
5851         error (_("Dwarf Error: missing dwo_id for dwo_name %s"
5852                  " [in module %s]"),
5853                dwo_name, objfile_name (this_cu->objfile));
5854       signature = DW_UNSND (attr);
5855       dwo_unit = lookup_dwo_comp_unit (this_cu, dwo_name, comp_dir,
5856                                        signature);
5857     }
5858
5859   return dwo_unit;
5860 }
5861
5862 /* Subroutine of init_cutu_and_read_dies to simplify it.
5863    See it for a description of the parameters.
5864    Read a TU directly from a DWO file, bypassing the stub.
5865
5866    Note: This function could be a little bit simpler if we shared cleanups
5867    with our caller, init_cutu_and_read_dies.  That's generally a fragile thing
5868    to do, so we keep this function self-contained.  Or we could move this
5869    into our caller, but it's complex enough already.  */
5870
5871 static void
5872 init_tu_and_read_dwo_dies (struct dwarf2_per_cu_data *this_cu,
5873                            int use_existing_cu, int keep,
5874                            die_reader_func_ftype *die_reader_func,
5875                            void *data)
5876 {
5877   struct dwarf2_cu *cu;
5878   struct signatured_type *sig_type;
5879   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5880   struct die_reader_specs reader;
5881   const gdb_byte *info_ptr;
5882   struct die_info *comp_unit_die;
5883   int has_children;
5884
5885   /* Verify we can do the following downcast, and that we have the
5886      data we need.  */
5887   gdb_assert (this_cu->is_debug_types && this_cu->reading_dwo_directly);
5888   sig_type = (struct signatured_type *) this_cu;
5889   gdb_assert (sig_type->dwo_unit != NULL);
5890
5891   cleanups = make_cleanup (null_cleanup, NULL);
5892
5893   if (use_existing_cu && this_cu->cu != NULL)
5894     {
5895       gdb_assert (this_cu->cu->dwo_unit == sig_type->dwo_unit);
5896       cu = this_cu->cu;
5897       /* There's no need to do the rereading_dwo_cu handling that
5898          init_cutu_and_read_dies does since we don't read the stub.  */
5899     }
5900   else
5901     {
5902       /* If !use_existing_cu, this_cu->cu must be NULL.  */
5903       gdb_assert (this_cu->cu == NULL);
5904       cu = XNEW (struct dwarf2_cu);
5905       init_one_comp_unit (cu, this_cu);
5906       /* If an error occurs while loading, release our storage.  */
5907       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
5908     }
5909
5910   /* A future optimization, if needed, would be to use an existing
5911      abbrev table.  When reading DWOs with skeletonless TUs, all the TUs
5912      could share abbrev tables.  */
5913
5914   if (read_cutu_die_from_dwo (this_cu, sig_type->dwo_unit,
5915                               0 /* abbrev_table_provided */,
5916                               NULL /* stub_comp_unit_die */,
5917                               sig_type->dwo_unit->dwo_file->comp_dir,
5918                               &reader, &info_ptr,
5919                               &comp_unit_die, &has_children) == 0)
5920     {
5921       /* Dummy die.  */
5922       do_cleanups (cleanups);
5923       return;
5924     }
5925
5926   /* All the "real" work is done here.  */
5927   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
5928
5929   /* This duplicates the code in init_cutu_and_read_dies,
5930      but the alternative is making the latter more complex.
5931      This function is only for the special case of using DWO files directly:
5932      no point in overly complicating the general case just to handle this.  */
5933   if (free_cu_cleanup != NULL)
5934     {
5935       if (keep)
5936         {
5937           /* We've successfully allocated this compilation unit.  Let our
5938              caller clean it up when finished with it.  */
5939           discard_cleanups (free_cu_cleanup);
5940
5941           /* We can only discard free_cu_cleanup and all subsequent cleanups.
5942              So we have to manually free the abbrev table.  */
5943           dwarf2_free_abbrev_table (cu);
5944
5945           /* Link this CU into read_in_chain.  */
5946           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
5947           dwarf2_per_objfile->read_in_chain = this_cu;
5948         }
5949       else
5950         do_cleanups (free_cu_cleanup);
5951     }
5952
5953   do_cleanups (cleanups);
5954 }
5955
5956 /* Initialize a CU (or TU) and read its DIEs.
5957    If the CU defers to a DWO file, read the DWO file as well.
5958
5959    ABBREV_TABLE, if non-NULL, is the abbreviation table to use.
5960    Otherwise the table specified in the comp unit header is read in and used.
5961    This is an optimization for when we already have the abbrev table.
5962
5963    If USE_EXISTING_CU is non-zero, and THIS_CU->cu is non-NULL, then use it.
5964    Otherwise, a new CU is allocated with xmalloc.
5965
5966    If KEEP is non-zero, then if we allocated a dwarf2_cu we add it to
5967    read_in_chain.  Otherwise the dwarf2_cu data is freed at the end.
5968
5969    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
5970    linker) then DIE_READER_FUNC will not get called.  */
5971
5972 static void
5973 init_cutu_and_read_dies (struct dwarf2_per_cu_data *this_cu,
5974                          struct abbrev_table *abbrev_table,
5975                          int use_existing_cu, int keep,
5976                          die_reader_func_ftype *die_reader_func,
5977                          void *data)
5978 {
5979   struct objfile *objfile = dwarf2_per_objfile->objfile;
5980   struct dwarf2_section_info *section = this_cu->section;
5981   bfd *abfd = get_section_bfd_owner (section);
5982   struct dwarf2_cu *cu;
5983   const gdb_byte *begin_info_ptr, *info_ptr;
5984   struct die_reader_specs reader;
5985   struct die_info *comp_unit_die;
5986   int has_children;
5987   struct attribute *attr;
5988   struct cleanup *cleanups, *free_cu_cleanup = NULL;
5989   struct signatured_type *sig_type = NULL;
5990   struct dwarf2_section_info *abbrev_section;
5991   /* Non-zero if CU currently points to a DWO file and we need to
5992      reread it.  When this happens we need to reread the skeleton die
5993      before we can reread the DWO file (this only applies to CUs, not TUs).  */
5994   int rereading_dwo_cu = 0;
5995
5996   if (dwarf_die_debug)
5997     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
5998                         this_cu->is_debug_types ? "type" : "comp",
5999                         to_underlying (this_cu->sect_off));
6000
6001   if (use_existing_cu)
6002     gdb_assert (keep);
6003
6004   /* If we're reading a TU directly from a DWO file, including a virtual DWO
6005      file (instead of going through the stub), short-circuit all of this.  */
6006   if (this_cu->reading_dwo_directly)
6007     {
6008       /* Narrow down the scope of possibilities to have to understand.  */
6009       gdb_assert (this_cu->is_debug_types);
6010       gdb_assert (abbrev_table == NULL);
6011       init_tu_and_read_dwo_dies (this_cu, use_existing_cu, keep,
6012                                  die_reader_func, data);
6013       return;
6014     }
6015
6016   cleanups = make_cleanup (null_cleanup, NULL);
6017
6018   /* This is cheap if the section is already read in.  */
6019   dwarf2_read_section (objfile, section);
6020
6021   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6022
6023   abbrev_section = get_abbrev_section_for_cu (this_cu);
6024
6025   if (use_existing_cu && this_cu->cu != NULL)
6026     {
6027       cu = this_cu->cu;
6028       /* If this CU is from a DWO file we need to start over, we need to
6029          refetch the attributes from the skeleton CU.
6030          This could be optimized by retrieving those attributes from when we
6031          were here the first time: the previous comp_unit_die was stored in
6032          comp_unit_obstack.  But there's no data yet that we need this
6033          optimization.  */
6034       if (cu->dwo_unit != NULL)
6035         rereading_dwo_cu = 1;
6036     }
6037   else
6038     {
6039       /* If !use_existing_cu, this_cu->cu must be NULL.  */
6040       gdb_assert (this_cu->cu == NULL);
6041       cu = XNEW (struct dwarf2_cu);
6042       init_one_comp_unit (cu, this_cu);
6043       /* If an error occurs while loading, release our storage.  */
6044       free_cu_cleanup = make_cleanup (free_heap_comp_unit, cu);
6045     }
6046
6047   /* Get the header.  */
6048   if (to_underlying (cu->header.first_die_cu_offset) != 0 && !rereading_dwo_cu)
6049     {
6050       /* We already have the header, there's no need to read it in again.  */
6051       info_ptr += to_underlying (cu->header.first_die_cu_offset);
6052     }
6053   else
6054     {
6055       if (this_cu->is_debug_types)
6056         {
6057           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6058                                                     abbrev_section, info_ptr,
6059                                                     rcuh_kind::TYPE);
6060
6061           /* Since per_cu is the first member of struct signatured_type,
6062              we can go from a pointer to one to a pointer to the other.  */
6063           sig_type = (struct signatured_type *) this_cu;
6064           gdb_assert (sig_type->signature == cu->header.signature);
6065           gdb_assert (sig_type->type_offset_in_tu
6066                       == cu->header.type_cu_offset_in_tu);
6067           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6068
6069           /* LENGTH has not been set yet for type units if we're
6070              using .gdb_index.  */
6071           this_cu->length = get_cu_length (&cu->header);
6072
6073           /* Establish the type offset that can be used to lookup the type.  */
6074           sig_type->type_offset_in_section =
6075             this_cu->sect_off + to_underlying (sig_type->type_offset_in_tu);
6076
6077           this_cu->dwarf_version = cu->header.version;
6078         }
6079       else
6080         {
6081           info_ptr = read_and_check_comp_unit_head (&cu->header, section,
6082                                                     abbrev_section,
6083                                                     info_ptr,
6084                                                     rcuh_kind::COMPILE);
6085
6086           gdb_assert (this_cu->sect_off == cu->header.sect_off);
6087           gdb_assert (this_cu->length == get_cu_length (&cu->header));
6088           this_cu->dwarf_version = cu->header.version;
6089         }
6090     }
6091
6092   /* Skip dummy compilation units.  */
6093   if (info_ptr >= begin_info_ptr + this_cu->length
6094       || peek_abbrev_code (abfd, info_ptr) == 0)
6095     {
6096       do_cleanups (cleanups);
6097       return;
6098     }
6099
6100   /* If we don't have them yet, read the abbrevs for this compilation unit.
6101      And if we need to read them now, make sure they're freed when we're
6102      done.  Note that it's important that if the CU had an abbrev table
6103      on entry we don't free it when we're done: Somewhere up the call stack
6104      it may be in use.  */
6105   if (abbrev_table != NULL)
6106     {
6107       gdb_assert (cu->abbrev_table == NULL);
6108       gdb_assert (cu->header.abbrev_sect_off == abbrev_table->sect_off);
6109       cu->abbrev_table = abbrev_table;
6110     }
6111   else if (cu->abbrev_table == NULL)
6112     {
6113       dwarf2_read_abbrevs (cu, abbrev_section);
6114       make_cleanup (dwarf2_free_abbrev_table, cu);
6115     }
6116   else if (rereading_dwo_cu)
6117     {
6118       dwarf2_free_abbrev_table (cu);
6119       dwarf2_read_abbrevs (cu, abbrev_section);
6120     }
6121
6122   /* Read the top level CU/TU die.  */
6123   init_cu_die_reader (&reader, cu, section, NULL);
6124   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6125
6126   /* If we are in a DWO stub, process it and then read in the "real" CU/TU
6127      from the DWO file.
6128      Note that if USE_EXISTING_OK != 0, and THIS_CU->cu already contains a
6129      DWO CU, that this test will fail (the attribute will not be present).  */
6130   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_name, cu);
6131   if (attr)
6132     {
6133       struct dwo_unit *dwo_unit;
6134       struct die_info *dwo_comp_unit_die;
6135
6136       if (has_children)
6137         {
6138           complaint (&symfile_complaints,
6139                      _("compilation unit with DW_AT_GNU_dwo_name"
6140                        " has children (offset 0x%x) [in module %s]"),
6141                      to_underlying (this_cu->sect_off), bfd_get_filename (abfd));
6142         }
6143       dwo_unit = lookup_dwo_unit (this_cu, comp_unit_die);
6144       if (dwo_unit != NULL)
6145         {
6146           if (read_cutu_die_from_dwo (this_cu, dwo_unit,
6147                                       abbrev_table != NULL,
6148                                       comp_unit_die, NULL,
6149                                       &reader, &info_ptr,
6150                                       &dwo_comp_unit_die, &has_children) == 0)
6151             {
6152               /* Dummy die.  */
6153               do_cleanups (cleanups);
6154               return;
6155             }
6156           comp_unit_die = dwo_comp_unit_die;
6157         }
6158       else
6159         {
6160           /* Yikes, we couldn't find the rest of the DIE, we only have
6161              the stub.  A complaint has already been logged.  There's
6162              not much more we can do except pass on the stub DIE to
6163              die_reader_func.  We don't want to throw an error on bad
6164              debug info.  */
6165         }
6166     }
6167
6168   /* All of the above is setup for this call.  Yikes.  */
6169   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6170
6171   /* Done, clean up.  */
6172   if (free_cu_cleanup != NULL)
6173     {
6174       if (keep)
6175         {
6176           /* We've successfully allocated this compilation unit.  Let our
6177              caller clean it up when finished with it.  */
6178           discard_cleanups (free_cu_cleanup);
6179
6180           /* We can only discard free_cu_cleanup and all subsequent cleanups.
6181              So we have to manually free the abbrev table.  */
6182           dwarf2_free_abbrev_table (cu);
6183
6184           /* Link this CU into read_in_chain.  */
6185           this_cu->cu->read_in_chain = dwarf2_per_objfile->read_in_chain;
6186           dwarf2_per_objfile->read_in_chain = this_cu;
6187         }
6188       else
6189         do_cleanups (free_cu_cleanup);
6190     }
6191
6192   do_cleanups (cleanups);
6193 }
6194
6195 /* Read CU/TU THIS_CU but do not follow DW_AT_GNU_dwo_name if present.
6196    DWO_FILE, if non-NULL, is the DWO file to read (the caller is assumed
6197    to have already done the lookup to find the DWO file).
6198
6199    The caller is required to fill in THIS_CU->section, THIS_CU->offset, and
6200    THIS_CU->is_debug_types, but nothing else.
6201
6202    We fill in THIS_CU->length.
6203
6204    WARNING: If THIS_CU is a "dummy CU" (used as filler by the incremental
6205    linker) then DIE_READER_FUNC will not get called.
6206
6207    THIS_CU->cu is always freed when done.
6208    This is done in order to not leave THIS_CU->cu in a state where we have
6209    to care whether it refers to the "main" CU or the DWO CU.  */
6210
6211 static void
6212 init_cutu_and_read_dies_no_follow (struct dwarf2_per_cu_data *this_cu,
6213                                    struct dwo_file *dwo_file,
6214                                    die_reader_func_ftype *die_reader_func,
6215                                    void *data)
6216 {
6217   struct objfile *objfile = dwarf2_per_objfile->objfile;
6218   struct dwarf2_section_info *section = this_cu->section;
6219   bfd *abfd = get_section_bfd_owner (section);
6220   struct dwarf2_section_info *abbrev_section;
6221   struct dwarf2_cu cu;
6222   const gdb_byte *begin_info_ptr, *info_ptr;
6223   struct die_reader_specs reader;
6224   struct cleanup *cleanups;
6225   struct die_info *comp_unit_die;
6226   int has_children;
6227
6228   if (dwarf_die_debug)
6229     fprintf_unfiltered (gdb_stdlog, "Reading %s unit at offset 0x%x\n",
6230                         this_cu->is_debug_types ? "type" : "comp",
6231                         to_underlying (this_cu->sect_off));
6232
6233   gdb_assert (this_cu->cu == NULL);
6234
6235   abbrev_section = (dwo_file != NULL
6236                     ? &dwo_file->sections.abbrev
6237                     : get_abbrev_section_for_cu (this_cu));
6238
6239   /* This is cheap if the section is already read in.  */
6240   dwarf2_read_section (objfile, section);
6241
6242   init_one_comp_unit (&cu, this_cu);
6243
6244   cleanups = make_cleanup (free_stack_comp_unit, &cu);
6245
6246   begin_info_ptr = info_ptr = section->buffer + to_underlying (this_cu->sect_off);
6247   info_ptr = read_and_check_comp_unit_head (&cu.header, section,
6248                                             abbrev_section, info_ptr,
6249                                             (this_cu->is_debug_types
6250                                              ? rcuh_kind::TYPE
6251                                              : rcuh_kind::COMPILE));
6252
6253   this_cu->length = get_cu_length (&cu.header);
6254
6255   /* Skip dummy compilation units.  */
6256   if (info_ptr >= begin_info_ptr + this_cu->length
6257       || peek_abbrev_code (abfd, info_ptr) == 0)
6258     {
6259       do_cleanups (cleanups);
6260       return;
6261     }
6262
6263   dwarf2_read_abbrevs (&cu, abbrev_section);
6264   make_cleanup (dwarf2_free_abbrev_table, &cu);
6265
6266   init_cu_die_reader (&reader, &cu, section, dwo_file);
6267   info_ptr = read_full_die (&reader, &comp_unit_die, info_ptr, &has_children);
6268
6269   die_reader_func (&reader, info_ptr, comp_unit_die, has_children, data);
6270
6271   do_cleanups (cleanups);
6272 }
6273
6274 /* Read a CU/TU, except that this does not look for DW_AT_GNU_dwo_name and
6275    does not lookup the specified DWO file.
6276    This cannot be used to read DWO files.
6277
6278    THIS_CU->cu is always freed when done.
6279    This is done in order to not leave THIS_CU->cu in a state where we have
6280    to care whether it refers to the "main" CU or the DWO CU.
6281    We can revisit this if the data shows there's a performance issue.  */
6282
6283 static void
6284 init_cutu_and_read_dies_simple (struct dwarf2_per_cu_data *this_cu,
6285                                 die_reader_func_ftype *die_reader_func,
6286                                 void *data)
6287 {
6288   init_cutu_and_read_dies_no_follow (this_cu, NULL, die_reader_func, data);
6289 }
6290 \f
6291 /* Type Unit Groups.
6292
6293    Type Unit Groups are a way to collapse the set of all TUs (type units) into
6294    a more manageable set.  The grouping is done by DW_AT_stmt_list entry
6295    so that all types coming from the same compilation (.o file) are grouped
6296    together.  A future step could be to put the types in the same symtab as
6297    the CU the types ultimately came from.  */
6298
6299 static hashval_t
6300 hash_type_unit_group (const void *item)
6301 {
6302   const struct type_unit_group *tu_group
6303     = (const struct type_unit_group *) item;
6304
6305   return hash_stmt_list_entry (&tu_group->hash);
6306 }
6307
6308 static int
6309 eq_type_unit_group (const void *item_lhs, const void *item_rhs)
6310 {
6311   const struct type_unit_group *lhs = (const struct type_unit_group *) item_lhs;
6312   const struct type_unit_group *rhs = (const struct type_unit_group *) item_rhs;
6313
6314   return eq_stmt_list_entry (&lhs->hash, &rhs->hash);
6315 }
6316
6317 /* Allocate a hash table for type unit groups.  */
6318
6319 static htab_t
6320 allocate_type_unit_groups_table (void)
6321 {
6322   return htab_create_alloc_ex (3,
6323                                hash_type_unit_group,
6324                                eq_type_unit_group,
6325                                NULL,
6326                                &dwarf2_per_objfile->objfile->objfile_obstack,
6327                                hashtab_obstack_allocate,
6328                                dummy_obstack_deallocate);
6329 }
6330
6331 /* Type units that don't have DW_AT_stmt_list are grouped into their own
6332    partial symtabs.  We combine several TUs per psymtab to not let the size
6333    of any one psymtab grow too big.  */
6334 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB (1 << 31)
6335 #define NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE 10
6336
6337 /* Helper routine for get_type_unit_group.
6338    Create the type_unit_group object used to hold one or more TUs.  */
6339
6340 static struct type_unit_group *
6341 create_type_unit_group (struct dwarf2_cu *cu, sect_offset line_offset_struct)
6342 {
6343   struct objfile *objfile = dwarf2_per_objfile->objfile;
6344   struct dwarf2_per_cu_data *per_cu;
6345   struct type_unit_group *tu_group;
6346
6347   tu_group = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6348                              struct type_unit_group);
6349   per_cu = &tu_group->per_cu;
6350   per_cu->objfile = objfile;
6351
6352   if (dwarf2_per_objfile->using_index)
6353     {
6354       per_cu->v.quick = OBSTACK_ZALLOC (&objfile->objfile_obstack,
6355                                         struct dwarf2_per_cu_quick_data);
6356     }
6357   else
6358     {
6359       unsigned int line_offset = to_underlying (line_offset_struct);
6360       struct partial_symtab *pst;
6361       char *name;
6362
6363       /* Give the symtab a useful name for debug purposes.  */
6364       if ((line_offset & NO_STMT_LIST_TYPE_UNIT_PSYMTAB) != 0)
6365         name = xstrprintf ("<type_units_%d>",
6366                            (line_offset & ~NO_STMT_LIST_TYPE_UNIT_PSYMTAB));
6367       else
6368         name = xstrprintf ("<type_units_at_0x%x>", line_offset);
6369
6370       pst = create_partial_symtab (per_cu, name);
6371       pst->anonymous = 1;
6372
6373       xfree (name);
6374     }
6375
6376   tu_group->hash.dwo_unit = cu->dwo_unit;
6377   tu_group->hash.line_sect_off = line_offset_struct;
6378
6379   return tu_group;
6380 }
6381
6382 /* Look up the type_unit_group for type unit CU, and create it if necessary.
6383    STMT_LIST is a DW_AT_stmt_list attribute.  */
6384
6385 static struct type_unit_group *
6386 get_type_unit_group (struct dwarf2_cu *cu, const struct attribute *stmt_list)
6387 {
6388   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6389   struct type_unit_group *tu_group;
6390   void **slot;
6391   unsigned int line_offset;
6392   struct type_unit_group type_unit_group_for_lookup;
6393
6394   if (dwarf2_per_objfile->type_unit_groups == NULL)
6395     {
6396       dwarf2_per_objfile->type_unit_groups =
6397         allocate_type_unit_groups_table ();
6398     }
6399
6400   /* Do we need to create a new group, or can we use an existing one?  */
6401
6402   if (stmt_list)
6403     {
6404       line_offset = DW_UNSND (stmt_list);
6405       ++tu_stats->nr_symtab_sharers;
6406     }
6407   else
6408     {
6409       /* Ugh, no stmt_list.  Rare, but we have to handle it.
6410          We can do various things here like create one group per TU or
6411          spread them over multiple groups to split up the expansion work.
6412          To avoid worst case scenarios (too many groups or too large groups)
6413          we, umm, group them in bunches.  */
6414       line_offset = (NO_STMT_LIST_TYPE_UNIT_PSYMTAB
6415                      | (tu_stats->nr_stmt_less_type_units
6416                         / NO_STMT_LIST_TYPE_UNIT_PSYMTAB_SIZE));
6417       ++tu_stats->nr_stmt_less_type_units;
6418     }
6419
6420   type_unit_group_for_lookup.hash.dwo_unit = cu->dwo_unit;
6421   type_unit_group_for_lookup.hash.line_sect_off = (sect_offset) line_offset;
6422   slot = htab_find_slot (dwarf2_per_objfile->type_unit_groups,
6423                          &type_unit_group_for_lookup, INSERT);
6424   if (*slot != NULL)
6425     {
6426       tu_group = (struct type_unit_group *) *slot;
6427       gdb_assert (tu_group != NULL);
6428     }
6429   else
6430     {
6431       sect_offset line_offset_struct = (sect_offset) line_offset;
6432       tu_group = create_type_unit_group (cu, line_offset_struct);
6433       *slot = tu_group;
6434       ++tu_stats->nr_symtabs;
6435     }
6436
6437   return tu_group;
6438 }
6439 \f
6440 /* Partial symbol tables.  */
6441
6442 /* Create a psymtab named NAME and assign it to PER_CU.
6443
6444    The caller must fill in the following details:
6445    dirname, textlow, texthigh.  */
6446
6447 static struct partial_symtab *
6448 create_partial_symtab (struct dwarf2_per_cu_data *per_cu, const char *name)
6449 {
6450   struct objfile *objfile = per_cu->objfile;
6451   struct partial_symtab *pst;
6452
6453   pst = start_psymtab_common (objfile, name, 0,
6454                               objfile->global_psymbols,
6455                               objfile->static_psymbols);
6456
6457   pst->psymtabs_addrmap_supported = 1;
6458
6459   /* This is the glue that links PST into GDB's symbol API.  */
6460   pst->read_symtab_private = per_cu;
6461   pst->read_symtab = dwarf2_read_symtab;
6462   per_cu->v.psymtab = pst;
6463
6464   return pst;
6465 }
6466
6467 /* The DATA object passed to process_psymtab_comp_unit_reader has this
6468    type.  */
6469
6470 struct process_psymtab_comp_unit_data
6471 {
6472   /* True if we are reading a DW_TAG_partial_unit.  */
6473
6474   int want_partial_unit;
6475
6476   /* The "pretend" language that is used if the CU doesn't declare a
6477      language.  */
6478
6479   enum language pretend_language;
6480 };
6481
6482 /* die_reader_func for process_psymtab_comp_unit.  */
6483
6484 static void
6485 process_psymtab_comp_unit_reader (const struct die_reader_specs *reader,
6486                                   const gdb_byte *info_ptr,
6487                                   struct die_info *comp_unit_die,
6488                                   int has_children,
6489                                   void *data)
6490 {
6491   struct dwarf2_cu *cu = reader->cu;
6492   struct objfile *objfile = cu->objfile;
6493   struct gdbarch *gdbarch = get_objfile_arch (objfile);
6494   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6495   CORE_ADDR baseaddr;
6496   CORE_ADDR best_lowpc = 0, best_highpc = 0;
6497   struct partial_symtab *pst;
6498   enum pc_bounds_kind cu_bounds_kind;
6499   const char *filename;
6500   struct process_psymtab_comp_unit_data *info
6501     = (struct process_psymtab_comp_unit_data *) data;
6502
6503   if (comp_unit_die->tag == DW_TAG_partial_unit && !info->want_partial_unit)
6504     return;
6505
6506   gdb_assert (! per_cu->is_debug_types);
6507
6508   prepare_one_comp_unit (cu, comp_unit_die, info->pretend_language);
6509
6510   cu->list_in_scope = &file_symbols;
6511
6512   /* Allocate a new partial symbol table structure.  */
6513   filename = dwarf2_string_attr (comp_unit_die, DW_AT_name, cu);
6514   if (filename == NULL)
6515     filename = "";
6516
6517   pst = create_partial_symtab (per_cu, filename);
6518
6519   /* This must be done before calling dwarf2_build_include_psymtabs.  */
6520   pst->dirname = dwarf2_string_attr (comp_unit_die, DW_AT_comp_dir, cu);
6521
6522   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
6523
6524   dwarf2_find_base_address (comp_unit_die, cu);
6525
6526   /* Possibly set the default values of LOWPC and HIGHPC from
6527      `DW_AT_ranges'.  */
6528   cu_bounds_kind = dwarf2_get_pc_bounds (comp_unit_die, &best_lowpc,
6529                                          &best_highpc, cu, pst);
6530   if (cu_bounds_kind == PC_BOUNDS_HIGH_LOW && best_lowpc < best_highpc)
6531     /* Store the contiguous range if it is not empty; it can be empty for
6532        CUs with no code.  */
6533     addrmap_set_empty (objfile->psymtabs_addrmap,
6534                        gdbarch_adjust_dwarf2_addr (gdbarch,
6535                                                    best_lowpc + baseaddr),
6536                        gdbarch_adjust_dwarf2_addr (gdbarch,
6537                                                    best_highpc + baseaddr) - 1,
6538                        pst);
6539
6540   /* Check if comp unit has_children.
6541      If so, read the rest of the partial symbols from this comp unit.
6542      If not, there's no more debug_info for this comp unit.  */
6543   if (has_children)
6544     {
6545       struct partial_die_info *first_die;
6546       CORE_ADDR lowpc, highpc;
6547
6548       lowpc = ((CORE_ADDR) -1);
6549       highpc = ((CORE_ADDR) 0);
6550
6551       first_die = load_partial_dies (reader, info_ptr, 1);
6552
6553       scan_partial_symbols (first_die, &lowpc, &highpc,
6554                             cu_bounds_kind <= PC_BOUNDS_INVALID, cu);
6555
6556       /* If we didn't find a lowpc, set it to highpc to avoid
6557          complaints from `maint check'.  */
6558       if (lowpc == ((CORE_ADDR) -1))
6559         lowpc = highpc;
6560
6561       /* If the compilation unit didn't have an explicit address range,
6562          then use the information extracted from its child dies.  */
6563       if (cu_bounds_kind <= PC_BOUNDS_INVALID)
6564         {
6565           best_lowpc = lowpc;
6566           best_highpc = highpc;
6567         }
6568     }
6569   pst->textlow = gdbarch_adjust_dwarf2_addr (gdbarch, best_lowpc + baseaddr);
6570   pst->texthigh = gdbarch_adjust_dwarf2_addr (gdbarch, best_highpc + baseaddr);
6571
6572   end_psymtab_common (objfile, pst);
6573
6574   if (!VEC_empty (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs))
6575     {
6576       int i;
6577       int len = VEC_length (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6578       struct dwarf2_per_cu_data *iter;
6579
6580       /* Fill in 'dependencies' here; we fill in 'users' in a
6581          post-pass.  */
6582       pst->number_of_dependencies = len;
6583       pst->dependencies =
6584         XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6585       for (i = 0;
6586            VEC_iterate (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
6587                         i, iter);
6588            ++i)
6589         pst->dependencies[i] = iter->v.psymtab;
6590
6591       VEC_free (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs);
6592     }
6593
6594   /* Get the list of files included in the current compilation unit,
6595      and build a psymtab for each of them.  */
6596   dwarf2_build_include_psymtabs (cu, comp_unit_die, pst);
6597
6598   if (dwarf_read_debug)
6599     {
6600       struct gdbarch *gdbarch = get_objfile_arch (objfile);
6601
6602       fprintf_unfiltered (gdb_stdlog,
6603                           "Psymtab for %s unit @0x%x: %s - %s"
6604                           ", %d global, %d static syms\n",
6605                           per_cu->is_debug_types ? "type" : "comp",
6606                           to_underlying (per_cu->sect_off),
6607                           paddress (gdbarch, pst->textlow),
6608                           paddress (gdbarch, pst->texthigh),
6609                           pst->n_global_syms, pst->n_static_syms);
6610     }
6611 }
6612
6613 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6614    Process compilation unit THIS_CU for a psymtab.  */
6615
6616 static void
6617 process_psymtab_comp_unit (struct dwarf2_per_cu_data *this_cu,
6618                            int want_partial_unit,
6619                            enum language pretend_language)
6620 {
6621   /* If this compilation unit was already read in, free the
6622      cached copy in order to read it in again.  This is
6623      necessary because we skipped some symbols when we first
6624      read in the compilation unit (see load_partial_dies).
6625      This problem could be avoided, but the benefit is unclear.  */
6626   if (this_cu->cu != NULL)
6627     free_one_cached_comp_unit (this_cu);
6628
6629   if (this_cu->is_debug_types)
6630     init_cutu_and_read_dies (this_cu, NULL, 0, 0, build_type_psymtabs_reader,
6631                              NULL);
6632   else
6633     {
6634       process_psymtab_comp_unit_data info;
6635       info.want_partial_unit = want_partial_unit;
6636       info.pretend_language = pretend_language;
6637       init_cutu_and_read_dies (this_cu, NULL, 0, 0,
6638                                process_psymtab_comp_unit_reader, &info);
6639     }
6640
6641   /* Age out any secondary CUs.  */
6642   age_cached_comp_units ();
6643 }
6644
6645 /* Reader function for build_type_psymtabs.  */
6646
6647 static void
6648 build_type_psymtabs_reader (const struct die_reader_specs *reader,
6649                             const gdb_byte *info_ptr,
6650                             struct die_info *type_unit_die,
6651                             int has_children,
6652                             void *data)
6653 {
6654   struct objfile *objfile = dwarf2_per_objfile->objfile;
6655   struct dwarf2_cu *cu = reader->cu;
6656   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
6657   struct signatured_type *sig_type;
6658   struct type_unit_group *tu_group;
6659   struct attribute *attr;
6660   struct partial_die_info *first_die;
6661   CORE_ADDR lowpc, highpc;
6662   struct partial_symtab *pst;
6663
6664   gdb_assert (data == NULL);
6665   gdb_assert (per_cu->is_debug_types);
6666   sig_type = (struct signatured_type *) per_cu;
6667
6668   if (! has_children)
6669     return;
6670
6671   attr = dwarf2_attr_no_follow (type_unit_die, DW_AT_stmt_list);
6672   tu_group = get_type_unit_group (cu, attr);
6673
6674   VEC_safe_push (sig_type_ptr, tu_group->tus, sig_type);
6675
6676   prepare_one_comp_unit (cu, type_unit_die, language_minimal);
6677   cu->list_in_scope = &file_symbols;
6678   pst = create_partial_symtab (per_cu, "");
6679   pst->anonymous = 1;
6680
6681   first_die = load_partial_dies (reader, info_ptr, 1);
6682
6683   lowpc = (CORE_ADDR) -1;
6684   highpc = (CORE_ADDR) 0;
6685   scan_partial_symbols (first_die, &lowpc, &highpc, 0, cu);
6686
6687   end_psymtab_common (objfile, pst);
6688 }
6689
6690 /* Struct used to sort TUs by their abbreviation table offset.  */
6691
6692 struct tu_abbrev_offset
6693 {
6694   struct signatured_type *sig_type;
6695   sect_offset abbrev_offset;
6696 };
6697
6698 /* Helper routine for build_type_psymtabs_1, passed to qsort.  */
6699
6700 static int
6701 sort_tu_by_abbrev_offset (const void *ap, const void *bp)
6702 {
6703   const struct tu_abbrev_offset * const *a
6704     = (const struct tu_abbrev_offset * const*) ap;
6705   const struct tu_abbrev_offset * const *b
6706     = (const struct tu_abbrev_offset * const*) bp;
6707   sect_offset aoff = (*a)->abbrev_offset;
6708   sect_offset boff = (*b)->abbrev_offset;
6709
6710   return (aoff > boff) - (aoff < boff);
6711 }
6712
6713 /* Efficiently read all the type units.
6714    This does the bulk of the work for build_type_psymtabs.
6715
6716    The efficiency is because we sort TUs by the abbrev table they use and
6717    only read each abbrev table once.  In one program there are 200K TUs
6718    sharing 8K abbrev tables.
6719
6720    The main purpose of this function is to support building the
6721    dwarf2_per_objfile->type_unit_groups table.
6722    TUs typically share the DW_AT_stmt_list of the CU they came from, so we
6723    can collapse the search space by grouping them by stmt_list.
6724    The savings can be significant, in the same program from above the 200K TUs
6725    share 8K stmt_list tables.
6726
6727    FUNC is expected to call get_type_unit_group, which will create the
6728    struct type_unit_group if necessary and add it to
6729    dwarf2_per_objfile->type_unit_groups.  */
6730
6731 static void
6732 build_type_psymtabs_1 (void)
6733 {
6734   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6735   struct cleanup *cleanups;
6736   struct abbrev_table *abbrev_table;
6737   sect_offset abbrev_offset;
6738   struct tu_abbrev_offset *sorted_by_abbrev;
6739   int i;
6740
6741   /* It's up to the caller to not call us multiple times.  */
6742   gdb_assert (dwarf2_per_objfile->type_unit_groups == NULL);
6743
6744   if (dwarf2_per_objfile->n_type_units == 0)
6745     return;
6746
6747   /* TUs typically share abbrev tables, and there can be way more TUs than
6748      abbrev tables.  Sort by abbrev table to reduce the number of times we
6749      read each abbrev table in.
6750      Alternatives are to punt or to maintain a cache of abbrev tables.
6751      This is simpler and efficient enough for now.
6752
6753      Later we group TUs by their DW_AT_stmt_list value (as this defines the
6754      symtab to use).  Typically TUs with the same abbrev offset have the same
6755      stmt_list value too so in practice this should work well.
6756
6757      The basic algorithm here is:
6758
6759       sort TUs by abbrev table
6760       for each TU with same abbrev table:
6761         read abbrev table if first user
6762         read TU top level DIE
6763           [IWBN if DWO skeletons had DW_AT_stmt_list]
6764         call FUNC  */
6765
6766   if (dwarf_read_debug)
6767     fprintf_unfiltered (gdb_stdlog, "Building type unit groups ...\n");
6768
6769   /* Sort in a separate table to maintain the order of all_type_units
6770      for .gdb_index: TU indices directly index all_type_units.  */
6771   sorted_by_abbrev = XNEWVEC (struct tu_abbrev_offset,
6772                               dwarf2_per_objfile->n_type_units);
6773   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6774     {
6775       struct signatured_type *sig_type = dwarf2_per_objfile->all_type_units[i];
6776
6777       sorted_by_abbrev[i].sig_type = sig_type;
6778       sorted_by_abbrev[i].abbrev_offset =
6779         read_abbrev_offset (sig_type->per_cu.section,
6780                             sig_type->per_cu.sect_off);
6781     }
6782   cleanups = make_cleanup (xfree, sorted_by_abbrev);
6783   qsort (sorted_by_abbrev, dwarf2_per_objfile->n_type_units,
6784          sizeof (struct tu_abbrev_offset), sort_tu_by_abbrev_offset);
6785
6786   abbrev_offset = (sect_offset) ~(unsigned) 0;
6787   abbrev_table = NULL;
6788   make_cleanup (abbrev_table_free_cleanup, &abbrev_table);
6789
6790   for (i = 0; i < dwarf2_per_objfile->n_type_units; ++i)
6791     {
6792       const struct tu_abbrev_offset *tu = &sorted_by_abbrev[i];
6793
6794       /* Switch to the next abbrev table if necessary.  */
6795       if (abbrev_table == NULL
6796           || tu->abbrev_offset != abbrev_offset)
6797         {
6798           if (abbrev_table != NULL)
6799             {
6800               abbrev_table_free (abbrev_table);
6801               /* Reset to NULL in case abbrev_table_read_table throws
6802                  an error: abbrev_table_free_cleanup will get called.  */
6803               abbrev_table = NULL;
6804             }
6805           abbrev_offset = tu->abbrev_offset;
6806           abbrev_table =
6807             abbrev_table_read_table (&dwarf2_per_objfile->abbrev,
6808                                      abbrev_offset);
6809           ++tu_stats->nr_uniq_abbrev_tables;
6810         }
6811
6812       init_cutu_and_read_dies (&tu->sig_type->per_cu, abbrev_table, 0, 0,
6813                                build_type_psymtabs_reader, NULL);
6814     }
6815
6816   do_cleanups (cleanups);
6817 }
6818
6819 /* Print collected type unit statistics.  */
6820
6821 static void
6822 print_tu_stats (void)
6823 {
6824   struct tu_stats *tu_stats = &dwarf2_per_objfile->tu_stats;
6825
6826   fprintf_unfiltered (gdb_stdlog, "Type unit statistics:\n");
6827   fprintf_unfiltered (gdb_stdlog, "  %d TUs\n",
6828                       dwarf2_per_objfile->n_type_units);
6829   fprintf_unfiltered (gdb_stdlog, "  %d uniq abbrev tables\n",
6830                       tu_stats->nr_uniq_abbrev_tables);
6831   fprintf_unfiltered (gdb_stdlog, "  %d symtabs from stmt_list entries\n",
6832                       tu_stats->nr_symtabs);
6833   fprintf_unfiltered (gdb_stdlog, "  %d symtab sharers\n",
6834                       tu_stats->nr_symtab_sharers);
6835   fprintf_unfiltered (gdb_stdlog, "  %d type units without a stmt_list\n",
6836                       tu_stats->nr_stmt_less_type_units);
6837   fprintf_unfiltered (gdb_stdlog, "  %d all_type_units reallocs\n",
6838                       tu_stats->nr_all_type_units_reallocs);
6839 }
6840
6841 /* Traversal function for build_type_psymtabs.  */
6842
6843 static int
6844 build_type_psymtab_dependencies (void **slot, void *info)
6845 {
6846   struct objfile *objfile = dwarf2_per_objfile->objfile;
6847   struct type_unit_group *tu_group = (struct type_unit_group *) *slot;
6848   struct dwarf2_per_cu_data *per_cu = &tu_group->per_cu;
6849   struct partial_symtab *pst = per_cu->v.psymtab;
6850   int len = VEC_length (sig_type_ptr, tu_group->tus);
6851   struct signatured_type *iter;
6852   int i;
6853
6854   gdb_assert (len > 0);
6855   gdb_assert (IS_TYPE_UNIT_GROUP (per_cu));
6856
6857   pst->number_of_dependencies = len;
6858   pst->dependencies =
6859     XOBNEWVEC (&objfile->objfile_obstack, struct partial_symtab *, len);
6860   for (i = 0;
6861        VEC_iterate (sig_type_ptr, tu_group->tus, i, iter);
6862        ++i)
6863     {
6864       gdb_assert (iter->per_cu.is_debug_types);
6865       pst->dependencies[i] = iter->per_cu.v.psymtab;
6866       iter->type_unit_group = tu_group;
6867     }
6868
6869   VEC_free (sig_type_ptr, tu_group->tus);
6870
6871   return 1;
6872 }
6873
6874 /* Subroutine of dwarf2_build_psymtabs_hard to simplify it.
6875    Build partial symbol tables for the .debug_types comp-units.  */
6876
6877 static void
6878 build_type_psymtabs (struct objfile *objfile)
6879 {
6880   if (! create_all_type_units (objfile))
6881     return;
6882
6883   build_type_psymtabs_1 ();
6884 }
6885
6886 /* Traversal function for process_skeletonless_type_unit.
6887    Read a TU in a DWO file and build partial symbols for it.  */
6888
6889 static int
6890 process_skeletonless_type_unit (void **slot, void *info)
6891 {
6892   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
6893   struct objfile *objfile = (struct objfile *) info;
6894   struct signatured_type find_entry, *entry;
6895
6896   /* If this TU doesn't exist in the global table, add it and read it in.  */
6897
6898   if (dwarf2_per_objfile->signatured_types == NULL)
6899     {
6900       dwarf2_per_objfile->signatured_types
6901         = allocate_signatured_type_table (objfile);
6902     }
6903
6904   find_entry.signature = dwo_unit->signature;
6905   slot = htab_find_slot (dwarf2_per_objfile->signatured_types, &find_entry,
6906                          INSERT);
6907   /* If we've already seen this type there's nothing to do.  What's happening
6908      is we're doing our own version of comdat-folding here.  */
6909   if (*slot != NULL)
6910     return 1;
6911
6912   /* This does the job that create_all_type_units would have done for
6913      this TU.  */
6914   entry = add_type_unit (dwo_unit->signature, slot);
6915   fill_in_sig_entry_from_dwo_entry (objfile, entry, dwo_unit);
6916   *slot = entry;
6917
6918   /* This does the job that build_type_psymtabs_1 would have done.  */
6919   init_cutu_and_read_dies (&entry->per_cu, NULL, 0, 0,
6920                            build_type_psymtabs_reader, NULL);
6921
6922   return 1;
6923 }
6924
6925 /* Traversal function for process_skeletonless_type_units.  */
6926
6927 static int
6928 process_dwo_file_for_skeletonless_type_units (void **slot, void *info)
6929 {
6930   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
6931
6932   if (dwo_file->tus != NULL)
6933     {
6934       htab_traverse_noresize (dwo_file->tus,
6935                               process_skeletonless_type_unit, info);
6936     }
6937
6938   return 1;
6939 }
6940
6941 /* Scan all TUs of DWO files, verifying we've processed them.
6942    This is needed in case a TU was emitted without its skeleton.
6943    Note: This can't be done until we know what all the DWO files are.  */
6944
6945 static void
6946 process_skeletonless_type_units (struct objfile *objfile)
6947 {
6948   /* Skeletonless TUs in DWP files without .gdb_index is not supported yet.  */
6949   if (get_dwp_file () == NULL
6950       && dwarf2_per_objfile->dwo_files != NULL)
6951     {
6952       htab_traverse_noresize (dwarf2_per_objfile->dwo_files,
6953                               process_dwo_file_for_skeletonless_type_units,
6954                               objfile);
6955     }
6956 }
6957
6958 /* Compute the 'user' field for each psymtab in OBJFILE.  */
6959
6960 static void
6961 set_partial_user (struct objfile *objfile)
6962 {
6963   int i;
6964
6965   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
6966     {
6967       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
6968       struct partial_symtab *pst = per_cu->v.psymtab;
6969       int j;
6970
6971       if (pst == NULL)
6972         continue;
6973
6974       for (j = 0; j < pst->number_of_dependencies; ++j)
6975         {
6976           /* Set the 'user' field only if it is not already set.  */
6977           if (pst->dependencies[j]->user == NULL)
6978             pst->dependencies[j]->user = pst;
6979         }
6980     }
6981 }
6982
6983 /* Build the partial symbol table by doing a quick pass through the
6984    .debug_info and .debug_abbrev sections.  */
6985
6986 static void
6987 dwarf2_build_psymtabs_hard (struct objfile *objfile)
6988 {
6989   struct cleanup *back_to;
6990   int i;
6991
6992   if (dwarf_read_debug)
6993     {
6994       fprintf_unfiltered (gdb_stdlog, "Building psymtabs of objfile %s ...\n",
6995                           objfile_name (objfile));
6996     }
6997
6998   dwarf2_per_objfile->reading_partial_symbols = 1;
6999
7000   dwarf2_read_section (objfile, &dwarf2_per_objfile->info);
7001
7002   /* Any cached compilation units will be linked by the per-objfile
7003      read_in_chain.  Make sure to free them when we're done.  */
7004   back_to = make_cleanup (free_cached_comp_units, NULL);
7005
7006   build_type_psymtabs (objfile);
7007
7008   create_all_comp_units (objfile);
7009
7010   /* Create a temporary address map on a temporary obstack.  We later
7011      copy this to the final obstack.  */
7012   auto_obstack temp_obstack;
7013
7014   scoped_restore save_psymtabs_addrmap
7015     = make_scoped_restore (&objfile->psymtabs_addrmap,
7016                            addrmap_create_mutable (&temp_obstack));
7017
7018   for (i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
7019     {
7020       struct dwarf2_per_cu_data *per_cu = dw2_get_cutu (i);
7021
7022       process_psymtab_comp_unit (per_cu, 0, language_minimal);
7023     }
7024
7025   /* This has to wait until we read the CUs, we need the list of DWOs.  */
7026   process_skeletonless_type_units (objfile);
7027
7028   /* Now that all TUs have been processed we can fill in the dependencies.  */
7029   if (dwarf2_per_objfile->type_unit_groups != NULL)
7030     {
7031       htab_traverse_noresize (dwarf2_per_objfile->type_unit_groups,
7032                               build_type_psymtab_dependencies, NULL);
7033     }
7034
7035   if (dwarf_read_debug)
7036     print_tu_stats ();
7037
7038   set_partial_user (objfile);
7039
7040   objfile->psymtabs_addrmap = addrmap_create_fixed (objfile->psymtabs_addrmap,
7041                                                     &objfile->objfile_obstack);
7042   /* At this point we want to keep the address map.  */
7043   save_psymtabs_addrmap.release ();
7044
7045   do_cleanups (back_to);
7046
7047   if (dwarf_read_debug)
7048     fprintf_unfiltered (gdb_stdlog, "Done building psymtabs of %s\n",
7049                         objfile_name (objfile));
7050 }
7051
7052 /* die_reader_func for load_partial_comp_unit.  */
7053
7054 static void
7055 load_partial_comp_unit_reader (const struct die_reader_specs *reader,
7056                                const gdb_byte *info_ptr,
7057                                struct die_info *comp_unit_die,
7058                                int has_children,
7059                                void *data)
7060 {
7061   struct dwarf2_cu *cu = reader->cu;
7062
7063   prepare_one_comp_unit (cu, comp_unit_die, language_minimal);
7064
7065   /* Check if comp unit has_children.
7066      If so, read the rest of the partial symbols from this comp unit.
7067      If not, there's no more debug_info for this comp unit.  */
7068   if (has_children)
7069     load_partial_dies (reader, info_ptr, 0);
7070 }
7071
7072 /* Load the partial DIEs for a secondary CU into memory.
7073    This is also used when rereading a primary CU with load_all_dies.  */
7074
7075 static void
7076 load_partial_comp_unit (struct dwarf2_per_cu_data *this_cu)
7077 {
7078   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
7079                            load_partial_comp_unit_reader, NULL);
7080 }
7081
7082 static void
7083 read_comp_units_from_section (struct objfile *objfile,
7084                               struct dwarf2_section_info *section,
7085                               struct dwarf2_section_info *abbrev_section,
7086                               unsigned int is_dwz,
7087                               int *n_allocated,
7088                               int *n_comp_units,
7089                               struct dwarf2_per_cu_data ***all_comp_units)
7090 {
7091   const gdb_byte *info_ptr;
7092   bfd *abfd = get_section_bfd_owner (section);
7093
7094   if (dwarf_read_debug)
7095     fprintf_unfiltered (gdb_stdlog, "Reading %s for %s\n",
7096                         get_section_name (section),
7097                         get_section_file_name (section));
7098
7099   dwarf2_read_section (objfile, section);
7100
7101   info_ptr = section->buffer;
7102
7103   while (info_ptr < section->buffer + section->size)
7104     {
7105       struct dwarf2_per_cu_data *this_cu;
7106
7107       sect_offset sect_off = (sect_offset) (info_ptr - section->buffer);
7108
7109       comp_unit_head cu_header;
7110       read_and_check_comp_unit_head (&cu_header, section, abbrev_section,
7111                                      info_ptr, rcuh_kind::COMPILE);
7112
7113       /* Save the compilation unit for later lookup.  */
7114       if (cu_header.unit_type != DW_UT_type)
7115         {
7116           this_cu = XOBNEW (&objfile->objfile_obstack,
7117                             struct dwarf2_per_cu_data);
7118           memset (this_cu, 0, sizeof (*this_cu));
7119         }
7120       else
7121         {
7122           auto sig_type = XOBNEW (&objfile->objfile_obstack,
7123                                   struct signatured_type);
7124           memset (sig_type, 0, sizeof (*sig_type));
7125           sig_type->signature = cu_header.signature;
7126           sig_type->type_offset_in_tu = cu_header.type_cu_offset_in_tu;
7127           this_cu = &sig_type->per_cu;
7128         }
7129       this_cu->is_debug_types = (cu_header.unit_type == DW_UT_type);
7130       this_cu->sect_off = sect_off;
7131       this_cu->length = cu_header.length + cu_header.initial_length_size;
7132       this_cu->is_dwz = is_dwz;
7133       this_cu->objfile = objfile;
7134       this_cu->section = section;
7135
7136       if (*n_comp_units == *n_allocated)
7137         {
7138           *n_allocated *= 2;
7139           *all_comp_units = XRESIZEVEC (struct dwarf2_per_cu_data *,
7140                                         *all_comp_units, *n_allocated);
7141         }
7142       (*all_comp_units)[*n_comp_units] = this_cu;
7143       ++*n_comp_units;
7144
7145       info_ptr = info_ptr + this_cu->length;
7146     }
7147 }
7148
7149 /* Create a list of all compilation units in OBJFILE.
7150    This is only done for -readnow and building partial symtabs.  */
7151
7152 static void
7153 create_all_comp_units (struct objfile *objfile)
7154 {
7155   int n_allocated;
7156   int n_comp_units;
7157   struct dwarf2_per_cu_data **all_comp_units;
7158   struct dwz_file *dwz;
7159
7160   n_comp_units = 0;
7161   n_allocated = 10;
7162   all_comp_units = XNEWVEC (struct dwarf2_per_cu_data *, n_allocated);
7163
7164   read_comp_units_from_section (objfile, &dwarf2_per_objfile->info,
7165                                 &dwarf2_per_objfile->abbrev, 0,
7166                                 &n_allocated, &n_comp_units, &all_comp_units);
7167
7168   dwz = dwarf2_get_dwz_file ();
7169   if (dwz != NULL)
7170     read_comp_units_from_section (objfile, &dwz->info, &dwz->abbrev, 1,
7171                                   &n_allocated, &n_comp_units,
7172                                   &all_comp_units);
7173
7174   dwarf2_per_objfile->all_comp_units = XOBNEWVEC (&objfile->objfile_obstack,
7175                                                   struct dwarf2_per_cu_data *,
7176                                                   n_comp_units);
7177   memcpy (dwarf2_per_objfile->all_comp_units, all_comp_units,
7178           n_comp_units * sizeof (struct dwarf2_per_cu_data *));
7179   xfree (all_comp_units);
7180   dwarf2_per_objfile->n_comp_units = n_comp_units;
7181 }
7182
7183 /* Process all loaded DIEs for compilation unit CU, starting at
7184    FIRST_DIE.  The caller should pass SET_ADDRMAP == 1 if the compilation
7185    unit DIE did not have PC info (DW_AT_low_pc and DW_AT_high_pc, or
7186    DW_AT_ranges).  See the comments of add_partial_subprogram on how
7187    SET_ADDRMAP is used and how *LOWPC and *HIGHPC are updated.  */
7188
7189 static void
7190 scan_partial_symbols (struct partial_die_info *first_die, CORE_ADDR *lowpc,
7191                       CORE_ADDR *highpc, int set_addrmap,
7192                       struct dwarf2_cu *cu)
7193 {
7194   struct partial_die_info *pdi;
7195
7196   /* Now, march along the PDI's, descending into ones which have
7197      interesting children but skipping the children of the other ones,
7198      until we reach the end of the compilation unit.  */
7199
7200   pdi = first_die;
7201
7202   while (pdi != NULL)
7203     {
7204       fixup_partial_die (pdi, cu);
7205
7206       /* Anonymous namespaces or modules have no name but have interesting
7207          children, so we need to look at them.  Ditto for anonymous
7208          enums.  */
7209
7210       if (pdi->name != NULL || pdi->tag == DW_TAG_namespace
7211           || pdi->tag == DW_TAG_module || pdi->tag == DW_TAG_enumeration_type
7212           || pdi->tag == DW_TAG_imported_unit)
7213         {
7214           switch (pdi->tag)
7215             {
7216             case DW_TAG_subprogram:
7217               add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7218               break;
7219             case DW_TAG_constant:
7220             case DW_TAG_variable:
7221             case DW_TAG_typedef:
7222             case DW_TAG_union_type:
7223               if (!pdi->is_declaration)
7224                 {
7225                   add_partial_symbol (pdi, cu);
7226                 }
7227               break;
7228             case DW_TAG_class_type:
7229             case DW_TAG_interface_type:
7230             case DW_TAG_structure_type:
7231               if (!pdi->is_declaration)
7232                 {
7233                   add_partial_symbol (pdi, cu);
7234                 }
7235               if (cu->language == language_rust && pdi->has_children)
7236                 scan_partial_symbols (pdi->die_child, lowpc, highpc,
7237                                       set_addrmap, cu);
7238               break;
7239             case DW_TAG_enumeration_type:
7240               if (!pdi->is_declaration)
7241                 add_partial_enumeration (pdi, cu);
7242               break;
7243             case DW_TAG_base_type:
7244             case DW_TAG_subrange_type:
7245               /* File scope base type definitions are added to the partial
7246                  symbol table.  */
7247               add_partial_symbol (pdi, cu);
7248               break;
7249             case DW_TAG_namespace:
7250               add_partial_namespace (pdi, lowpc, highpc, set_addrmap, cu);
7251               break;
7252             case DW_TAG_module:
7253               add_partial_module (pdi, lowpc, highpc, set_addrmap, cu);
7254               break;
7255             case DW_TAG_imported_unit:
7256               {
7257                 struct dwarf2_per_cu_data *per_cu;
7258
7259                 /* For now we don't handle imported units in type units.  */
7260                 if (cu->per_cu->is_debug_types)
7261                   {
7262                     error (_("Dwarf Error: DW_TAG_imported_unit is not"
7263                              " supported in type units [in module %s]"),
7264                            objfile_name (cu->objfile));
7265                   }
7266
7267                 per_cu = dwarf2_find_containing_comp_unit (pdi->d.sect_off,
7268                                                            pdi->is_dwz,
7269                                                            cu->objfile);
7270
7271                 /* Go read the partial unit, if needed.  */
7272                 if (per_cu->v.psymtab == NULL)
7273                   process_psymtab_comp_unit (per_cu, 1, cu->language);
7274
7275                 VEC_safe_push (dwarf2_per_cu_ptr,
7276                                cu->per_cu->imported_symtabs, per_cu);
7277               }
7278               break;
7279             case DW_TAG_imported_declaration:
7280               add_partial_symbol (pdi, cu);
7281               break;
7282             default:
7283               break;
7284             }
7285         }
7286
7287       /* If the die has a sibling, skip to the sibling.  */
7288
7289       pdi = pdi->die_sibling;
7290     }
7291 }
7292
7293 /* Functions used to compute the fully scoped name of a partial DIE.
7294
7295    Normally, this is simple.  For C++, the parent DIE's fully scoped
7296    name is concatenated with "::" and the partial DIE's name.
7297    Enumerators are an exception; they use the scope of their parent
7298    enumeration type, i.e. the name of the enumeration type is not
7299    prepended to the enumerator.
7300
7301    There are two complexities.  One is DW_AT_specification; in this
7302    case "parent" means the parent of the target of the specification,
7303    instead of the direct parent of the DIE.  The other is compilers
7304    which do not emit DW_TAG_namespace; in this case we try to guess
7305    the fully qualified name of structure types from their members'
7306    linkage names.  This must be done using the DIE's children rather
7307    than the children of any DW_AT_specification target.  We only need
7308    to do this for structures at the top level, i.e. if the target of
7309    any DW_AT_specification (if any; otherwise the DIE itself) does not
7310    have a parent.  */
7311
7312 /* Compute the scope prefix associated with PDI's parent, in
7313    compilation unit CU.  The result will be allocated on CU's
7314    comp_unit_obstack, or a copy of the already allocated PDI->NAME
7315    field.  NULL is returned if no prefix is necessary.  */
7316 static const char *
7317 partial_die_parent_scope (struct partial_die_info *pdi,
7318                           struct dwarf2_cu *cu)
7319 {
7320   const char *grandparent_scope;
7321   struct partial_die_info *parent, *real_pdi;
7322
7323   /* We need to look at our parent DIE; if we have a DW_AT_specification,
7324      then this means the parent of the specification DIE.  */
7325
7326   real_pdi = pdi;
7327   while (real_pdi->has_specification)
7328     real_pdi = find_partial_die (real_pdi->spec_offset,
7329                                  real_pdi->spec_is_dwz, cu);
7330
7331   parent = real_pdi->die_parent;
7332   if (parent == NULL)
7333     return NULL;
7334
7335   if (parent->scope_set)
7336     return parent->scope;
7337
7338   fixup_partial_die (parent, cu);
7339
7340   grandparent_scope = partial_die_parent_scope (parent, cu);
7341
7342   /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
7343      DW_TAG_namespace DIEs with a name of "::" for the global namespace.
7344      Work around this problem here.  */
7345   if (cu->language == language_cplus
7346       && parent->tag == DW_TAG_namespace
7347       && strcmp (parent->name, "::") == 0
7348       && grandparent_scope == NULL)
7349     {
7350       parent->scope = NULL;
7351       parent->scope_set = 1;
7352       return NULL;
7353     }
7354
7355   if (pdi->tag == DW_TAG_enumerator)
7356     /* Enumerators should not get the name of the enumeration as a prefix.  */
7357     parent->scope = grandparent_scope;
7358   else if (parent->tag == DW_TAG_namespace
7359       || parent->tag == DW_TAG_module
7360       || parent->tag == DW_TAG_structure_type
7361       || parent->tag == DW_TAG_class_type
7362       || parent->tag == DW_TAG_interface_type
7363       || parent->tag == DW_TAG_union_type
7364       || parent->tag == DW_TAG_enumeration_type)
7365     {
7366       if (grandparent_scope == NULL)
7367         parent->scope = parent->name;
7368       else
7369         parent->scope = typename_concat (&cu->comp_unit_obstack,
7370                                          grandparent_scope,
7371                                          parent->name, 0, cu);
7372     }
7373   else
7374     {
7375       /* FIXME drow/2004-04-01: What should we be doing with
7376          function-local names?  For partial symbols, we should probably be
7377          ignoring them.  */
7378       complaint (&symfile_complaints,
7379                  _("unhandled containing DIE tag %d for DIE at %d"),
7380                  parent->tag, to_underlying (pdi->sect_off));
7381       parent->scope = grandparent_scope;
7382     }
7383
7384   parent->scope_set = 1;
7385   return parent->scope;
7386 }
7387
7388 /* Return the fully scoped name associated with PDI, from compilation unit
7389    CU.  The result will be allocated with malloc.  */
7390
7391 static char *
7392 partial_die_full_name (struct partial_die_info *pdi,
7393                        struct dwarf2_cu *cu)
7394 {
7395   const char *parent_scope;
7396
7397   /* If this is a template instantiation, we can not work out the
7398      template arguments from partial DIEs.  So, unfortunately, we have
7399      to go through the full DIEs.  At least any work we do building
7400      types here will be reused if full symbols are loaded later.  */
7401   if (pdi->has_template_arguments)
7402     {
7403       fixup_partial_die (pdi, cu);
7404
7405       if (pdi->name != NULL && strchr (pdi->name, '<') == NULL)
7406         {
7407           struct die_info *die;
7408           struct attribute attr;
7409           struct dwarf2_cu *ref_cu = cu;
7410
7411           /* DW_FORM_ref_addr is using section offset.  */
7412           attr.name = (enum dwarf_attribute) 0;
7413           attr.form = DW_FORM_ref_addr;
7414           attr.u.unsnd = to_underlying (pdi->sect_off);
7415           die = follow_die_ref (NULL, &attr, &ref_cu);
7416
7417           return xstrdup (dwarf2_full_name (NULL, die, ref_cu));
7418         }
7419     }
7420
7421   parent_scope = partial_die_parent_scope (pdi, cu);
7422   if (parent_scope == NULL)
7423     return NULL;
7424   else
7425     return typename_concat (NULL, parent_scope, pdi->name, 0, cu);
7426 }
7427
7428 static void
7429 add_partial_symbol (struct partial_die_info *pdi, struct dwarf2_cu *cu)
7430 {
7431   struct objfile *objfile = cu->objfile;
7432   struct gdbarch *gdbarch = get_objfile_arch (objfile);
7433   CORE_ADDR addr = 0;
7434   const char *actual_name = NULL;
7435   CORE_ADDR baseaddr;
7436   char *built_actual_name;
7437
7438   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
7439
7440   built_actual_name = partial_die_full_name (pdi, cu);
7441   if (built_actual_name != NULL)
7442     actual_name = built_actual_name;
7443
7444   if (actual_name == NULL)
7445     actual_name = pdi->name;
7446
7447   switch (pdi->tag)
7448     {
7449     case DW_TAG_subprogram:
7450       addr = gdbarch_adjust_dwarf2_addr (gdbarch, pdi->lowpc + baseaddr);
7451       if (pdi->is_external || cu->language == language_ada)
7452         {
7453           /* brobecker/2007-12-26: Normally, only "external" DIEs are part
7454              of the global scope.  But in Ada, we want to be able to access
7455              nested procedures globally.  So all Ada subprograms are stored
7456              in the global scope.  */
7457           add_psymbol_to_list (actual_name, strlen (actual_name),
7458                                built_actual_name != NULL,
7459                                VAR_DOMAIN, LOC_BLOCK,
7460                                &objfile->global_psymbols,
7461                                addr, cu->language, objfile);
7462         }
7463       else
7464         {
7465           add_psymbol_to_list (actual_name, strlen (actual_name),
7466                                built_actual_name != NULL,
7467                                VAR_DOMAIN, LOC_BLOCK,
7468                                &objfile->static_psymbols,
7469                                addr, cu->language, objfile);
7470         }
7471
7472       if (pdi->main_subprogram && actual_name != NULL)
7473         set_objfile_main_name (objfile, actual_name, cu->language);
7474       break;
7475     case DW_TAG_constant:
7476       {
7477         std::vector<partial_symbol *> *list;
7478
7479         if (pdi->is_external)
7480           list = &objfile->global_psymbols;
7481         else
7482           list = &objfile->static_psymbols;
7483         add_psymbol_to_list (actual_name, strlen (actual_name),
7484                              built_actual_name != NULL, VAR_DOMAIN, LOC_STATIC,
7485                              list, 0, cu->language, objfile);
7486       }
7487       break;
7488     case DW_TAG_variable:
7489       if (pdi->d.locdesc)
7490         addr = decode_locdesc (pdi->d.locdesc, cu);
7491
7492       if (pdi->d.locdesc
7493           && addr == 0
7494           && !dwarf2_per_objfile->has_section_at_zero)
7495         {
7496           /* A global or static variable may also have been stripped
7497              out by the linker if unused, in which case its address
7498              will be nullified; do not add such variables into partial
7499              symbol table then.  */
7500         }
7501       else if (pdi->is_external)
7502         {
7503           /* Global Variable.
7504              Don't enter into the minimal symbol tables as there is
7505              a minimal symbol table entry from the ELF symbols already.
7506              Enter into partial symbol table if it has a location
7507              descriptor or a type.
7508              If the location descriptor is missing, new_symbol will create
7509              a LOC_UNRESOLVED symbol, the address of the variable will then
7510              be determined from the minimal symbol table whenever the variable
7511              is referenced.
7512              The address for the partial symbol table entry is not
7513              used by GDB, but it comes in handy for debugging partial symbol
7514              table building.  */
7515
7516           if (pdi->d.locdesc || pdi->has_type)
7517             add_psymbol_to_list (actual_name, strlen (actual_name),
7518                                  built_actual_name != NULL,
7519                                  VAR_DOMAIN, LOC_STATIC,
7520                                  &objfile->global_psymbols,
7521                                  addr + baseaddr,
7522                                  cu->language, objfile);
7523         }
7524       else
7525         {
7526           int has_loc = pdi->d.locdesc != NULL;
7527
7528           /* Static Variable.  Skip symbols whose value we cannot know (those
7529              without location descriptors or constant values).  */
7530           if (!has_loc && !pdi->has_const_value)
7531             {
7532               xfree (built_actual_name);
7533               return;
7534             }
7535
7536           add_psymbol_to_list (actual_name, strlen (actual_name),
7537                                built_actual_name != NULL,
7538                                VAR_DOMAIN, LOC_STATIC,
7539                                &objfile->static_psymbols,
7540                                has_loc ? addr + baseaddr : (CORE_ADDR) 0,
7541                                cu->language, objfile);
7542         }
7543       break;
7544     case DW_TAG_typedef:
7545     case DW_TAG_base_type:
7546     case DW_TAG_subrange_type:
7547       add_psymbol_to_list (actual_name, strlen (actual_name),
7548                            built_actual_name != NULL,
7549                            VAR_DOMAIN, LOC_TYPEDEF,
7550                            &objfile->static_psymbols,
7551                            0, cu->language, objfile);
7552       break;
7553     case DW_TAG_imported_declaration:
7554     case DW_TAG_namespace:
7555       add_psymbol_to_list (actual_name, strlen (actual_name),
7556                            built_actual_name != NULL,
7557                            VAR_DOMAIN, LOC_TYPEDEF,
7558                            &objfile->global_psymbols,
7559                            0, cu->language, objfile);
7560       break;
7561     case DW_TAG_module:
7562       add_psymbol_to_list (actual_name, strlen (actual_name),
7563                            built_actual_name != NULL,
7564                            MODULE_DOMAIN, LOC_TYPEDEF,
7565                            &objfile->global_psymbols,
7566                            0, cu->language, objfile);
7567       break;
7568     case DW_TAG_class_type:
7569     case DW_TAG_interface_type:
7570     case DW_TAG_structure_type:
7571     case DW_TAG_union_type:
7572     case DW_TAG_enumeration_type:
7573       /* Skip external references.  The DWARF standard says in the section
7574          about "Structure, Union, and Class Type Entries": "An incomplete
7575          structure, union or class type is represented by a structure,
7576          union or class entry that does not have a byte size attribute
7577          and that has a DW_AT_declaration attribute."  */
7578       if (!pdi->has_byte_size && pdi->is_declaration)
7579         {
7580           xfree (built_actual_name);
7581           return;
7582         }
7583
7584       /* NOTE: carlton/2003-10-07: See comment in new_symbol about
7585          static vs. global.  */
7586       add_psymbol_to_list (actual_name, strlen (actual_name),
7587                            built_actual_name != NULL,
7588                            STRUCT_DOMAIN, LOC_TYPEDEF,
7589                            cu->language == language_cplus
7590                            ? &objfile->global_psymbols
7591                            : &objfile->static_psymbols,
7592                            0, cu->language, objfile);
7593
7594       break;
7595     case DW_TAG_enumerator:
7596       add_psymbol_to_list (actual_name, strlen (actual_name),
7597                            built_actual_name != NULL,
7598                            VAR_DOMAIN, LOC_CONST,
7599                            cu->language == language_cplus
7600                            ? &objfile->global_psymbols
7601                            : &objfile->static_psymbols,
7602                            0, cu->language, objfile);
7603       break;
7604     default:
7605       break;
7606     }
7607
7608   xfree (built_actual_name);
7609 }
7610
7611 /* Read a partial die corresponding to a namespace; also, add a symbol
7612    corresponding to that namespace to the symbol table.  NAMESPACE is
7613    the name of the enclosing namespace.  */
7614
7615 static void
7616 add_partial_namespace (struct partial_die_info *pdi,
7617                        CORE_ADDR *lowpc, CORE_ADDR *highpc,
7618                        int set_addrmap, struct dwarf2_cu *cu)
7619 {
7620   /* Add a symbol for the namespace.  */
7621
7622   add_partial_symbol (pdi, cu);
7623
7624   /* Now scan partial symbols in that namespace.  */
7625
7626   if (pdi->has_children)
7627     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7628 }
7629
7630 /* Read a partial die corresponding to a Fortran module.  */
7631
7632 static void
7633 add_partial_module (struct partial_die_info *pdi, CORE_ADDR *lowpc,
7634                     CORE_ADDR *highpc, int set_addrmap, struct dwarf2_cu *cu)
7635 {
7636   /* Add a symbol for the namespace.  */
7637
7638   add_partial_symbol (pdi, cu);
7639
7640   /* Now scan partial symbols in that module.  */
7641
7642   if (pdi->has_children)
7643     scan_partial_symbols (pdi->die_child, lowpc, highpc, set_addrmap, cu);
7644 }
7645
7646 /* Read a partial die corresponding to a subprogram and create a partial
7647    symbol for that subprogram.  When the CU language allows it, this
7648    routine also defines a partial symbol for each nested subprogram
7649    that this subprogram contains.  If SET_ADDRMAP is true, record the
7650    covered ranges in the addrmap.  Set *LOWPC and *HIGHPC to the lowest
7651    and highest PC values found in PDI.
7652
7653    PDI may also be a lexical block, in which case we simply search
7654    recursively for subprograms defined inside that lexical block.
7655    Again, this is only performed when the CU language allows this
7656    type of definitions.  */
7657
7658 static void
7659 add_partial_subprogram (struct partial_die_info *pdi,
7660                         CORE_ADDR *lowpc, CORE_ADDR *highpc,
7661                         int set_addrmap, struct dwarf2_cu *cu)
7662 {
7663   if (pdi->tag == DW_TAG_subprogram)
7664     {
7665       if (pdi->has_pc_info)
7666         {
7667           if (pdi->lowpc < *lowpc)
7668             *lowpc = pdi->lowpc;
7669           if (pdi->highpc > *highpc)
7670             *highpc = pdi->highpc;
7671           if (set_addrmap)
7672             {
7673               struct objfile *objfile = cu->objfile;
7674               struct gdbarch *gdbarch = get_objfile_arch (objfile);
7675               CORE_ADDR baseaddr;
7676               CORE_ADDR highpc;
7677               CORE_ADDR lowpc;
7678
7679               baseaddr = ANOFFSET (objfile->section_offsets,
7680                                    SECT_OFF_TEXT (objfile));
7681               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7682                                                   pdi->lowpc + baseaddr);
7683               highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
7684                                                    pdi->highpc + baseaddr);
7685               addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
7686                                  cu->per_cu->v.psymtab);
7687             }
7688         }
7689
7690       if (pdi->has_pc_info || (!pdi->is_external && pdi->may_be_inlined))
7691         {
7692           if (!pdi->is_declaration)
7693             /* Ignore subprogram DIEs that do not have a name, they are
7694                illegal.  Do not emit a complaint at this point, we will
7695                do so when we convert this psymtab into a symtab.  */
7696             if (pdi->name)
7697               add_partial_symbol (pdi, cu);
7698         }
7699     }
7700
7701   if (! pdi->has_children)
7702     return;
7703
7704   if (cu->language == language_ada)
7705     {
7706       pdi = pdi->die_child;
7707       while (pdi != NULL)
7708         {
7709           fixup_partial_die (pdi, cu);
7710           if (pdi->tag == DW_TAG_subprogram
7711               || pdi->tag == DW_TAG_lexical_block)
7712             add_partial_subprogram (pdi, lowpc, highpc, set_addrmap, cu);
7713           pdi = pdi->die_sibling;
7714         }
7715     }
7716 }
7717
7718 /* Read a partial die corresponding to an enumeration type.  */
7719
7720 static void
7721 add_partial_enumeration (struct partial_die_info *enum_pdi,
7722                          struct dwarf2_cu *cu)
7723 {
7724   struct partial_die_info *pdi;
7725
7726   if (enum_pdi->name != NULL)
7727     add_partial_symbol (enum_pdi, cu);
7728
7729   pdi = enum_pdi->die_child;
7730   while (pdi)
7731     {
7732       if (pdi->tag != DW_TAG_enumerator || pdi->name == NULL)
7733         complaint (&symfile_complaints, _("malformed enumerator DIE ignored"));
7734       else
7735         add_partial_symbol (pdi, cu);
7736       pdi = pdi->die_sibling;
7737     }
7738 }
7739
7740 /* Return the initial uleb128 in the die at INFO_PTR.  */
7741
7742 static unsigned int
7743 peek_abbrev_code (bfd *abfd, const gdb_byte *info_ptr)
7744 {
7745   unsigned int bytes_read;
7746
7747   return read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7748 }
7749
7750 /* Read the initial uleb128 in the die at INFO_PTR in compilation unit CU.
7751    Return the corresponding abbrev, or NULL if the number is zero (indicating
7752    an empty DIE).  In either case *BYTES_READ will be set to the length of
7753    the initial number.  */
7754
7755 static struct abbrev_info *
7756 peek_die_abbrev (const gdb_byte *info_ptr, unsigned int *bytes_read,
7757                  struct dwarf2_cu *cu)
7758 {
7759   bfd *abfd = cu->objfile->obfd;
7760   unsigned int abbrev_number;
7761   struct abbrev_info *abbrev;
7762
7763   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
7764
7765   if (abbrev_number == 0)
7766     return NULL;
7767
7768   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
7769   if (!abbrev)
7770     {
7771       error (_("Dwarf Error: Could not find abbrev number %d in %s"
7772                " at offset 0x%x [in module %s]"),
7773              abbrev_number, cu->per_cu->is_debug_types ? "TU" : "CU",
7774              to_underlying (cu->header.sect_off), bfd_get_filename (abfd));
7775     }
7776
7777   return abbrev;
7778 }
7779
7780 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7781    Returns a pointer to the end of a series of DIEs, terminated by an empty
7782    DIE.  Any children of the skipped DIEs will also be skipped.  */
7783
7784 static const gdb_byte *
7785 skip_children (const struct die_reader_specs *reader, const gdb_byte *info_ptr)
7786 {
7787   struct dwarf2_cu *cu = reader->cu;
7788   struct abbrev_info *abbrev;
7789   unsigned int bytes_read;
7790
7791   while (1)
7792     {
7793       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
7794       if (abbrev == NULL)
7795         return info_ptr + bytes_read;
7796       else
7797         info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
7798     }
7799 }
7800
7801 /* Scan the debug information for CU starting at INFO_PTR in buffer BUFFER.
7802    INFO_PTR should point just after the initial uleb128 of a DIE, and the
7803    abbrev corresponding to that skipped uleb128 should be passed in
7804    ABBREV.  Returns a pointer to this DIE's sibling, skipping any
7805    children.  */
7806
7807 static const gdb_byte *
7808 skip_one_die (const struct die_reader_specs *reader, const gdb_byte *info_ptr,
7809               struct abbrev_info *abbrev)
7810 {
7811   unsigned int bytes_read;
7812   struct attribute attr;
7813   bfd *abfd = reader->abfd;
7814   struct dwarf2_cu *cu = reader->cu;
7815   const gdb_byte *buffer = reader->buffer;
7816   const gdb_byte *buffer_end = reader->buffer_end;
7817   unsigned int form, i;
7818
7819   for (i = 0; i < abbrev->num_attrs; i++)
7820     {
7821       /* The only abbrev we care about is DW_AT_sibling.  */
7822       if (abbrev->attrs[i].name == DW_AT_sibling)
7823         {
7824           read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
7825           if (attr.form == DW_FORM_ref_addr)
7826             complaint (&symfile_complaints,
7827                        _("ignoring absolute DW_AT_sibling"));
7828           else
7829             {
7830               sect_offset off = dwarf2_get_ref_die_offset (&attr);
7831               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
7832
7833               if (sibling_ptr < info_ptr)
7834                 complaint (&symfile_complaints,
7835                            _("DW_AT_sibling points backwards"));
7836               else if (sibling_ptr > reader->buffer_end)
7837                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
7838               else
7839                 return sibling_ptr;
7840             }
7841         }
7842
7843       /* If it isn't DW_AT_sibling, skip this attribute.  */
7844       form = abbrev->attrs[i].form;
7845     skip_attribute:
7846       switch (form)
7847         {
7848         case DW_FORM_ref_addr:
7849           /* In DWARF 2, DW_FORM_ref_addr is address sized; in DWARF 3
7850              and later it is offset sized.  */
7851           if (cu->header.version == 2)
7852             info_ptr += cu->header.addr_size;
7853           else
7854             info_ptr += cu->header.offset_size;
7855           break;
7856         case DW_FORM_GNU_ref_alt:
7857           info_ptr += cu->header.offset_size;
7858           break;
7859         case DW_FORM_addr:
7860           info_ptr += cu->header.addr_size;
7861           break;
7862         case DW_FORM_data1:
7863         case DW_FORM_ref1:
7864         case DW_FORM_flag:
7865           info_ptr += 1;
7866           break;
7867         case DW_FORM_flag_present:
7868         case DW_FORM_implicit_const:
7869           break;
7870         case DW_FORM_data2:
7871         case DW_FORM_ref2:
7872           info_ptr += 2;
7873           break;
7874         case DW_FORM_data4:
7875         case DW_FORM_ref4:
7876           info_ptr += 4;
7877           break;
7878         case DW_FORM_data8:
7879         case DW_FORM_ref8:
7880         case DW_FORM_ref_sig8:
7881           info_ptr += 8;
7882           break;
7883         case DW_FORM_data16:
7884           info_ptr += 16;
7885           break;
7886         case DW_FORM_string:
7887           read_direct_string (abfd, info_ptr, &bytes_read);
7888           info_ptr += bytes_read;
7889           break;
7890         case DW_FORM_sec_offset:
7891         case DW_FORM_strp:
7892         case DW_FORM_GNU_strp_alt:
7893           info_ptr += cu->header.offset_size;
7894           break;
7895         case DW_FORM_exprloc:
7896         case DW_FORM_block:
7897           info_ptr += read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7898           info_ptr += bytes_read;
7899           break;
7900         case DW_FORM_block1:
7901           info_ptr += 1 + read_1_byte (abfd, info_ptr);
7902           break;
7903         case DW_FORM_block2:
7904           info_ptr += 2 + read_2_bytes (abfd, info_ptr);
7905           break;
7906         case DW_FORM_block4:
7907           info_ptr += 4 + read_4_bytes (abfd, info_ptr);
7908           break;
7909         case DW_FORM_sdata:
7910         case DW_FORM_udata:
7911         case DW_FORM_ref_udata:
7912         case DW_FORM_GNU_addr_index:
7913         case DW_FORM_GNU_str_index:
7914           info_ptr = safe_skip_leb128 (info_ptr, buffer_end);
7915           break;
7916         case DW_FORM_indirect:
7917           form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
7918           info_ptr += bytes_read;
7919           /* We need to continue parsing from here, so just go back to
7920              the top.  */
7921           goto skip_attribute;
7922
7923         default:
7924           error (_("Dwarf Error: Cannot handle %s "
7925                    "in DWARF reader [in module %s]"),
7926                  dwarf_form_name (form),
7927                  bfd_get_filename (abfd));
7928         }
7929     }
7930
7931   if (abbrev->has_children)
7932     return skip_children (reader, info_ptr);
7933   else
7934     return info_ptr;
7935 }
7936
7937 /* Locate ORIG_PDI's sibling.
7938    INFO_PTR should point to the start of the next DIE after ORIG_PDI.  */
7939
7940 static const gdb_byte *
7941 locate_pdi_sibling (const struct die_reader_specs *reader,
7942                     struct partial_die_info *orig_pdi,
7943                     const gdb_byte *info_ptr)
7944 {
7945   /* Do we know the sibling already?  */
7946
7947   if (orig_pdi->sibling)
7948     return orig_pdi->sibling;
7949
7950   /* Are there any children to deal with?  */
7951
7952   if (!orig_pdi->has_children)
7953     return info_ptr;
7954
7955   /* Skip the children the long way.  */
7956
7957   return skip_children (reader, info_ptr);
7958 }
7959
7960 /* Expand this partial symbol table into a full symbol table.  SELF is
7961    not NULL.  */
7962
7963 static void
7964 dwarf2_read_symtab (struct partial_symtab *self,
7965                     struct objfile *objfile)
7966 {
7967   if (self->readin)
7968     {
7969       warning (_("bug: psymtab for %s is already read in."),
7970                self->filename);
7971     }
7972   else
7973     {
7974       if (info_verbose)
7975         {
7976           printf_filtered (_("Reading in symbols for %s..."),
7977                            self->filename);
7978           gdb_flush (gdb_stdout);
7979         }
7980
7981       /* Restore our global data.  */
7982       dwarf2_per_objfile
7983         = (struct dwarf2_per_objfile *) objfile_data (objfile,
7984                                                       dwarf2_objfile_data_key);
7985
7986       /* If this psymtab is constructed from a debug-only objfile, the
7987          has_section_at_zero flag will not necessarily be correct.  We
7988          can get the correct value for this flag by looking at the data
7989          associated with the (presumably stripped) associated objfile.  */
7990       if (objfile->separate_debug_objfile_backlink)
7991         {
7992           struct dwarf2_per_objfile *dpo_backlink
7993             = ((struct dwarf2_per_objfile *)
7994                objfile_data (objfile->separate_debug_objfile_backlink,
7995                              dwarf2_objfile_data_key));
7996
7997           dwarf2_per_objfile->has_section_at_zero
7998             = dpo_backlink->has_section_at_zero;
7999         }
8000
8001       dwarf2_per_objfile->reading_partial_symbols = 0;
8002
8003       psymtab_to_symtab_1 (self);
8004
8005       /* Finish up the debug error message.  */
8006       if (info_verbose)
8007         printf_filtered (_("done.\n"));
8008     }
8009
8010   process_cu_includes ();
8011 }
8012 \f
8013 /* Reading in full CUs.  */
8014
8015 /* Add PER_CU to the queue.  */
8016
8017 static void
8018 queue_comp_unit (struct dwarf2_per_cu_data *per_cu,
8019                  enum language pretend_language)
8020 {
8021   struct dwarf2_queue_item *item;
8022
8023   per_cu->queued = 1;
8024   item = XNEW (struct dwarf2_queue_item);
8025   item->per_cu = per_cu;
8026   item->pretend_language = pretend_language;
8027   item->next = NULL;
8028
8029   if (dwarf2_queue == NULL)
8030     dwarf2_queue = item;
8031   else
8032     dwarf2_queue_tail->next = item;
8033
8034   dwarf2_queue_tail = item;
8035 }
8036
8037 /* If PER_CU is not yet queued, add it to the queue.
8038    If DEPENDENT_CU is non-NULL, it has a reference to PER_CU so add a
8039    dependency.
8040    The result is non-zero if PER_CU was queued, otherwise the result is zero
8041    meaning either PER_CU is already queued or it is already loaded.
8042
8043    N.B. There is an invariant here that if a CU is queued then it is loaded.
8044    The caller is required to load PER_CU if we return non-zero.  */
8045
8046 static int
8047 maybe_queue_comp_unit (struct dwarf2_cu *dependent_cu,
8048                        struct dwarf2_per_cu_data *per_cu,
8049                        enum language pretend_language)
8050 {
8051   /* We may arrive here during partial symbol reading, if we need full
8052      DIEs to process an unusual case (e.g. template arguments).  Do
8053      not queue PER_CU, just tell our caller to load its DIEs.  */
8054   if (dwarf2_per_objfile->reading_partial_symbols)
8055     {
8056       if (per_cu->cu == NULL || per_cu->cu->dies == NULL)
8057         return 1;
8058       return 0;
8059     }
8060
8061   /* Mark the dependence relation so that we don't flush PER_CU
8062      too early.  */
8063   if (dependent_cu != NULL)
8064     dwarf2_add_dependence (dependent_cu, per_cu);
8065
8066   /* If it's already on the queue, we have nothing to do.  */
8067   if (per_cu->queued)
8068     return 0;
8069
8070   /* If the compilation unit is already loaded, just mark it as
8071      used.  */
8072   if (per_cu->cu != NULL)
8073     {
8074       per_cu->cu->last_used = 0;
8075       return 0;
8076     }
8077
8078   /* Add it to the queue.  */
8079   queue_comp_unit (per_cu, pretend_language);
8080
8081   return 1;
8082 }
8083
8084 /* Process the queue.  */
8085
8086 static void
8087 process_queue (void)
8088 {
8089   struct dwarf2_queue_item *item, *next_item;
8090
8091   if (dwarf_read_debug)
8092     {
8093       fprintf_unfiltered (gdb_stdlog,
8094                           "Expanding one or more symtabs of objfile %s ...\n",
8095                           objfile_name (dwarf2_per_objfile->objfile));
8096     }
8097
8098   /* The queue starts out with one item, but following a DIE reference
8099      may load a new CU, adding it to the end of the queue.  */
8100   for (item = dwarf2_queue; item != NULL; dwarf2_queue = item = next_item)
8101     {
8102       if ((dwarf2_per_objfile->using_index
8103            ? !item->per_cu->v.quick->compunit_symtab
8104            : (item->per_cu->v.psymtab && !item->per_cu->v.psymtab->readin))
8105           /* Skip dummy CUs.  */
8106           && item->per_cu->cu != NULL)
8107         {
8108           struct dwarf2_per_cu_data *per_cu = item->per_cu;
8109           unsigned int debug_print_threshold;
8110           char buf[100];
8111
8112           if (per_cu->is_debug_types)
8113             {
8114               struct signatured_type *sig_type =
8115                 (struct signatured_type *) per_cu;
8116
8117               sprintf (buf, "TU %s at offset 0x%x",
8118                        hex_string (sig_type->signature),
8119                        to_underlying (per_cu->sect_off));
8120               /* There can be 100s of TUs.
8121                  Only print them in verbose mode.  */
8122               debug_print_threshold = 2;
8123             }
8124           else
8125             {
8126               sprintf (buf, "CU at offset 0x%x",
8127                        to_underlying (per_cu->sect_off));
8128               debug_print_threshold = 1;
8129             }
8130
8131           if (dwarf_read_debug >= debug_print_threshold)
8132             fprintf_unfiltered (gdb_stdlog, "Expanding symtab of %s\n", buf);
8133
8134           if (per_cu->is_debug_types)
8135             process_full_type_unit (per_cu, item->pretend_language);
8136           else
8137             process_full_comp_unit (per_cu, item->pretend_language);
8138
8139           if (dwarf_read_debug >= debug_print_threshold)
8140             fprintf_unfiltered (gdb_stdlog, "Done expanding %s\n", buf);
8141         }
8142
8143       item->per_cu->queued = 0;
8144       next_item = item->next;
8145       xfree (item);
8146     }
8147
8148   dwarf2_queue_tail = NULL;
8149
8150   if (dwarf_read_debug)
8151     {
8152       fprintf_unfiltered (gdb_stdlog, "Done expanding symtabs of %s.\n",
8153                           objfile_name (dwarf2_per_objfile->objfile));
8154     }
8155 }
8156
8157 /* Free all allocated queue entries.  This function only releases anything if
8158    an error was thrown; if the queue was processed then it would have been
8159    freed as we went along.  */
8160
8161 static void
8162 dwarf2_release_queue (void *dummy)
8163 {
8164   struct dwarf2_queue_item *item, *last;
8165
8166   item = dwarf2_queue;
8167   while (item)
8168     {
8169       /* Anything still marked queued is likely to be in an
8170          inconsistent state, so discard it.  */
8171       if (item->per_cu->queued)
8172         {
8173           if (item->per_cu->cu != NULL)
8174             free_one_cached_comp_unit (item->per_cu);
8175           item->per_cu->queued = 0;
8176         }
8177
8178       last = item;
8179       item = item->next;
8180       xfree (last);
8181     }
8182
8183   dwarf2_queue = dwarf2_queue_tail = NULL;
8184 }
8185
8186 /* Read in full symbols for PST, and anything it depends on.  */
8187
8188 static void
8189 psymtab_to_symtab_1 (struct partial_symtab *pst)
8190 {
8191   struct dwarf2_per_cu_data *per_cu;
8192   int i;
8193
8194   if (pst->readin)
8195     return;
8196
8197   for (i = 0; i < pst->number_of_dependencies; i++)
8198     if (!pst->dependencies[i]->readin
8199         && pst->dependencies[i]->user == NULL)
8200       {
8201         /* Inform about additional files that need to be read in.  */
8202         if (info_verbose)
8203           {
8204             /* FIXME: i18n: Need to make this a single string.  */
8205             fputs_filtered (" ", gdb_stdout);
8206             wrap_here ("");
8207             fputs_filtered ("and ", gdb_stdout);
8208             wrap_here ("");
8209             printf_filtered ("%s...", pst->dependencies[i]->filename);
8210             wrap_here ("");     /* Flush output.  */
8211             gdb_flush (gdb_stdout);
8212           }
8213         psymtab_to_symtab_1 (pst->dependencies[i]);
8214       }
8215
8216   per_cu = (struct dwarf2_per_cu_data *) pst->read_symtab_private;
8217
8218   if (per_cu == NULL)
8219     {
8220       /* It's an include file, no symbols to read for it.
8221          Everything is in the parent symtab.  */
8222       pst->readin = 1;
8223       return;
8224     }
8225
8226   dw2_do_instantiate_symtab (per_cu);
8227 }
8228
8229 /* Trivial hash function for die_info: the hash value of a DIE
8230    is its offset in .debug_info for this objfile.  */
8231
8232 static hashval_t
8233 die_hash (const void *item)
8234 {
8235   const struct die_info *die = (const struct die_info *) item;
8236
8237   return to_underlying (die->sect_off);
8238 }
8239
8240 /* Trivial comparison function for die_info structures: two DIEs
8241    are equal if they have the same offset.  */
8242
8243 static int
8244 die_eq (const void *item_lhs, const void *item_rhs)
8245 {
8246   const struct die_info *die_lhs = (const struct die_info *) item_lhs;
8247   const struct die_info *die_rhs = (const struct die_info *) item_rhs;
8248
8249   return die_lhs->sect_off == die_rhs->sect_off;
8250 }
8251
8252 /* die_reader_func for load_full_comp_unit.
8253    This is identical to read_signatured_type_reader,
8254    but is kept separate for now.  */
8255
8256 static void
8257 load_full_comp_unit_reader (const struct die_reader_specs *reader,
8258                             const gdb_byte *info_ptr,
8259                             struct die_info *comp_unit_die,
8260                             int has_children,
8261                             void *data)
8262 {
8263   struct dwarf2_cu *cu = reader->cu;
8264   enum language *language_ptr = (enum language *) data;
8265
8266   gdb_assert (cu->die_hash == NULL);
8267   cu->die_hash =
8268     htab_create_alloc_ex (cu->header.length / 12,
8269                           die_hash,
8270                           die_eq,
8271                           NULL,
8272                           &cu->comp_unit_obstack,
8273                           hashtab_obstack_allocate,
8274                           dummy_obstack_deallocate);
8275
8276   if (has_children)
8277     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
8278                                                   &info_ptr, comp_unit_die);
8279   cu->dies = comp_unit_die;
8280   /* comp_unit_die is not stored in die_hash, no need.  */
8281
8282   /* We try not to read any attributes in this function, because not
8283      all CUs needed for references have been loaded yet, and symbol
8284      table processing isn't initialized.  But we have to set the CU language,
8285      or we won't be able to build types correctly.
8286      Similarly, if we do not read the producer, we can not apply
8287      producer-specific interpretation.  */
8288   prepare_one_comp_unit (cu, cu->dies, *language_ptr);
8289 }
8290
8291 /* Load the DIEs associated with PER_CU into memory.  */
8292
8293 static void
8294 load_full_comp_unit (struct dwarf2_per_cu_data *this_cu,
8295                      enum language pretend_language)
8296 {
8297   gdb_assert (! this_cu->is_debug_types);
8298
8299   init_cutu_and_read_dies (this_cu, NULL, 1, 1,
8300                            load_full_comp_unit_reader, &pretend_language);
8301 }
8302
8303 /* Add a DIE to the delayed physname list.  */
8304
8305 static void
8306 add_to_method_list (struct type *type, int fnfield_index, int index,
8307                     const char *name, struct die_info *die,
8308                     struct dwarf2_cu *cu)
8309 {
8310   struct delayed_method_info mi;
8311   mi.type = type;
8312   mi.fnfield_index = fnfield_index;
8313   mi.index = index;
8314   mi.name = name;
8315   mi.die = die;
8316   VEC_safe_push (delayed_method_info, cu->method_list, &mi);
8317 }
8318
8319 /* A cleanup for freeing the delayed method list.  */
8320
8321 static void
8322 free_delayed_list (void *ptr)
8323 {
8324   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr;
8325   if (cu->method_list != NULL)
8326     {
8327       VEC_free (delayed_method_info, cu->method_list);
8328       cu->method_list = NULL;
8329     }
8330 }
8331
8332 /* Check whether [PHYSNAME, PHYSNAME+LEN) ends with a modifier like
8333    "const" / "volatile".  If so, decrements LEN by the length of the
8334    modifier and return true.  Otherwise return false.  */
8335
8336 template<size_t N>
8337 static bool
8338 check_modifier (const char *physname, size_t &len, const char (&mod)[N])
8339 {
8340   size_t mod_len = sizeof (mod) - 1;
8341   if (len > mod_len && startswith (physname + (len - mod_len), mod))
8342     {
8343       len -= mod_len;
8344       return true;
8345     }
8346   return false;
8347 }
8348
8349 /* Compute the physnames of any methods on the CU's method list.
8350
8351    The computation of method physnames is delayed in order to avoid the
8352    (bad) condition that one of the method's formal parameters is of an as yet
8353    incomplete type.  */
8354
8355 static void
8356 compute_delayed_physnames (struct dwarf2_cu *cu)
8357 {
8358   int i;
8359   struct delayed_method_info *mi;
8360
8361   /* Only C++ delays computing physnames.  */
8362   if (VEC_empty (delayed_method_info, cu->method_list))
8363     return;
8364   gdb_assert (cu->language == language_cplus);
8365
8366   for (i = 0; VEC_iterate (delayed_method_info, cu->method_list, i, mi) ; ++i)
8367     {
8368       const char *physname;
8369       struct fn_fieldlist *fn_flp
8370         = &TYPE_FN_FIELDLIST (mi->type, mi->fnfield_index);
8371       physname = dwarf2_physname (mi->name, mi->die, cu);
8372       TYPE_FN_FIELD_PHYSNAME (fn_flp->fn_fields, mi->index)
8373         = physname ? physname : "";
8374
8375       /* Since there's no tag to indicate whether a method is a
8376          const/volatile overload, extract that information out of the
8377          demangled name.  */
8378       if (physname != NULL)
8379         {
8380           size_t len = strlen (physname);
8381
8382           while (1)
8383             {
8384               if (physname[len] == ')') /* shortcut */
8385                 break;
8386               else if (check_modifier (physname, len, " const"))
8387                 TYPE_FN_FIELD_CONST (fn_flp->fn_fields, mi->index) = 1;
8388               else if (check_modifier (physname, len, " volatile"))
8389                 TYPE_FN_FIELD_VOLATILE (fn_flp->fn_fields, mi->index) = 1;
8390               else
8391                 break;
8392             }
8393         }
8394     }
8395 }
8396
8397 /* Go objects should be embedded in a DW_TAG_module DIE,
8398    and it's not clear if/how imported objects will appear.
8399    To keep Go support simple until that's worked out,
8400    go back through what we've read and create something usable.
8401    We could do this while processing each DIE, and feels kinda cleaner,
8402    but that way is more invasive.
8403    This is to, for example, allow the user to type "p var" or "b main"
8404    without having to specify the package name, and allow lookups
8405    of module.object to work in contexts that use the expression
8406    parser.  */
8407
8408 static void
8409 fixup_go_packaging (struct dwarf2_cu *cu)
8410 {
8411   char *package_name = NULL;
8412   struct pending *list;
8413   int i;
8414
8415   for (list = global_symbols; list != NULL; list = list->next)
8416     {
8417       for (i = 0; i < list->nsyms; ++i)
8418         {
8419           struct symbol *sym = list->symbol[i];
8420
8421           if (SYMBOL_LANGUAGE (sym) == language_go
8422               && SYMBOL_CLASS (sym) == LOC_BLOCK)
8423             {
8424               char *this_package_name = go_symbol_package_name (sym);
8425
8426               if (this_package_name == NULL)
8427                 continue;
8428               if (package_name == NULL)
8429                 package_name = this_package_name;
8430               else
8431                 {
8432                   if (strcmp (package_name, this_package_name) != 0)
8433                     complaint (&symfile_complaints,
8434                                _("Symtab %s has objects from two different Go packages: %s and %s"),
8435                                (symbol_symtab (sym) != NULL
8436                                 ? symtab_to_filename_for_display
8437                                     (symbol_symtab (sym))
8438                                 : objfile_name (cu->objfile)),
8439                                this_package_name, package_name);
8440                   xfree (this_package_name);
8441                 }
8442             }
8443         }
8444     }
8445
8446   if (package_name != NULL)
8447     {
8448       struct objfile *objfile = cu->objfile;
8449       const char *saved_package_name
8450         = (const char *) obstack_copy0 (&objfile->per_bfd->storage_obstack,
8451                                         package_name,
8452                                         strlen (package_name));
8453       struct type *type = init_type (objfile, TYPE_CODE_MODULE, 0,
8454                                      saved_package_name);
8455       struct symbol *sym;
8456
8457       TYPE_TAG_NAME (type) = TYPE_NAME (type);
8458
8459       sym = allocate_symbol (objfile);
8460       SYMBOL_SET_LANGUAGE (sym, language_go, &objfile->objfile_obstack);
8461       SYMBOL_SET_NAMES (sym, saved_package_name,
8462                         strlen (saved_package_name), 0, objfile);
8463       /* This is not VAR_DOMAIN because we want a way to ensure a lookup of,
8464          e.g., "main" finds the "main" module and not C's main().  */
8465       SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
8466       SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
8467       SYMBOL_TYPE (sym) = type;
8468
8469       add_symbol_to_list (sym, &global_symbols);
8470
8471       xfree (package_name);
8472     }
8473 }
8474
8475 /* Return the symtab for PER_CU.  This works properly regardless of
8476    whether we're using the index or psymtabs.  */
8477
8478 static struct compunit_symtab *
8479 get_compunit_symtab (struct dwarf2_per_cu_data *per_cu)
8480 {
8481   return (dwarf2_per_objfile->using_index
8482           ? per_cu->v.quick->compunit_symtab
8483           : per_cu->v.psymtab->compunit_symtab);
8484 }
8485
8486 /* A helper function for computing the list of all symbol tables
8487    included by PER_CU.  */
8488
8489 static void
8490 recursively_compute_inclusions (VEC (compunit_symtab_ptr) **result,
8491                                 htab_t all_children, htab_t all_type_symtabs,
8492                                 struct dwarf2_per_cu_data *per_cu,
8493                                 struct compunit_symtab *immediate_parent)
8494 {
8495   void **slot;
8496   int ix;
8497   struct compunit_symtab *cust;
8498   struct dwarf2_per_cu_data *iter;
8499
8500   slot = htab_find_slot (all_children, per_cu, INSERT);
8501   if (*slot != NULL)
8502     {
8503       /* This inclusion and its children have been processed.  */
8504       return;
8505     }
8506
8507   *slot = per_cu;
8508   /* Only add a CU if it has a symbol table.  */
8509   cust = get_compunit_symtab (per_cu);
8510   if (cust != NULL)
8511     {
8512       /* If this is a type unit only add its symbol table if we haven't
8513          seen it yet (type unit per_cu's can share symtabs).  */
8514       if (per_cu->is_debug_types)
8515         {
8516           slot = htab_find_slot (all_type_symtabs, cust, INSERT);
8517           if (*slot == NULL)
8518             {
8519               *slot = cust;
8520               VEC_safe_push (compunit_symtab_ptr, *result, cust);
8521               if (cust->user == NULL)
8522                 cust->user = immediate_parent;
8523             }
8524         }
8525       else
8526         {
8527           VEC_safe_push (compunit_symtab_ptr, *result, cust);
8528           if (cust->user == NULL)
8529             cust->user = immediate_parent;
8530         }
8531     }
8532
8533   for (ix = 0;
8534        VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs, ix, iter);
8535        ++ix)
8536     {
8537       recursively_compute_inclusions (result, all_children,
8538                                       all_type_symtabs, iter, cust);
8539     }
8540 }
8541
8542 /* Compute the compunit_symtab 'includes' fields for the compunit_symtab of
8543    PER_CU.  */
8544
8545 static void
8546 compute_compunit_symtab_includes (struct dwarf2_per_cu_data *per_cu)
8547 {
8548   gdb_assert (! per_cu->is_debug_types);
8549
8550   if (!VEC_empty (dwarf2_per_cu_ptr, per_cu->imported_symtabs))
8551     {
8552       int ix, len;
8553       struct dwarf2_per_cu_data *per_cu_iter;
8554       struct compunit_symtab *compunit_symtab_iter;
8555       VEC (compunit_symtab_ptr) *result_symtabs = NULL;
8556       htab_t all_children, all_type_symtabs;
8557       struct compunit_symtab *cust = get_compunit_symtab (per_cu);
8558
8559       /* If we don't have a symtab, we can just skip this case.  */
8560       if (cust == NULL)
8561         return;
8562
8563       all_children = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8564                                         NULL, xcalloc, xfree);
8565       all_type_symtabs = htab_create_alloc (1, htab_hash_pointer, htab_eq_pointer,
8566                                             NULL, xcalloc, xfree);
8567
8568       for (ix = 0;
8569            VEC_iterate (dwarf2_per_cu_ptr, per_cu->imported_symtabs,
8570                         ix, per_cu_iter);
8571            ++ix)
8572         {
8573           recursively_compute_inclusions (&result_symtabs, all_children,
8574                                           all_type_symtabs, per_cu_iter,
8575                                           cust);
8576         }
8577
8578       /* Now we have a transitive closure of all the included symtabs.  */
8579       len = VEC_length (compunit_symtab_ptr, result_symtabs);
8580       cust->includes
8581         = XOBNEWVEC (&dwarf2_per_objfile->objfile->objfile_obstack,
8582                      struct compunit_symtab *, len + 1);
8583       for (ix = 0;
8584            VEC_iterate (compunit_symtab_ptr, result_symtabs, ix,
8585                         compunit_symtab_iter);
8586            ++ix)
8587         cust->includes[ix] = compunit_symtab_iter;
8588       cust->includes[len] = NULL;
8589
8590       VEC_free (compunit_symtab_ptr, result_symtabs);
8591       htab_delete (all_children);
8592       htab_delete (all_type_symtabs);
8593     }
8594 }
8595
8596 /* Compute the 'includes' field for the symtabs of all the CUs we just
8597    read.  */
8598
8599 static void
8600 process_cu_includes (void)
8601 {
8602   int ix;
8603   struct dwarf2_per_cu_data *iter;
8604
8605   for (ix = 0;
8606        VEC_iterate (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus,
8607                     ix, iter);
8608        ++ix)
8609     {
8610       if (! iter->is_debug_types)
8611         compute_compunit_symtab_includes (iter);
8612     }
8613
8614   VEC_free (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus);
8615 }
8616
8617 /* Generate full symbol information for PER_CU, whose DIEs have
8618    already been loaded into memory.  */
8619
8620 static void
8621 process_full_comp_unit (struct dwarf2_per_cu_data *per_cu,
8622                         enum language pretend_language)
8623 {
8624   struct dwarf2_cu *cu = per_cu->cu;
8625   struct objfile *objfile = per_cu->objfile;
8626   struct gdbarch *gdbarch = get_objfile_arch (objfile);
8627   CORE_ADDR lowpc, highpc;
8628   struct compunit_symtab *cust;
8629   struct cleanup *delayed_list_cleanup;
8630   CORE_ADDR baseaddr;
8631   struct block *static_block;
8632   CORE_ADDR addr;
8633
8634   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
8635
8636   buildsym_init ();
8637   scoped_free_pendings free_pending;
8638   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8639
8640   cu->list_in_scope = &file_symbols;
8641
8642   cu->language = pretend_language;
8643   cu->language_defn = language_def (cu->language);
8644
8645   /* Do line number decoding in read_file_scope () */
8646   process_die (cu->dies, cu);
8647
8648   /* For now fudge the Go package.  */
8649   if (cu->language == language_go)
8650     fixup_go_packaging (cu);
8651
8652   /* Now that we have processed all the DIEs in the CU, all the types 
8653      should be complete, and it should now be safe to compute all of the
8654      physnames.  */
8655   compute_delayed_physnames (cu);
8656   do_cleanups (delayed_list_cleanup);
8657
8658   /* Some compilers don't define a DW_AT_high_pc attribute for the
8659      compilation unit.  If the DW_AT_high_pc is missing, synthesize
8660      it, by scanning the DIE's below the compilation unit.  */
8661   get_scope_pc_bounds (cu->dies, &lowpc, &highpc, cu);
8662
8663   addr = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
8664   static_block = end_symtab_get_static_block (addr, 0, 1);
8665
8666   /* If the comp unit has DW_AT_ranges, it may have discontiguous ranges.
8667      Also, DW_AT_ranges may record ranges not belonging to any child DIEs
8668      (such as virtual method tables).  Record the ranges in STATIC_BLOCK's
8669      addrmap to help ensure it has an accurate map of pc values belonging to
8670      this comp unit.  */
8671   dwarf2_record_block_ranges (cu->dies, static_block, baseaddr, cu);
8672
8673   cust = end_symtab_from_static_block (static_block,
8674                                        SECT_OFF_TEXT (objfile), 0);
8675
8676   if (cust != NULL)
8677     {
8678       int gcc_4_minor = producer_is_gcc_ge_4 (cu->producer);
8679
8680       /* Set symtab language to language from DW_AT_language.  If the
8681          compilation is from a C file generated by language preprocessors, do
8682          not set the language if it was already deduced by start_subfile.  */
8683       if (!(cu->language == language_c
8684             && COMPUNIT_FILETABS (cust)->language != language_unknown))
8685         COMPUNIT_FILETABS (cust)->language = cu->language;
8686
8687       /* GCC-4.0 has started to support -fvar-tracking.  GCC-3.x still can
8688          produce DW_AT_location with location lists but it can be possibly
8689          invalid without -fvar-tracking.  Still up to GCC-4.4.x incl. 4.4.0
8690          there were bugs in prologue debug info, fixed later in GCC-4.5
8691          by "unwind info for epilogues" patch (which is not directly related).
8692
8693          For -gdwarf-4 type units LOCATIONS_VALID indication is fortunately not
8694          needed, it would be wrong due to missing DW_AT_producer there.
8695
8696          Still one can confuse GDB by using non-standard GCC compilation
8697          options - this waits on GCC PR other/32998 (-frecord-gcc-switches).
8698          */ 
8699       if (cu->has_loclist && gcc_4_minor >= 5)
8700         cust->locations_valid = 1;
8701
8702       if (gcc_4_minor >= 5)
8703         cust->epilogue_unwind_valid = 1;
8704
8705       cust->call_site_htab = cu->call_site_htab;
8706     }
8707
8708   if (dwarf2_per_objfile->using_index)
8709     per_cu->v.quick->compunit_symtab = cust;
8710   else
8711     {
8712       struct partial_symtab *pst = per_cu->v.psymtab;
8713       pst->compunit_symtab = cust;
8714       pst->readin = 1;
8715     }
8716
8717   /* Push it for inclusion processing later.  */
8718   VEC_safe_push (dwarf2_per_cu_ptr, dwarf2_per_objfile->just_read_cus, per_cu);
8719 }
8720
8721 /* Generate full symbol information for type unit PER_CU, whose DIEs have
8722    already been loaded into memory.  */
8723
8724 static void
8725 process_full_type_unit (struct dwarf2_per_cu_data *per_cu,
8726                         enum language pretend_language)
8727 {
8728   struct dwarf2_cu *cu = per_cu->cu;
8729   struct objfile *objfile = per_cu->objfile;
8730   struct compunit_symtab *cust;
8731   struct cleanup *delayed_list_cleanup;
8732   struct signatured_type *sig_type;
8733
8734   gdb_assert (per_cu->is_debug_types);
8735   sig_type = (struct signatured_type *) per_cu;
8736
8737   buildsym_init ();
8738   scoped_free_pendings free_pending;
8739   delayed_list_cleanup = make_cleanup (free_delayed_list, cu);
8740
8741   cu->list_in_scope = &file_symbols;
8742
8743   cu->language = pretend_language;
8744   cu->language_defn = language_def (cu->language);
8745
8746   /* The symbol tables are set up in read_type_unit_scope.  */
8747   process_die (cu->dies, cu);
8748
8749   /* For now fudge the Go package.  */
8750   if (cu->language == language_go)
8751     fixup_go_packaging (cu);
8752
8753   /* Now that we have processed all the DIEs in the CU, all the types 
8754      should be complete, and it should now be safe to compute all of the
8755      physnames.  */
8756   compute_delayed_physnames (cu);
8757   do_cleanups (delayed_list_cleanup);
8758
8759   /* TUs share symbol tables.
8760      If this is the first TU to use this symtab, complete the construction
8761      of it with end_expandable_symtab.  Otherwise, complete the addition of
8762      this TU's symbols to the existing symtab.  */
8763   if (sig_type->type_unit_group->compunit_symtab == NULL)
8764     {
8765       cust = end_expandable_symtab (0, SECT_OFF_TEXT (objfile));
8766       sig_type->type_unit_group->compunit_symtab = cust;
8767
8768       if (cust != NULL)
8769         {
8770           /* Set symtab language to language from DW_AT_language.  If the
8771              compilation is from a C file generated by language preprocessors,
8772              do not set the language if it was already deduced by
8773              start_subfile.  */
8774           if (!(cu->language == language_c
8775                 && COMPUNIT_FILETABS (cust)->language != language_c))
8776             COMPUNIT_FILETABS (cust)->language = cu->language;
8777         }
8778     }
8779   else
8780     {
8781       augment_type_symtab ();
8782       cust = sig_type->type_unit_group->compunit_symtab;
8783     }
8784
8785   if (dwarf2_per_objfile->using_index)
8786     per_cu->v.quick->compunit_symtab = cust;
8787   else
8788     {
8789       struct partial_symtab *pst = per_cu->v.psymtab;
8790       pst->compunit_symtab = cust;
8791       pst->readin = 1;
8792     }
8793 }
8794
8795 /* Process an imported unit DIE.  */
8796
8797 static void
8798 process_imported_unit_die (struct die_info *die, struct dwarf2_cu *cu)
8799 {
8800   struct attribute *attr;
8801
8802   /* For now we don't handle imported units in type units.  */
8803   if (cu->per_cu->is_debug_types)
8804     {
8805       error (_("Dwarf Error: DW_TAG_imported_unit is not"
8806                " supported in type units [in module %s]"),
8807              objfile_name (cu->objfile));
8808     }
8809
8810   attr = dwarf2_attr (die, DW_AT_import, cu);
8811   if (attr != NULL)
8812     {
8813       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
8814       bool is_dwz = (attr->form == DW_FORM_GNU_ref_alt || cu->per_cu->is_dwz);
8815       dwarf2_per_cu_data *per_cu
8816         = dwarf2_find_containing_comp_unit (sect_off, is_dwz, cu->objfile);
8817
8818       /* If necessary, add it to the queue and load its DIEs.  */
8819       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
8820         load_full_comp_unit (per_cu, cu->language);
8821
8822       VEC_safe_push (dwarf2_per_cu_ptr, cu->per_cu->imported_symtabs,
8823                      per_cu);
8824     }
8825 }
8826
8827 /* RAII object that represents a process_die scope: i.e.,
8828    starts/finishes processing a DIE.  */
8829 class process_die_scope
8830 {
8831 public:
8832   process_die_scope (die_info *die, dwarf2_cu *cu)
8833     : m_die (die), m_cu (cu)
8834   {
8835     /* We should only be processing DIEs not already in process.  */
8836     gdb_assert (!m_die->in_process);
8837     m_die->in_process = true;
8838   }
8839
8840   ~process_die_scope ()
8841   {
8842     m_die->in_process = false;
8843
8844     /* If we're done processing the DIE for the CU that owns the line
8845        header, we don't need the line header anymore.  */
8846     if (m_cu->line_header_die_owner == m_die)
8847       {
8848         delete m_cu->line_header;
8849         m_cu->line_header = NULL;
8850         m_cu->line_header_die_owner = NULL;
8851       }
8852   }
8853
8854 private:
8855   die_info *m_die;
8856   dwarf2_cu *m_cu;
8857 };
8858
8859 /* Process a die and its children.  */
8860
8861 static void
8862 process_die (struct die_info *die, struct dwarf2_cu *cu)
8863 {
8864   process_die_scope scope (die, cu);
8865
8866   switch (die->tag)
8867     {
8868     case DW_TAG_padding:
8869       break;
8870     case DW_TAG_compile_unit:
8871     case DW_TAG_partial_unit:
8872       read_file_scope (die, cu);
8873       break;
8874     case DW_TAG_type_unit:
8875       read_type_unit_scope (die, cu);
8876       break;
8877     case DW_TAG_subprogram:
8878     case DW_TAG_inlined_subroutine:
8879       read_func_scope (die, cu);
8880       break;
8881     case DW_TAG_lexical_block:
8882     case DW_TAG_try_block:
8883     case DW_TAG_catch_block:
8884       read_lexical_block_scope (die, cu);
8885       break;
8886     case DW_TAG_call_site:
8887     case DW_TAG_GNU_call_site:
8888       read_call_site_scope (die, cu);
8889       break;
8890     case DW_TAG_class_type:
8891     case DW_TAG_interface_type:
8892     case DW_TAG_structure_type:
8893     case DW_TAG_union_type:
8894       process_structure_scope (die, cu);
8895       break;
8896     case DW_TAG_enumeration_type:
8897       process_enumeration_scope (die, cu);
8898       break;
8899
8900     /* These dies have a type, but processing them does not create
8901        a symbol or recurse to process the children.  Therefore we can
8902        read them on-demand through read_type_die.  */
8903     case DW_TAG_subroutine_type:
8904     case DW_TAG_set_type:
8905     case DW_TAG_array_type:
8906     case DW_TAG_pointer_type:
8907     case DW_TAG_ptr_to_member_type:
8908     case DW_TAG_reference_type:
8909     case DW_TAG_rvalue_reference_type:
8910     case DW_TAG_string_type:
8911       break;
8912
8913     case DW_TAG_base_type:
8914     case DW_TAG_subrange_type:
8915     case DW_TAG_typedef:
8916       /* Add a typedef symbol for the type definition, if it has a
8917          DW_AT_name.  */
8918       new_symbol (die, read_type_die (die, cu), cu);
8919       break;
8920     case DW_TAG_common_block:
8921       read_common_block (die, cu);
8922       break;
8923     case DW_TAG_common_inclusion:
8924       break;
8925     case DW_TAG_namespace:
8926       cu->processing_has_namespace_info = 1;
8927       read_namespace (die, cu);
8928       break;
8929     case DW_TAG_module:
8930       cu->processing_has_namespace_info = 1;
8931       read_module (die, cu);
8932       break;
8933     case DW_TAG_imported_declaration:
8934       cu->processing_has_namespace_info = 1;
8935       if (read_namespace_alias (die, cu))
8936         break;
8937       /* The declaration is not a global namespace alias: fall through.  */
8938     case DW_TAG_imported_module:
8939       cu->processing_has_namespace_info = 1;
8940       if (die->child != NULL && (die->tag == DW_TAG_imported_declaration
8941                                  || cu->language != language_fortran))
8942         complaint (&symfile_complaints, _("Tag '%s' has unexpected children"),
8943                    dwarf_tag_name (die->tag));
8944       read_import_statement (die, cu);
8945       break;
8946
8947     case DW_TAG_imported_unit:
8948       process_imported_unit_die (die, cu);
8949       break;
8950
8951     default:
8952       new_symbol (die, NULL, cu);
8953       break;
8954     }
8955 }
8956 \f
8957 /* DWARF name computation.  */
8958
8959 /* A helper function for dwarf2_compute_name which determines whether DIE
8960    needs to have the name of the scope prepended to the name listed in the
8961    die.  */
8962
8963 static int
8964 die_needs_namespace (struct die_info *die, struct dwarf2_cu *cu)
8965 {
8966   struct attribute *attr;
8967
8968   switch (die->tag)
8969     {
8970     case DW_TAG_namespace:
8971     case DW_TAG_typedef:
8972     case DW_TAG_class_type:
8973     case DW_TAG_interface_type:
8974     case DW_TAG_structure_type:
8975     case DW_TAG_union_type:
8976     case DW_TAG_enumeration_type:
8977     case DW_TAG_enumerator:
8978     case DW_TAG_subprogram:
8979     case DW_TAG_inlined_subroutine:
8980     case DW_TAG_member:
8981     case DW_TAG_imported_declaration:
8982       return 1;
8983
8984     case DW_TAG_variable:
8985     case DW_TAG_constant:
8986       /* We only need to prefix "globally" visible variables.  These include
8987          any variable marked with DW_AT_external or any variable that
8988          lives in a namespace.  [Variables in anonymous namespaces
8989          require prefixing, but they are not DW_AT_external.]  */
8990
8991       if (dwarf2_attr (die, DW_AT_specification, cu))
8992         {
8993           struct dwarf2_cu *spec_cu = cu;
8994
8995           return die_needs_namespace (die_specification (die, &spec_cu),
8996                                       spec_cu);
8997         }
8998
8999       attr = dwarf2_attr (die, DW_AT_external, cu);
9000       if (attr == NULL && die->parent->tag != DW_TAG_namespace
9001           && die->parent->tag != DW_TAG_module)
9002         return 0;
9003       /* A variable in a lexical block of some kind does not need a
9004          namespace, even though in C++ such variables may be external
9005          and have a mangled name.  */
9006       if (die->parent->tag ==  DW_TAG_lexical_block
9007           || die->parent->tag ==  DW_TAG_try_block
9008           || die->parent->tag ==  DW_TAG_catch_block
9009           || die->parent->tag == DW_TAG_subprogram)
9010         return 0;
9011       return 1;
9012
9013     default:
9014       return 0;
9015     }
9016 }
9017
9018 /* Return the DIE's linkage name attribute, either DW_AT_linkage_name
9019    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9020    defined for the given DIE.  */
9021
9022 static struct attribute *
9023 dw2_linkage_name_attr (struct die_info *die, struct dwarf2_cu *cu)
9024 {
9025   struct attribute *attr;
9026
9027   attr = dwarf2_attr (die, DW_AT_linkage_name, cu);
9028   if (attr == NULL)
9029     attr = dwarf2_attr (die, DW_AT_MIPS_linkage_name, cu);
9030
9031   return attr;
9032 }
9033
9034 /* Return the DIE's linkage name as a string, either DW_AT_linkage_name
9035    or DW_AT_MIPS_linkage_name.  Returns NULL if the attribute is not
9036    defined for the given DIE.  */
9037
9038 static const char *
9039 dw2_linkage_name (struct die_info *die, struct dwarf2_cu *cu)
9040 {
9041   const char *linkage_name;
9042
9043   linkage_name = dwarf2_string_attr (die, DW_AT_linkage_name, cu);
9044   if (linkage_name == NULL)
9045     linkage_name = dwarf2_string_attr (die, DW_AT_MIPS_linkage_name, cu);
9046
9047   return linkage_name;
9048 }
9049
9050 /* Compute the fully qualified name of DIE in CU.  If PHYSNAME is nonzero,
9051    compute the physname for the object, which include a method's:
9052    - formal parameters (C++),
9053    - receiver type (Go),
9054
9055    The term "physname" is a bit confusing.
9056    For C++, for example, it is the demangled name.
9057    For Go, for example, it's the mangled name.
9058
9059    For Ada, return the DIE's linkage name rather than the fully qualified
9060    name.  PHYSNAME is ignored..
9061
9062    The result is allocated on the objfile_obstack and canonicalized.  */
9063
9064 static const char *
9065 dwarf2_compute_name (const char *name,
9066                      struct die_info *die, struct dwarf2_cu *cu,
9067                      int physname)
9068 {
9069   struct objfile *objfile = cu->objfile;
9070
9071   if (name == NULL)
9072     name = dwarf2_name (die, cu);
9073
9074   /* For Fortran GDB prefers DW_AT_*linkage_name for the physname if present
9075      but otherwise compute it by typename_concat inside GDB.
9076      FIXME: Actually this is not really true, or at least not always true.
9077      It's all very confusing.  SYMBOL_SET_NAMES doesn't try to demangle
9078      Fortran names because there is no mangling standard.  So new_symbol_full
9079      will set the demangled name to the result of dwarf2_full_name, and it is
9080      the demangled name that GDB uses if it exists.  */
9081   if (cu->language == language_ada
9082       || (cu->language == language_fortran && physname))
9083     {
9084       /* For Ada unit, we prefer the linkage name over the name, as
9085          the former contains the exported name, which the user expects
9086          to be able to reference.  Ideally, we want the user to be able
9087          to reference this entity using either natural or linkage name,
9088          but we haven't started looking at this enhancement yet.  */
9089       const char *linkage_name = dw2_linkage_name (die, cu);
9090
9091       if (linkage_name != NULL)
9092         return linkage_name;
9093     }
9094
9095   /* These are the only languages we know how to qualify names in.  */
9096   if (name != NULL
9097       && (cu->language == language_cplus
9098           || cu->language == language_fortran || cu->language == language_d
9099           || cu->language == language_rust))
9100     {
9101       if (die_needs_namespace (die, cu))
9102         {
9103           long length;
9104           const char *prefix;
9105           const char *canonical_name = NULL;
9106
9107           string_file buf;
9108
9109           prefix = determine_prefix (die, cu);
9110           if (*prefix != '\0')
9111             {
9112               char *prefixed_name = typename_concat (NULL, prefix, name,
9113                                                      physname, cu);
9114
9115               buf.puts (prefixed_name);
9116               xfree (prefixed_name);
9117             }
9118           else
9119             buf.puts (name);
9120
9121           /* Template parameters may be specified in the DIE's DW_AT_name, or
9122              as children with DW_TAG_template_type_param or
9123              DW_TAG_value_type_param.  If the latter, add them to the name
9124              here.  If the name already has template parameters, then
9125              skip this step; some versions of GCC emit both, and
9126              it is more efficient to use the pre-computed name.
9127
9128              Something to keep in mind about this process: it is very
9129              unlikely, or in some cases downright impossible, to produce
9130              something that will match the mangled name of a function.
9131              If the definition of the function has the same debug info,
9132              we should be able to match up with it anyway.  But fallbacks
9133              using the minimal symbol, for instance to find a method
9134              implemented in a stripped copy of libstdc++, will not work.
9135              If we do not have debug info for the definition, we will have to
9136              match them up some other way.
9137
9138              When we do name matching there is a related problem with function
9139              templates; two instantiated function templates are allowed to
9140              differ only by their return types, which we do not add here.  */
9141
9142           if (cu->language == language_cplus && strchr (name, '<') == NULL)
9143             {
9144               struct attribute *attr;
9145               struct die_info *child;
9146               int first = 1;
9147
9148               die->building_fullname = 1;
9149
9150               for (child = die->child; child != NULL; child = child->sibling)
9151                 {
9152                   struct type *type;
9153                   LONGEST value;
9154                   const gdb_byte *bytes;
9155                   struct dwarf2_locexpr_baton *baton;
9156                   struct value *v;
9157
9158                   if (child->tag != DW_TAG_template_type_param
9159                       && child->tag != DW_TAG_template_value_param)
9160                     continue;
9161
9162                   if (first)
9163                     {
9164                       buf.puts ("<");
9165                       first = 0;
9166                     }
9167                   else
9168                     buf.puts (", ");
9169
9170                   attr = dwarf2_attr (child, DW_AT_type, cu);
9171                   if (attr == NULL)
9172                     {
9173                       complaint (&symfile_complaints,
9174                                  _("template parameter missing DW_AT_type"));
9175                       buf.puts ("UNKNOWN_TYPE");
9176                       continue;
9177                     }
9178                   type = die_type (child, cu);
9179
9180                   if (child->tag == DW_TAG_template_type_param)
9181                     {
9182                       c_print_type (type, "", &buf, -1, 0, &type_print_raw_options);
9183                       continue;
9184                     }
9185
9186                   attr = dwarf2_attr (child, DW_AT_const_value, cu);
9187                   if (attr == NULL)
9188                     {
9189                       complaint (&symfile_complaints,
9190                                  _("template parameter missing "
9191                                    "DW_AT_const_value"));
9192                       buf.puts ("UNKNOWN_VALUE");
9193                       continue;
9194                     }
9195
9196                   dwarf2_const_value_attr (attr, type, name,
9197                                            &cu->comp_unit_obstack, cu,
9198                                            &value, &bytes, &baton);
9199
9200                   if (TYPE_NOSIGN (type))
9201                     /* GDB prints characters as NUMBER 'CHAR'.  If that's
9202                        changed, this can use value_print instead.  */
9203                     c_printchar (value, type, &buf);
9204                   else
9205                     {
9206                       struct value_print_options opts;
9207
9208                       if (baton != NULL)
9209                         v = dwarf2_evaluate_loc_desc (type, NULL,
9210                                                       baton->data,
9211                                                       baton->size,
9212                                                       baton->per_cu);
9213                       else if (bytes != NULL)
9214                         {
9215                           v = allocate_value (type);
9216                           memcpy (value_contents_writeable (v), bytes,
9217                                   TYPE_LENGTH (type));
9218                         }
9219                       else
9220                         v = value_from_longest (type, value);
9221
9222                       /* Specify decimal so that we do not depend on
9223                          the radix.  */
9224                       get_formatted_print_options (&opts, 'd');
9225                       opts.raw = 1;
9226                       value_print (v, &buf, &opts);
9227                       release_value (v);
9228                       value_free (v);
9229                     }
9230                 }
9231
9232               die->building_fullname = 0;
9233
9234               if (!first)
9235                 {
9236                   /* Close the argument list, with a space if necessary
9237                      (nested templates).  */
9238                   if (!buf.empty () && buf.string ().back () == '>')
9239                     buf.puts (" >");
9240                   else
9241                     buf.puts (">");
9242                 }
9243             }
9244
9245           /* For C++ methods, append formal parameter type
9246              information, if PHYSNAME.  */
9247
9248           if (physname && die->tag == DW_TAG_subprogram
9249               && cu->language == language_cplus)
9250             {
9251               struct type *type = read_type_die (die, cu);
9252
9253               c_type_print_args (type, &buf, 1, cu->language,
9254                                  &type_print_raw_options);
9255
9256               if (cu->language == language_cplus)
9257                 {
9258                   /* Assume that an artificial first parameter is
9259                      "this", but do not crash if it is not.  RealView
9260                      marks unnamed (and thus unused) parameters as
9261                      artificial; there is no way to differentiate
9262                      the two cases.  */
9263                   if (TYPE_NFIELDS (type) > 0
9264                       && TYPE_FIELD_ARTIFICIAL (type, 0)
9265                       && TYPE_CODE (TYPE_FIELD_TYPE (type, 0)) == TYPE_CODE_PTR
9266                       && TYPE_CONST (TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (type,
9267                                                                         0))))
9268                     buf.puts (" const");
9269                 }
9270             }
9271
9272           const std::string &intermediate_name = buf.string ();
9273
9274           if (cu->language == language_cplus)
9275             canonical_name
9276               = dwarf2_canonicalize_name (intermediate_name.c_str (), cu,
9277                                           &objfile->per_bfd->storage_obstack);
9278
9279           /* If we only computed INTERMEDIATE_NAME, or if
9280              INTERMEDIATE_NAME is already canonical, then we need to
9281              copy it to the appropriate obstack.  */
9282           if (canonical_name == NULL || canonical_name == intermediate_name.c_str ())
9283             name = ((const char *)
9284                     obstack_copy0 (&objfile->per_bfd->storage_obstack,
9285                                    intermediate_name.c_str (),
9286                                    intermediate_name.length ()));
9287           else
9288             name = canonical_name;
9289         }
9290     }
9291
9292   return name;
9293 }
9294
9295 /* Return the fully qualified name of DIE, based on its DW_AT_name.
9296    If scope qualifiers are appropriate they will be added.  The result
9297    will be allocated on the storage_obstack, or NULL if the DIE does
9298    not have a name.  NAME may either be from a previous call to
9299    dwarf2_name or NULL.
9300
9301    The output string will be canonicalized (if C++).  */
9302
9303 static const char *
9304 dwarf2_full_name (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9305 {
9306   return dwarf2_compute_name (name, die, cu, 0);
9307 }
9308
9309 /* Construct a physname for the given DIE in CU.  NAME may either be
9310    from a previous call to dwarf2_name or NULL.  The result will be
9311    allocated on the objfile_objstack or NULL if the DIE does not have a
9312    name.
9313
9314    The output string will be canonicalized (if C++).  */
9315
9316 static const char *
9317 dwarf2_physname (const char *name, struct die_info *die, struct dwarf2_cu *cu)
9318 {
9319   struct objfile *objfile = cu->objfile;
9320   const char *retval, *mangled = NULL, *canon = NULL;
9321   int need_copy = 1;
9322
9323   /* In this case dwarf2_compute_name is just a shortcut not building anything
9324      on its own.  */
9325   if (!die_needs_namespace (die, cu))
9326     return dwarf2_compute_name (name, die, cu, 1);
9327
9328   mangled = dw2_linkage_name (die, cu);
9329
9330   /* rustc emits invalid values for DW_AT_linkage_name.  Ignore these.
9331      See https://github.com/rust-lang/rust/issues/32925.  */
9332   if (cu->language == language_rust && mangled != NULL
9333       && strchr (mangled, '{') != NULL)
9334     mangled = NULL;
9335
9336   /* DW_AT_linkage_name is missing in some cases - depend on what GDB
9337      has computed.  */
9338   gdb::unique_xmalloc_ptr<char> demangled;
9339   if (mangled != NULL)
9340     {
9341       /* Use DMGL_RET_DROP for C++ template functions to suppress their return
9342          type.  It is easier for GDB users to search for such functions as
9343          `name(params)' than `long name(params)'.  In such case the minimal
9344          symbol names do not match the full symbol names but for template
9345          functions there is never a need to look up their definition from their
9346          declaration so the only disadvantage remains the minimal symbol
9347          variant `long name(params)' does not have the proper inferior type.
9348          */
9349
9350       if (cu->language == language_go)
9351         {
9352           /* This is a lie, but we already lie to the caller new_symbol_full.
9353              new_symbol_full assumes we return the mangled name.
9354              This just undoes that lie until things are cleaned up.  */
9355         }
9356       else
9357         {
9358           demangled.reset (gdb_demangle (mangled,
9359                                          (DMGL_PARAMS | DMGL_ANSI
9360                                           | DMGL_RET_DROP)));
9361         }
9362       if (demangled)
9363         canon = demangled.get ();
9364       else
9365         {
9366           canon = mangled;
9367           need_copy = 0;
9368         }
9369     }
9370
9371   if (canon == NULL || check_physname)
9372     {
9373       const char *physname = dwarf2_compute_name (name, die, cu, 1);
9374
9375       if (canon != NULL && strcmp (physname, canon) != 0)
9376         {
9377           /* It may not mean a bug in GDB.  The compiler could also
9378              compute DW_AT_linkage_name incorrectly.  But in such case
9379              GDB would need to be bug-to-bug compatible.  */
9380
9381           complaint (&symfile_complaints,
9382                      _("Computed physname <%s> does not match demangled <%s> "
9383                        "(from linkage <%s>) - DIE at 0x%x [in module %s]"),
9384                      physname, canon, mangled, to_underlying (die->sect_off),
9385                      objfile_name (objfile));
9386
9387           /* Prefer DW_AT_linkage_name (in the CANON form) - when it
9388              is available here - over computed PHYSNAME.  It is safer
9389              against both buggy GDB and buggy compilers.  */
9390
9391           retval = canon;
9392         }
9393       else
9394         {
9395           retval = physname;
9396           need_copy = 0;
9397         }
9398     }
9399   else
9400     retval = canon;
9401
9402   if (need_copy)
9403     retval = ((const char *)
9404               obstack_copy0 (&objfile->per_bfd->storage_obstack,
9405                              retval, strlen (retval)));
9406
9407   return retval;
9408 }
9409
9410 /* Inspect DIE in CU for a namespace alias.  If one exists, record
9411    a new symbol for it.
9412
9413    Returns 1 if a namespace alias was recorded, 0 otherwise.  */
9414
9415 static int
9416 read_namespace_alias (struct die_info *die, struct dwarf2_cu *cu)
9417 {
9418   struct attribute *attr;
9419
9420   /* If the die does not have a name, this is not a namespace
9421      alias.  */
9422   attr = dwarf2_attr (die, DW_AT_name, cu);
9423   if (attr != NULL)
9424     {
9425       int num;
9426       struct die_info *d = die;
9427       struct dwarf2_cu *imported_cu = cu;
9428
9429       /* If the compiler has nested DW_AT_imported_declaration DIEs,
9430          keep inspecting DIEs until we hit the underlying import.  */
9431 #define MAX_NESTED_IMPORTED_DECLARATIONS 100
9432       for (num = 0; num  < MAX_NESTED_IMPORTED_DECLARATIONS; ++num)
9433         {
9434           attr = dwarf2_attr (d, DW_AT_import, cu);
9435           if (attr == NULL)
9436             break;
9437
9438           d = follow_die_ref (d, attr, &imported_cu);
9439           if (d->tag != DW_TAG_imported_declaration)
9440             break;
9441         }
9442
9443       if (num == MAX_NESTED_IMPORTED_DECLARATIONS)
9444         {
9445           complaint (&symfile_complaints,
9446                      _("DIE at 0x%x has too many recursively imported "
9447                        "declarations"), to_underlying (d->sect_off));
9448           return 0;
9449         }
9450
9451       if (attr != NULL)
9452         {
9453           struct type *type;
9454           sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
9455
9456           type = get_die_type_at_offset (sect_off, cu->per_cu);
9457           if (type != NULL && TYPE_CODE (type) == TYPE_CODE_NAMESPACE)
9458             {
9459               /* This declaration is a global namespace alias.  Add
9460                  a symbol for it whose type is the aliased namespace.  */
9461               new_symbol (die, type, cu);
9462               return 1;
9463             }
9464         }
9465     }
9466
9467   return 0;
9468 }
9469
9470 /* Return the using directives repository (global or local?) to use in the
9471    current context for LANGUAGE.
9472
9473    For Ada, imported declarations can materialize renamings, which *may* be
9474    global.  However it is impossible (for now?) in DWARF to distinguish
9475    "external" imported declarations and "static" ones.  As all imported
9476    declarations seem to be static in all other languages, make them all CU-wide
9477    global only in Ada.  */
9478
9479 static struct using_direct **
9480 using_directives (enum language language)
9481 {
9482   if (language == language_ada && context_stack_depth == 0)
9483     return &global_using_directives;
9484   else
9485     return &local_using_directives;
9486 }
9487
9488 /* Read the import statement specified by the given die and record it.  */
9489
9490 static void
9491 read_import_statement (struct die_info *die, struct dwarf2_cu *cu)
9492 {
9493   struct objfile *objfile = cu->objfile;
9494   struct attribute *import_attr;
9495   struct die_info *imported_die, *child_die;
9496   struct dwarf2_cu *imported_cu;
9497   const char *imported_name;
9498   const char *imported_name_prefix;
9499   const char *canonical_name;
9500   const char *import_alias;
9501   const char *imported_declaration = NULL;
9502   const char *import_prefix;
9503   std::vector<const char *> excludes;
9504
9505   import_attr = dwarf2_attr (die, DW_AT_import, cu);
9506   if (import_attr == NULL)
9507     {
9508       complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9509                  dwarf_tag_name (die->tag));
9510       return;
9511     }
9512
9513   imported_cu = cu;
9514   imported_die = follow_die_ref_or_sig (die, import_attr, &imported_cu);
9515   imported_name = dwarf2_name (imported_die, imported_cu);
9516   if (imported_name == NULL)
9517     {
9518       /* GCC bug: https://bugzilla.redhat.com/show_bug.cgi?id=506524
9519
9520         The import in the following code:
9521         namespace A
9522           {
9523             typedef int B;
9524           }
9525
9526         int main ()
9527           {
9528             using A::B;
9529             B b;
9530             return b;
9531           }
9532
9533         ...
9534          <2><51>: Abbrev Number: 3 (DW_TAG_imported_declaration)
9535             <52>   DW_AT_decl_file   : 1
9536             <53>   DW_AT_decl_line   : 6
9537             <54>   DW_AT_import      : <0x75>
9538          <2><58>: Abbrev Number: 4 (DW_TAG_typedef)
9539             <59>   DW_AT_name        : B
9540             <5b>   DW_AT_decl_file   : 1
9541             <5c>   DW_AT_decl_line   : 2
9542             <5d>   DW_AT_type        : <0x6e>
9543         ...
9544          <1><75>: Abbrev Number: 7 (DW_TAG_base_type)
9545             <76>   DW_AT_byte_size   : 4
9546             <77>   DW_AT_encoding    : 5        (signed)
9547
9548         imports the wrong die ( 0x75 instead of 0x58 ).
9549         This case will be ignored until the gcc bug is fixed.  */
9550       return;
9551     }
9552
9553   /* Figure out the local name after import.  */
9554   import_alias = dwarf2_name (die, cu);
9555
9556   /* Figure out where the statement is being imported to.  */
9557   import_prefix = determine_prefix (die, cu);
9558
9559   /* Figure out what the scope of the imported die is and prepend it
9560      to the name of the imported die.  */
9561   imported_name_prefix = determine_prefix (imported_die, imported_cu);
9562
9563   if (imported_die->tag != DW_TAG_namespace
9564       && imported_die->tag != DW_TAG_module)
9565     {
9566       imported_declaration = imported_name;
9567       canonical_name = imported_name_prefix;
9568     }
9569   else if (strlen (imported_name_prefix) > 0)
9570     canonical_name = obconcat (&objfile->objfile_obstack,
9571                                imported_name_prefix,
9572                                (cu->language == language_d ? "." : "::"),
9573                                imported_name, (char *) NULL);
9574   else
9575     canonical_name = imported_name;
9576
9577   if (die->tag == DW_TAG_imported_module && cu->language == language_fortran)
9578     for (child_die = die->child; child_die && child_die->tag;
9579          child_die = sibling_die (child_die))
9580       {
9581         /* DWARF-4: A Fortran use statement with a “rename list” may be
9582            represented by an imported module entry with an import attribute
9583            referring to the module and owned entries corresponding to those
9584            entities that are renamed as part of being imported.  */
9585
9586         if (child_die->tag != DW_TAG_imported_declaration)
9587           {
9588             complaint (&symfile_complaints,
9589                        _("child DW_TAG_imported_declaration expected "
9590                          "- DIE at 0x%x [in module %s]"),
9591                        to_underlying (child_die->sect_off), objfile_name (objfile));
9592             continue;
9593           }
9594
9595         import_attr = dwarf2_attr (child_die, DW_AT_import, cu);
9596         if (import_attr == NULL)
9597           {
9598             complaint (&symfile_complaints, _("Tag '%s' has no DW_AT_import"),
9599                        dwarf_tag_name (child_die->tag));
9600             continue;
9601           }
9602
9603         imported_cu = cu;
9604         imported_die = follow_die_ref_or_sig (child_die, import_attr,
9605                                               &imported_cu);
9606         imported_name = dwarf2_name (imported_die, imported_cu);
9607         if (imported_name == NULL)
9608           {
9609             complaint (&symfile_complaints,
9610                        _("child DW_TAG_imported_declaration has unknown "
9611                          "imported name - DIE at 0x%x [in module %s]"),
9612                        to_underlying (child_die->sect_off), objfile_name (objfile));
9613             continue;
9614           }
9615
9616         excludes.push_back (imported_name);
9617
9618         process_die (child_die, cu);
9619       }
9620
9621   add_using_directive (using_directives (cu->language),
9622                        import_prefix,
9623                        canonical_name,
9624                        import_alias,
9625                        imported_declaration,
9626                        excludes,
9627                        0,
9628                        &objfile->objfile_obstack);
9629 }
9630
9631 /* ICC<14 does not output the required DW_AT_declaration on incomplete
9632    types, but gives them a size of zero.  Starting with version 14,
9633    ICC is compatible with GCC.  */
9634
9635 static int
9636 producer_is_icc_lt_14 (struct dwarf2_cu *cu)
9637 {
9638   if (!cu->checked_producer)
9639     check_producer (cu);
9640
9641   return cu->producer_is_icc_lt_14;
9642 }
9643
9644 /* Check for possibly missing DW_AT_comp_dir with relative .debug_line
9645    directory paths.  GCC SVN r127613 (new option -fdebug-prefix-map) fixed
9646    this, it was first present in GCC release 4.3.0.  */
9647
9648 static int
9649 producer_is_gcc_lt_4_3 (struct dwarf2_cu *cu)
9650 {
9651   if (!cu->checked_producer)
9652     check_producer (cu);
9653
9654   return cu->producer_is_gcc_lt_4_3;
9655 }
9656
9657 static file_and_directory
9658 find_file_and_directory (struct die_info *die, struct dwarf2_cu *cu)
9659 {
9660   file_and_directory res;
9661
9662   /* Find the filename.  Do not use dwarf2_name here, since the filename
9663      is not a source language identifier.  */
9664   res.name = dwarf2_string_attr (die, DW_AT_name, cu);
9665   res.comp_dir = dwarf2_string_attr (die, DW_AT_comp_dir, cu);
9666
9667   if (res.comp_dir == NULL
9668       && producer_is_gcc_lt_4_3 (cu) && res.name != NULL
9669       && IS_ABSOLUTE_PATH (res.name))
9670     {
9671       res.comp_dir_storage = ldirname (res.name);
9672       if (!res.comp_dir_storage.empty ())
9673         res.comp_dir = res.comp_dir_storage.c_str ();
9674     }
9675   if (res.comp_dir != NULL)
9676     {
9677       /* Irix 6.2 native cc prepends <machine>.: to the compilation
9678          directory, get rid of it.  */
9679       const char *cp = strchr (res.comp_dir, ':');
9680
9681       if (cp && cp != res.comp_dir && cp[-1] == '.' && cp[1] == '/')
9682         res.comp_dir = cp + 1;
9683     }
9684
9685   if (res.name == NULL)
9686     res.name = "<unknown>";
9687
9688   return res;
9689 }
9690
9691 /* Handle DW_AT_stmt_list for a compilation unit.
9692    DIE is the DW_TAG_compile_unit die for CU.
9693    COMP_DIR is the compilation directory.  LOWPC is passed to
9694    dwarf_decode_lines.  See dwarf_decode_lines comments about it.  */
9695
9696 static void
9697 handle_DW_AT_stmt_list (struct die_info *die, struct dwarf2_cu *cu,
9698                         const char *comp_dir, CORE_ADDR lowpc) /* ARI: editCase function */
9699 {
9700   struct objfile *objfile = dwarf2_per_objfile->objfile;
9701   struct attribute *attr;
9702   struct line_header line_header_local;
9703   hashval_t line_header_local_hash;
9704   unsigned u;
9705   void **slot;
9706   int decode_mapping;
9707
9708   gdb_assert (! cu->per_cu->is_debug_types);
9709
9710   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9711   if (attr == NULL)
9712     return;
9713
9714   sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9715
9716   /* The line header hash table is only created if needed (it exists to
9717      prevent redundant reading of the line table for partial_units).
9718      If we're given a partial_unit, we'll need it.  If we're given a
9719      compile_unit, then use the line header hash table if it's already
9720      created, but don't create one just yet.  */
9721
9722   if (dwarf2_per_objfile->line_header_hash == NULL
9723       && die->tag == DW_TAG_partial_unit)
9724     {
9725       dwarf2_per_objfile->line_header_hash
9726         = htab_create_alloc_ex (127, line_header_hash_voidp,
9727                                 line_header_eq_voidp,
9728                                 free_line_header_voidp,
9729                                 &objfile->objfile_obstack,
9730                                 hashtab_obstack_allocate,
9731                                 dummy_obstack_deallocate);
9732     }
9733
9734   line_header_local.sect_off = line_offset;
9735   line_header_local.offset_in_dwz = cu->per_cu->is_dwz;
9736   line_header_local_hash = line_header_hash (&line_header_local);
9737   if (dwarf2_per_objfile->line_header_hash != NULL)
9738     {
9739       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9740                                        &line_header_local,
9741                                        line_header_local_hash, NO_INSERT);
9742
9743       /* For DW_TAG_compile_unit we need info like symtab::linetable which
9744          is not present in *SLOT (since if there is something in *SLOT then
9745          it will be for a partial_unit).  */
9746       if (die->tag == DW_TAG_partial_unit && slot != NULL)
9747         {
9748           gdb_assert (*slot != NULL);
9749           cu->line_header = (struct line_header *) *slot;
9750           return;
9751         }
9752     }
9753
9754   /* dwarf_decode_line_header does not yet provide sufficient information.
9755      We always have to call also dwarf_decode_lines for it.  */
9756   line_header_up lh = dwarf_decode_line_header (line_offset, cu);
9757   if (lh == NULL)
9758     return;
9759
9760   cu->line_header = lh.release ();
9761   cu->line_header_die_owner = die;
9762
9763   if (dwarf2_per_objfile->line_header_hash == NULL)
9764     slot = NULL;
9765   else
9766     {
9767       slot = htab_find_slot_with_hash (dwarf2_per_objfile->line_header_hash,
9768                                        &line_header_local,
9769                                        line_header_local_hash, INSERT);
9770       gdb_assert (slot != NULL);
9771     }
9772   if (slot != NULL && *slot == NULL)
9773     {
9774       /* This newly decoded line number information unit will be owned
9775          by line_header_hash hash table.  */
9776       *slot = cu->line_header;
9777       cu->line_header_die_owner = NULL;
9778     }
9779   else
9780     {
9781       /* We cannot free any current entry in (*slot) as that struct line_header
9782          may be already used by multiple CUs.  Create only temporary decoded
9783          line_header for this CU - it may happen at most once for each line
9784          number information unit.  And if we're not using line_header_hash
9785          then this is what we want as well.  */
9786       gdb_assert (die->tag != DW_TAG_partial_unit);
9787     }
9788   decode_mapping = (die->tag != DW_TAG_partial_unit);
9789   dwarf_decode_lines (cu->line_header, comp_dir, cu, NULL, lowpc,
9790                       decode_mapping);
9791
9792 }
9793
9794 /* Process DW_TAG_compile_unit or DW_TAG_partial_unit.  */
9795
9796 static void
9797 read_file_scope (struct die_info *die, struct dwarf2_cu *cu)
9798 {
9799   struct objfile *objfile = dwarf2_per_objfile->objfile;
9800   struct gdbarch *gdbarch = get_objfile_arch (objfile);
9801   CORE_ADDR lowpc = ((CORE_ADDR) -1);
9802   CORE_ADDR highpc = ((CORE_ADDR) 0);
9803   struct attribute *attr;
9804   struct die_info *child_die;
9805   CORE_ADDR baseaddr;
9806
9807   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
9808
9809   get_scope_pc_bounds (die, &lowpc, &highpc, cu);
9810
9811   /* If we didn't find a lowpc, set it to highpc to avoid complaints
9812      from finish_block.  */
9813   if (lowpc == ((CORE_ADDR) -1))
9814     lowpc = highpc;
9815   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
9816
9817   file_and_directory fnd = find_file_and_directory (die, cu);
9818
9819   prepare_one_comp_unit (cu, die, cu->language);
9820
9821   /* The XLCL doesn't generate DW_LANG_OpenCL because this attribute is not
9822      standardised yet.  As a workaround for the language detection we fall
9823      back to the DW_AT_producer string.  */
9824   if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL") != NULL)
9825     cu->language = language_opencl;
9826
9827   /* Similar hack for Go.  */
9828   if (cu->producer && strstr (cu->producer, "GNU Go ") != NULL)
9829     set_cu_language (DW_LANG_Go, cu);
9830
9831   dwarf2_start_symtab (cu, fnd.name, fnd.comp_dir, lowpc);
9832
9833   /* Decode line number information if present.  We do this before
9834      processing child DIEs, so that the line header table is available
9835      for DW_AT_decl_file.  */
9836   handle_DW_AT_stmt_list (die, cu, fnd.comp_dir, lowpc);
9837
9838   /* Process all dies in compilation unit.  */
9839   if (die->child != NULL)
9840     {
9841       child_die = die->child;
9842       while (child_die && child_die->tag)
9843         {
9844           process_die (child_die, cu);
9845           child_die = sibling_die (child_die);
9846         }
9847     }
9848
9849   /* Decode macro information, if present.  Dwarf 2 macro information
9850      refers to information in the line number info statement program
9851      header, so we can only read it if we've read the header
9852      successfully.  */
9853   attr = dwarf2_attr (die, DW_AT_macros, cu);
9854   if (attr == NULL)
9855     attr = dwarf2_attr (die, DW_AT_GNU_macros, cu);
9856   if (attr && cu->line_header)
9857     {
9858       if (dwarf2_attr (die, DW_AT_macro_info, cu))
9859         complaint (&symfile_complaints,
9860                    _("CU refers to both DW_AT_macros and DW_AT_macro_info"));
9861
9862       dwarf_decode_macros (cu, DW_UNSND (attr), 1);
9863     }
9864   else
9865     {
9866       attr = dwarf2_attr (die, DW_AT_macro_info, cu);
9867       if (attr && cu->line_header)
9868         {
9869           unsigned int macro_offset = DW_UNSND (attr);
9870
9871           dwarf_decode_macros (cu, macro_offset, 0);
9872         }
9873     }
9874 }
9875
9876 /* TU version of handle_DW_AT_stmt_list for read_type_unit_scope.
9877    Create the set of symtabs used by this TU, or if this TU is sharing
9878    symtabs with another TU and the symtabs have already been created
9879    then restore those symtabs in the line header.
9880    We don't need the pc/line-number mapping for type units.  */
9881
9882 static void
9883 setup_type_unit_groups (struct die_info *die, struct dwarf2_cu *cu)
9884 {
9885   struct dwarf2_per_cu_data *per_cu = cu->per_cu;
9886   struct type_unit_group *tu_group;
9887   int first_time;
9888   struct attribute *attr;
9889   unsigned int i;
9890   struct signatured_type *sig_type;
9891
9892   gdb_assert (per_cu->is_debug_types);
9893   sig_type = (struct signatured_type *) per_cu;
9894
9895   attr = dwarf2_attr (die, DW_AT_stmt_list, cu);
9896
9897   /* If we're using .gdb_index (includes -readnow) then
9898      per_cu->type_unit_group may not have been set up yet.  */
9899   if (sig_type->type_unit_group == NULL)
9900     sig_type->type_unit_group = get_type_unit_group (cu, attr);
9901   tu_group = sig_type->type_unit_group;
9902
9903   /* If we've already processed this stmt_list there's no real need to
9904      do it again, we could fake it and just recreate the part we need
9905      (file name,index -> symtab mapping).  If data shows this optimization
9906      is useful we can do it then.  */
9907   first_time = tu_group->compunit_symtab == NULL;
9908
9909   /* We have to handle the case of both a missing DW_AT_stmt_list or bad
9910      debug info.  */
9911   line_header_up lh;
9912   if (attr != NULL)
9913     {
9914       sect_offset line_offset = (sect_offset) DW_UNSND (attr);
9915       lh = dwarf_decode_line_header (line_offset, cu);
9916     }
9917   if (lh == NULL)
9918     {
9919       if (first_time)
9920         dwarf2_start_symtab (cu, "", NULL, 0);
9921       else
9922         {
9923           gdb_assert (tu_group->symtabs == NULL);
9924           restart_symtab (tu_group->compunit_symtab, "", 0);
9925         }
9926       return;
9927     }
9928
9929   cu->line_header = lh.release ();
9930   cu->line_header_die_owner = die;
9931
9932   if (first_time)
9933     {
9934       struct compunit_symtab *cust = dwarf2_start_symtab (cu, "", NULL, 0);
9935
9936       /* Note: We don't assign tu_group->compunit_symtab yet because we're
9937          still initializing it, and our caller (a few levels up)
9938          process_full_type_unit still needs to know if this is the first
9939          time.  */
9940
9941       tu_group->num_symtabs = cu->line_header->file_names.size ();
9942       tu_group->symtabs = XNEWVEC (struct symtab *,
9943                                    cu->line_header->file_names.size ());
9944
9945       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9946         {
9947           file_entry &fe = cu->line_header->file_names[i];
9948
9949           dwarf2_start_subfile (fe.name, fe.include_dir (cu->line_header));
9950
9951           if (current_subfile->symtab == NULL)
9952             {
9953               /* NOTE: start_subfile will recognize when it's been
9954                  passed a file it has already seen.  So we can't
9955                  assume there's a simple mapping from
9956                  cu->line_header->file_names to subfiles, plus
9957                  cu->line_header->file_names may contain dups.  */
9958               current_subfile->symtab
9959                 = allocate_symtab (cust, current_subfile->name);
9960             }
9961
9962           fe.symtab = current_subfile->symtab;
9963           tu_group->symtabs[i] = fe.symtab;
9964         }
9965     }
9966   else
9967     {
9968       restart_symtab (tu_group->compunit_symtab, "", 0);
9969
9970       for (i = 0; i < cu->line_header->file_names.size (); ++i)
9971         {
9972           file_entry &fe = cu->line_header->file_names[i];
9973
9974           fe.symtab = tu_group->symtabs[i];
9975         }
9976     }
9977
9978   /* The main symtab is allocated last.  Type units don't have DW_AT_name
9979      so they don't have a "real" (so to speak) symtab anyway.
9980      There is later code that will assign the main symtab to all symbols
9981      that don't have one.  We need to handle the case of a symbol with a
9982      missing symtab (DW_AT_decl_file) anyway.  */
9983 }
9984
9985 /* Process DW_TAG_type_unit.
9986    For TUs we want to skip the first top level sibling if it's not the
9987    actual type being defined by this TU.  In this case the first top
9988    level sibling is there to provide context only.  */
9989
9990 static void
9991 read_type_unit_scope (struct die_info *die, struct dwarf2_cu *cu)
9992 {
9993   struct die_info *child_die;
9994
9995   prepare_one_comp_unit (cu, die, language_minimal);
9996
9997   /* Initialize (or reinitialize) the machinery for building symtabs.
9998      We do this before processing child DIEs, so that the line header table
9999      is available for DW_AT_decl_file.  */
10000   setup_type_unit_groups (die, cu);
10001
10002   if (die->child != NULL)
10003     {
10004       child_die = die->child;
10005       while (child_die && child_die->tag)
10006         {
10007           process_die (child_die, cu);
10008           child_die = sibling_die (child_die);
10009         }
10010     }
10011 }
10012 \f
10013 /* DWO/DWP files.
10014
10015    http://gcc.gnu.org/wiki/DebugFission
10016    http://gcc.gnu.org/wiki/DebugFissionDWP
10017
10018    To simplify handling of both DWO files ("object" files with the DWARF info)
10019    and DWP files (a file with the DWOs packaged up into one file), we treat
10020    DWP files as having a collection of virtual DWO files.  */
10021
10022 static hashval_t
10023 hash_dwo_file (const void *item)
10024 {
10025   const struct dwo_file *dwo_file = (const struct dwo_file *) item;
10026   hashval_t hash;
10027
10028   hash = htab_hash_string (dwo_file->dwo_name);
10029   if (dwo_file->comp_dir != NULL)
10030     hash += htab_hash_string (dwo_file->comp_dir);
10031   return hash;
10032 }
10033
10034 static int
10035 eq_dwo_file (const void *item_lhs, const void *item_rhs)
10036 {
10037   const struct dwo_file *lhs = (const struct dwo_file *) item_lhs;
10038   const struct dwo_file *rhs = (const struct dwo_file *) item_rhs;
10039
10040   if (strcmp (lhs->dwo_name, rhs->dwo_name) != 0)
10041     return 0;
10042   if (lhs->comp_dir == NULL || rhs->comp_dir == NULL)
10043     return lhs->comp_dir == rhs->comp_dir;
10044   return strcmp (lhs->comp_dir, rhs->comp_dir) == 0;
10045 }
10046
10047 /* Allocate a hash table for DWO files.  */
10048
10049 static htab_t
10050 allocate_dwo_file_hash_table (void)
10051 {
10052   struct objfile *objfile = dwarf2_per_objfile->objfile;
10053
10054   return htab_create_alloc_ex (41,
10055                                hash_dwo_file,
10056                                eq_dwo_file,
10057                                NULL,
10058                                &objfile->objfile_obstack,
10059                                hashtab_obstack_allocate,
10060                                dummy_obstack_deallocate);
10061 }
10062
10063 /* Lookup DWO file DWO_NAME.  */
10064
10065 static void **
10066 lookup_dwo_file_slot (const char *dwo_name, const char *comp_dir)
10067 {
10068   struct dwo_file find_entry;
10069   void **slot;
10070
10071   if (dwarf2_per_objfile->dwo_files == NULL)
10072     dwarf2_per_objfile->dwo_files = allocate_dwo_file_hash_table ();
10073
10074   memset (&find_entry, 0, sizeof (find_entry));
10075   find_entry.dwo_name = dwo_name;
10076   find_entry.comp_dir = comp_dir;
10077   slot = htab_find_slot (dwarf2_per_objfile->dwo_files, &find_entry, INSERT);
10078
10079   return slot;
10080 }
10081
10082 static hashval_t
10083 hash_dwo_unit (const void *item)
10084 {
10085   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
10086
10087   /* This drops the top 32 bits of the id, but is ok for a hash.  */
10088   return dwo_unit->signature;
10089 }
10090
10091 static int
10092 eq_dwo_unit (const void *item_lhs, const void *item_rhs)
10093 {
10094   const struct dwo_unit *lhs = (const struct dwo_unit *) item_lhs;
10095   const struct dwo_unit *rhs = (const struct dwo_unit *) item_rhs;
10096
10097   /* The signature is assumed to be unique within the DWO file.
10098      So while object file CU dwo_id's always have the value zero,
10099      that's OK, assuming each object file DWO file has only one CU,
10100      and that's the rule for now.  */
10101   return lhs->signature == rhs->signature;
10102 }
10103
10104 /* Allocate a hash table for DWO CUs,TUs.
10105    There is one of these tables for each of CUs,TUs for each DWO file.  */
10106
10107 static htab_t
10108 allocate_dwo_unit_table (struct objfile *objfile)
10109 {
10110   /* Start out with a pretty small number.
10111      Generally DWO files contain only one CU and maybe some TUs.  */
10112   return htab_create_alloc_ex (3,
10113                                hash_dwo_unit,
10114                                eq_dwo_unit,
10115                                NULL,
10116                                &objfile->objfile_obstack,
10117                                hashtab_obstack_allocate,
10118                                dummy_obstack_deallocate);
10119 }
10120
10121 /* Structure used to pass data to create_dwo_debug_info_hash_table_reader.  */
10122
10123 struct create_dwo_cu_data
10124 {
10125   struct dwo_file *dwo_file;
10126   struct dwo_unit dwo_unit;
10127 };
10128
10129 /* die_reader_func for create_dwo_cu.  */
10130
10131 static void
10132 create_dwo_cu_reader (const struct die_reader_specs *reader,
10133                       const gdb_byte *info_ptr,
10134                       struct die_info *comp_unit_die,
10135                       int has_children,
10136                       void *datap)
10137 {
10138   struct dwarf2_cu *cu = reader->cu;
10139   sect_offset sect_off = cu->per_cu->sect_off;
10140   struct dwarf2_section_info *section = cu->per_cu->section;
10141   struct create_dwo_cu_data *data = (struct create_dwo_cu_data *) datap;
10142   struct dwo_file *dwo_file = data->dwo_file;
10143   struct dwo_unit *dwo_unit = &data->dwo_unit;
10144   struct attribute *attr;
10145
10146   attr = dwarf2_attr (comp_unit_die, DW_AT_GNU_dwo_id, cu);
10147   if (attr == NULL)
10148     {
10149       complaint (&symfile_complaints,
10150                  _("Dwarf Error: debug entry at offset 0x%x is missing"
10151                    " its dwo_id [in module %s]"),
10152                  to_underlying (sect_off), dwo_file->dwo_name);
10153       return;
10154     }
10155
10156   dwo_unit->dwo_file = dwo_file;
10157   dwo_unit->signature = DW_UNSND (attr);
10158   dwo_unit->section = section;
10159   dwo_unit->sect_off = sect_off;
10160   dwo_unit->length = cu->per_cu->length;
10161
10162   if (dwarf_read_debug)
10163     fprintf_unfiltered (gdb_stdlog, "  offset 0x%x, dwo_id %s\n",
10164                         to_underlying (sect_off),
10165                         hex_string (dwo_unit->signature));
10166 }
10167
10168 /* Create the dwo_units for the CUs in a DWO_FILE.
10169    Note: This function processes DWO files only, not DWP files.  */
10170
10171 static void
10172 create_cus_hash_table (struct dwo_file &dwo_file, dwarf2_section_info &section,
10173                        htab_t &cus_htab)
10174 {
10175   struct objfile *objfile = dwarf2_per_objfile->objfile;
10176   const struct dwarf2_section_info *abbrev_section = &dwo_file.sections.abbrev;
10177   const gdb_byte *info_ptr, *end_ptr;
10178
10179   dwarf2_read_section (objfile, &section);
10180   info_ptr = section.buffer;
10181
10182   if (info_ptr == NULL)
10183     return;
10184
10185   if (dwarf_read_debug)
10186     {
10187       fprintf_unfiltered (gdb_stdlog, "Reading %s for %s:\n",
10188                           get_section_name (&section),
10189                           get_section_file_name (&section));
10190     }
10191
10192   end_ptr = info_ptr + section.size;
10193   while (info_ptr < end_ptr)
10194     {
10195       struct dwarf2_per_cu_data per_cu;
10196       struct create_dwo_cu_data create_dwo_cu_data;
10197       struct dwo_unit *dwo_unit;
10198       void **slot;
10199       sect_offset sect_off = (sect_offset) (info_ptr - section.buffer);
10200
10201       memset (&create_dwo_cu_data.dwo_unit, 0,
10202               sizeof (create_dwo_cu_data.dwo_unit));
10203       memset (&per_cu, 0, sizeof (per_cu));
10204       per_cu.objfile = objfile;
10205       per_cu.is_debug_types = 0;
10206       per_cu.sect_off = sect_offset (info_ptr - section.buffer);
10207       per_cu.section = &section;
10208       create_dwo_cu_data.dwo_file = &dwo_file;
10209
10210       init_cutu_and_read_dies_no_follow (
10211           &per_cu, &dwo_file, create_dwo_cu_reader, &create_dwo_cu_data);
10212       info_ptr += per_cu.length;
10213
10214       // If the unit could not be parsed, skip it.
10215       if (create_dwo_cu_data.dwo_unit.dwo_file == NULL)
10216         continue;
10217
10218       if (cus_htab == NULL)
10219         cus_htab = allocate_dwo_unit_table (objfile);
10220
10221       dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10222       *dwo_unit = create_dwo_cu_data.dwo_unit;
10223       slot = htab_find_slot (cus_htab, dwo_unit, INSERT);
10224       gdb_assert (slot != NULL);
10225       if (*slot != NULL)
10226         {
10227           const struct dwo_unit *dup_cu = (const struct dwo_unit *)*slot;
10228           sect_offset dup_sect_off = dup_cu->sect_off;
10229
10230           complaint (&symfile_complaints,
10231                      _("debug cu entry at offset 0x%x is duplicate to"
10232                        " the entry at offset 0x%x, signature %s"),
10233                      to_underlying (sect_off), to_underlying (dup_sect_off),
10234                      hex_string (dwo_unit->signature));
10235         }
10236       *slot = (void *)dwo_unit;
10237     }
10238 }
10239
10240 /* DWP file .debug_{cu,tu}_index section format:
10241    [ref: http://gcc.gnu.org/wiki/DebugFissionDWP]
10242
10243    DWP Version 1:
10244
10245    Both index sections have the same format, and serve to map a 64-bit
10246    signature to a set of section numbers.  Each section begins with a header,
10247    followed by a hash table of 64-bit signatures, a parallel table of 32-bit
10248    indexes, and a pool of 32-bit section numbers.  The index sections will be
10249    aligned at 8-byte boundaries in the file.
10250
10251    The index section header consists of:
10252
10253     V, 32 bit version number
10254     -, 32 bits unused
10255     N, 32 bit number of compilation units or type units in the index
10256     M, 32 bit number of slots in the hash table
10257
10258    Numbers are recorded using the byte order of the application binary.
10259
10260    The hash table begins at offset 16 in the section, and consists of an array
10261    of M 64-bit slots.  Each slot contains a 64-bit signature (using the byte
10262    order of the application binary).  Unused slots in the hash table are 0.
10263    (We rely on the extreme unlikeliness of a signature being exactly 0.)
10264
10265    The parallel table begins immediately after the hash table
10266    (at offset 16 + 8 * M from the beginning of the section), and consists of an
10267    array of 32-bit indexes (using the byte order of the application binary),
10268    corresponding 1-1 with slots in the hash table.  Each entry in the parallel
10269    table contains a 32-bit index into the pool of section numbers.  For unused
10270    hash table slots, the corresponding entry in the parallel table will be 0.
10271
10272    The pool of section numbers begins immediately following the hash table
10273    (at offset 16 + 12 * M from the beginning of the section).  The pool of
10274    section numbers consists of an array of 32-bit words (using the byte order
10275    of the application binary).  Each item in the array is indexed starting
10276    from 0.  The hash table entry provides the index of the first section
10277    number in the set.  Additional section numbers in the set follow, and the
10278    set is terminated by a 0 entry (section number 0 is not used in ELF).
10279
10280    In each set of section numbers, the .debug_info.dwo or .debug_types.dwo
10281    section must be the first entry in the set, and the .debug_abbrev.dwo must
10282    be the second entry. Other members of the set may follow in any order.
10283
10284    ---
10285
10286    DWP Version 2:
10287
10288    DWP Version 2 combines all the .debug_info, etc. sections into one,
10289    and the entries in the index tables are now offsets into these sections.
10290    CU offsets begin at 0.  TU offsets begin at the size of the .debug_info
10291    section.
10292
10293    Index Section Contents:
10294     Header
10295     Hash Table of Signatures   dwp_hash_table.hash_table
10296     Parallel Table of Indices  dwp_hash_table.unit_table
10297     Table of Section Offsets   dwp_hash_table.v2.{section_ids,offsets}
10298     Table of Section Sizes     dwp_hash_table.v2.sizes
10299
10300    The index section header consists of:
10301
10302     V, 32 bit version number
10303     L, 32 bit number of columns in the table of section offsets
10304     N, 32 bit number of compilation units or type units in the index
10305     M, 32 bit number of slots in the hash table
10306
10307    Numbers are recorded using the byte order of the application binary.
10308
10309    The hash table has the same format as version 1.
10310    The parallel table of indices has the same format as version 1,
10311    except that the entries are origin-1 indices into the table of sections
10312    offsets and the table of section sizes.
10313
10314    The table of offsets begins immediately following the parallel table
10315    (at offset 16 + 12 * M from the beginning of the section).  The table is
10316    a two-dimensional array of 32-bit words (using the byte order of the
10317    application binary), with L columns and N+1 rows, in row-major order.
10318    Each row in the array is indexed starting from 0.  The first row provides
10319    a key to the remaining rows: each column in this row provides an identifier
10320    for a debug section, and the offsets in the same column of subsequent rows
10321    refer to that section.  The section identifiers are:
10322
10323     DW_SECT_INFO         1  .debug_info.dwo
10324     DW_SECT_TYPES        2  .debug_types.dwo
10325     DW_SECT_ABBREV       3  .debug_abbrev.dwo
10326     DW_SECT_LINE         4  .debug_line.dwo
10327     DW_SECT_LOC          5  .debug_loc.dwo
10328     DW_SECT_STR_OFFSETS  6  .debug_str_offsets.dwo
10329     DW_SECT_MACINFO      7  .debug_macinfo.dwo
10330     DW_SECT_MACRO        8  .debug_macro.dwo
10331
10332    The offsets provided by the CU and TU index sections are the base offsets
10333    for the contributions made by each CU or TU to the corresponding section
10334    in the package file.  Each CU and TU header contains an abbrev_offset
10335    field, used to find the abbreviations table for that CU or TU within the
10336    contribution to the .debug_abbrev.dwo section for that CU or TU, and should
10337    be interpreted as relative to the base offset given in the index section.
10338    Likewise, offsets into .debug_line.dwo from DW_AT_stmt_list attributes
10339    should be interpreted as relative to the base offset for .debug_line.dwo,
10340    and offsets into other debug sections obtained from DWARF attributes should
10341    also be interpreted as relative to the corresponding base offset.
10342
10343    The table of sizes begins immediately following the table of offsets.
10344    Like the table of offsets, it is a two-dimensional array of 32-bit words,
10345    with L columns and N rows, in row-major order.  Each row in the array is
10346    indexed starting from 1 (row 0 is shared by the two tables).
10347
10348    ---
10349
10350    Hash table lookup is handled the same in version 1 and 2:
10351
10352    We assume that N and M will not exceed 2^32 - 1.
10353    The size of the hash table, M, must be 2^k such that 2^k > 3*N/2.
10354
10355    Given a 64-bit compilation unit signature or a type signature S, an entry
10356    in the hash table is located as follows:
10357
10358    1) Calculate a primary hash H = S & MASK(k), where MASK(k) is a mask with
10359       the low-order k bits all set to 1.
10360
10361    2) Calculate a secondary hash H' = (((S >> 32) & MASK(k)) | 1).
10362
10363    3) If the hash table entry at index H matches the signature, use that
10364       entry.  If the hash table entry at index H is unused (all zeroes),
10365       terminate the search: the signature is not present in the table.
10366
10367    4) Let H = (H + H') modulo M. Repeat at Step 3.
10368
10369    Because M > N and H' and M are relatively prime, the search is guaranteed
10370    to stop at an unused slot or find the match.  */
10371
10372 /* Create a hash table to map DWO IDs to their CU/TU entry in
10373    .debug_{info,types}.dwo in DWP_FILE.
10374    Returns NULL if there isn't one.
10375    Note: This function processes DWP files only, not DWO files.  */
10376
10377 static struct dwp_hash_table *
10378 create_dwp_hash_table (struct dwp_file *dwp_file, int is_debug_types)
10379 {
10380   struct objfile *objfile = dwarf2_per_objfile->objfile;
10381   bfd *dbfd = dwp_file->dbfd;
10382   const gdb_byte *index_ptr, *index_end;
10383   struct dwarf2_section_info *index;
10384   uint32_t version, nr_columns, nr_units, nr_slots;
10385   struct dwp_hash_table *htab;
10386
10387   if (is_debug_types)
10388     index = &dwp_file->sections.tu_index;
10389   else
10390     index = &dwp_file->sections.cu_index;
10391
10392   if (dwarf2_section_empty_p (index))
10393     return NULL;
10394   dwarf2_read_section (objfile, index);
10395
10396   index_ptr = index->buffer;
10397   index_end = index_ptr + index->size;
10398
10399   version = read_4_bytes (dbfd, index_ptr);
10400   index_ptr += 4;
10401   if (version == 2)
10402     nr_columns = read_4_bytes (dbfd, index_ptr);
10403   else
10404     nr_columns = 0;
10405   index_ptr += 4;
10406   nr_units = read_4_bytes (dbfd, index_ptr);
10407   index_ptr += 4;
10408   nr_slots = read_4_bytes (dbfd, index_ptr);
10409   index_ptr += 4;
10410
10411   if (version != 1 && version != 2)
10412     {
10413       error (_("Dwarf Error: unsupported DWP file version (%s)"
10414                " [in module %s]"),
10415              pulongest (version), dwp_file->name);
10416     }
10417   if (nr_slots != (nr_slots & -nr_slots))
10418     {
10419       error (_("Dwarf Error: number of slots in DWP hash table (%s)"
10420                " is not power of 2 [in module %s]"),
10421              pulongest (nr_slots), dwp_file->name);
10422     }
10423
10424   htab = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_hash_table);
10425   htab->version = version;
10426   htab->nr_columns = nr_columns;
10427   htab->nr_units = nr_units;
10428   htab->nr_slots = nr_slots;
10429   htab->hash_table = index_ptr;
10430   htab->unit_table = htab->hash_table + sizeof (uint64_t) * nr_slots;
10431
10432   /* Exit early if the table is empty.  */
10433   if (nr_slots == 0 || nr_units == 0
10434       || (version == 2 && nr_columns == 0))
10435     {
10436       /* All must be zero.  */
10437       if (nr_slots != 0 || nr_units != 0
10438           || (version == 2 && nr_columns != 0))
10439         {
10440           complaint (&symfile_complaints,
10441                      _("Empty DWP but nr_slots,nr_units,nr_columns not"
10442                        " all zero [in modules %s]"),
10443                      dwp_file->name);
10444         }
10445       return htab;
10446     }
10447
10448   if (version == 1)
10449     {
10450       htab->section_pool.v1.indices =
10451         htab->unit_table + sizeof (uint32_t) * nr_slots;
10452       /* It's harder to decide whether the section is too small in v1.
10453          V1 is deprecated anyway so we punt.  */
10454     }
10455   else
10456     {
10457       const gdb_byte *ids_ptr = htab->unit_table + sizeof (uint32_t) * nr_slots;
10458       int *ids = htab->section_pool.v2.section_ids;
10459       /* Reverse map for error checking.  */
10460       int ids_seen[DW_SECT_MAX + 1];
10461       int i;
10462
10463       if (nr_columns < 2)
10464         {
10465           error (_("Dwarf Error: bad DWP hash table, too few columns"
10466                    " in section table [in module %s]"),
10467                  dwp_file->name);
10468         }
10469       if (nr_columns > MAX_NR_V2_DWO_SECTIONS)
10470         {
10471           error (_("Dwarf Error: bad DWP hash table, too many columns"
10472                    " in section table [in module %s]"),
10473                  dwp_file->name);
10474         }
10475       memset (ids, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10476       memset (ids_seen, 255, (DW_SECT_MAX + 1) * sizeof (int32_t));
10477       for (i = 0; i < nr_columns; ++i)
10478         {
10479           int id = read_4_bytes (dbfd, ids_ptr + i * sizeof (uint32_t));
10480
10481           if (id < DW_SECT_MIN || id > DW_SECT_MAX)
10482             {
10483               error (_("Dwarf Error: bad DWP hash table, bad section id %d"
10484                        " in section table [in module %s]"),
10485                      id, dwp_file->name);
10486             }
10487           if (ids_seen[id] != -1)
10488             {
10489               error (_("Dwarf Error: bad DWP hash table, duplicate section"
10490                        " id %d in section table [in module %s]"),
10491                      id, dwp_file->name);
10492             }
10493           ids_seen[id] = i;
10494           ids[i] = id;
10495         }
10496       /* Must have exactly one info or types section.  */
10497       if (((ids_seen[DW_SECT_INFO] != -1)
10498            + (ids_seen[DW_SECT_TYPES] != -1))
10499           != 1)
10500         {
10501           error (_("Dwarf Error: bad DWP hash table, missing/duplicate"
10502                    " DWO info/types section [in module %s]"),
10503                  dwp_file->name);
10504         }
10505       /* Must have an abbrev section.  */
10506       if (ids_seen[DW_SECT_ABBREV] == -1)
10507         {
10508           error (_("Dwarf Error: bad DWP hash table, missing DWO abbrev"
10509                    " section [in module %s]"),
10510                  dwp_file->name);
10511         }
10512       htab->section_pool.v2.offsets = ids_ptr + sizeof (uint32_t) * nr_columns;
10513       htab->section_pool.v2.sizes =
10514         htab->section_pool.v2.offsets + (sizeof (uint32_t)
10515                                          * nr_units * nr_columns);
10516       if ((htab->section_pool.v2.sizes + (sizeof (uint32_t)
10517                                           * nr_units * nr_columns))
10518           > index_end)
10519         {
10520           error (_("Dwarf Error: DWP index section is corrupt (too small)"
10521                    " [in module %s]"),
10522                  dwp_file->name);
10523         }
10524     }
10525
10526   return htab;
10527 }
10528
10529 /* Update SECTIONS with the data from SECTP.
10530
10531    This function is like the other "locate" section routines that are
10532    passed to bfd_map_over_sections, but in this context the sections to
10533    read comes from the DWP V1 hash table, not the full ELF section table.
10534
10535    The result is non-zero for success, or zero if an error was found.  */
10536
10537 static int
10538 locate_v1_virtual_dwo_sections (asection *sectp,
10539                                 struct virtual_v1_dwo_sections *sections)
10540 {
10541   const struct dwop_section_names *names = &dwop_section_names;
10542
10543   if (section_is_p (sectp->name, &names->abbrev_dwo))
10544     {
10545       /* There can be only one.  */
10546       if (sections->abbrev.s.section != NULL)
10547         return 0;
10548       sections->abbrev.s.section = sectp;
10549       sections->abbrev.size = bfd_get_section_size (sectp);
10550     }
10551   else if (section_is_p (sectp->name, &names->info_dwo)
10552            || section_is_p (sectp->name, &names->types_dwo))
10553     {
10554       /* There can be only one.  */
10555       if (sections->info_or_types.s.section != NULL)
10556         return 0;
10557       sections->info_or_types.s.section = sectp;
10558       sections->info_or_types.size = bfd_get_section_size (sectp);
10559     }
10560   else if (section_is_p (sectp->name, &names->line_dwo))
10561     {
10562       /* There can be only one.  */
10563       if (sections->line.s.section != NULL)
10564         return 0;
10565       sections->line.s.section = sectp;
10566       sections->line.size = bfd_get_section_size (sectp);
10567     }
10568   else if (section_is_p (sectp->name, &names->loc_dwo))
10569     {
10570       /* There can be only one.  */
10571       if (sections->loc.s.section != NULL)
10572         return 0;
10573       sections->loc.s.section = sectp;
10574       sections->loc.size = bfd_get_section_size (sectp);
10575     }
10576   else if (section_is_p (sectp->name, &names->macinfo_dwo))
10577     {
10578       /* There can be only one.  */
10579       if (sections->macinfo.s.section != NULL)
10580         return 0;
10581       sections->macinfo.s.section = sectp;
10582       sections->macinfo.size = bfd_get_section_size (sectp);
10583     }
10584   else if (section_is_p (sectp->name, &names->macro_dwo))
10585     {
10586       /* There can be only one.  */
10587       if (sections->macro.s.section != NULL)
10588         return 0;
10589       sections->macro.s.section = sectp;
10590       sections->macro.size = bfd_get_section_size (sectp);
10591     }
10592   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
10593     {
10594       /* There can be only one.  */
10595       if (sections->str_offsets.s.section != NULL)
10596         return 0;
10597       sections->str_offsets.s.section = sectp;
10598       sections->str_offsets.size = bfd_get_section_size (sectp);
10599     }
10600   else
10601     {
10602       /* No other kind of section is valid.  */
10603       return 0;
10604     }
10605
10606   return 1;
10607 }
10608
10609 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10610    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10611    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10612    This is for DWP version 1 files.  */
10613
10614 static struct dwo_unit *
10615 create_dwo_unit_in_dwp_v1 (struct dwp_file *dwp_file,
10616                            uint32_t unit_index,
10617                            const char *comp_dir,
10618                            ULONGEST signature, int is_debug_types)
10619 {
10620   struct objfile *objfile = dwarf2_per_objfile->objfile;
10621   const struct dwp_hash_table *dwp_htab =
10622     is_debug_types ? dwp_file->tus : dwp_file->cus;
10623   bfd *dbfd = dwp_file->dbfd;
10624   const char *kind = is_debug_types ? "TU" : "CU";
10625   struct dwo_file *dwo_file;
10626   struct dwo_unit *dwo_unit;
10627   struct virtual_v1_dwo_sections sections;
10628   void **dwo_file_slot;
10629   int i;
10630
10631   gdb_assert (dwp_file->version == 1);
10632
10633   if (dwarf_read_debug)
10634     {
10635       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V1 file: %s\n",
10636                           kind,
10637                           pulongest (unit_index), hex_string (signature),
10638                           dwp_file->name);
10639     }
10640
10641   /* Fetch the sections of this DWO unit.
10642      Put a limit on the number of sections we look for so that bad data
10643      doesn't cause us to loop forever.  */
10644
10645 #define MAX_NR_V1_DWO_SECTIONS \
10646   (1 /* .debug_info or .debug_types */ \
10647    + 1 /* .debug_abbrev */ \
10648    + 1 /* .debug_line */ \
10649    + 1 /* .debug_loc */ \
10650    + 1 /* .debug_str_offsets */ \
10651    + 1 /* .debug_macro or .debug_macinfo */ \
10652    + 1 /* trailing zero */)
10653
10654   memset (&sections, 0, sizeof (sections));
10655
10656   for (i = 0; i < MAX_NR_V1_DWO_SECTIONS; ++i)
10657     {
10658       asection *sectp;
10659       uint32_t section_nr =
10660         read_4_bytes (dbfd,
10661                       dwp_htab->section_pool.v1.indices
10662                       + (unit_index + i) * sizeof (uint32_t));
10663
10664       if (section_nr == 0)
10665         break;
10666       if (section_nr >= dwp_file->num_sections)
10667         {
10668           error (_("Dwarf Error: bad DWP hash table, section number too large"
10669                    " [in module %s]"),
10670                  dwp_file->name);
10671         }
10672
10673       sectp = dwp_file->elf_sections[section_nr];
10674       if (! locate_v1_virtual_dwo_sections (sectp, &sections))
10675         {
10676           error (_("Dwarf Error: bad DWP hash table, invalid section found"
10677                    " [in module %s]"),
10678                  dwp_file->name);
10679         }
10680     }
10681
10682   if (i < 2
10683       || dwarf2_section_empty_p (&sections.info_or_types)
10684       || dwarf2_section_empty_p (&sections.abbrev))
10685     {
10686       error (_("Dwarf Error: bad DWP hash table, missing DWO sections"
10687                " [in module %s]"),
10688              dwp_file->name);
10689     }
10690   if (i == MAX_NR_V1_DWO_SECTIONS)
10691     {
10692       error (_("Dwarf Error: bad DWP hash table, too many DWO sections"
10693                " [in module %s]"),
10694              dwp_file->name);
10695     }
10696
10697   /* It's easier for the rest of the code if we fake a struct dwo_file and
10698      have dwo_unit "live" in that.  At least for now.
10699
10700      The DWP file can be made up of a random collection of CUs and TUs.
10701      However, for each CU + set of TUs that came from the same original DWO
10702      file, we can combine them back into a virtual DWO file to save space
10703      (fewer struct dwo_file objects to allocate).  Remember that for really
10704      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10705
10706   std::string virtual_dwo_name =
10707     string_printf ("virtual-dwo/%d-%d-%d-%d",
10708                    get_section_id (&sections.abbrev),
10709                    get_section_id (&sections.line),
10710                    get_section_id (&sections.loc),
10711                    get_section_id (&sections.str_offsets));
10712   /* Can we use an existing virtual DWO file?  */
10713   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10714   /* Create one if necessary.  */
10715   if (*dwo_file_slot == NULL)
10716     {
10717       if (dwarf_read_debug)
10718         {
10719           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10720                               virtual_dwo_name.c_str ());
10721         }
10722       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10723       dwo_file->dwo_name
10724         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10725                                         virtual_dwo_name.c_str (),
10726                                         virtual_dwo_name.size ());
10727       dwo_file->comp_dir = comp_dir;
10728       dwo_file->sections.abbrev = sections.abbrev;
10729       dwo_file->sections.line = sections.line;
10730       dwo_file->sections.loc = sections.loc;
10731       dwo_file->sections.macinfo = sections.macinfo;
10732       dwo_file->sections.macro = sections.macro;
10733       dwo_file->sections.str_offsets = sections.str_offsets;
10734       /* The "str" section is global to the entire DWP file.  */
10735       dwo_file->sections.str = dwp_file->sections.str;
10736       /* The info or types section is assigned below to dwo_unit,
10737          there's no need to record it in dwo_file.
10738          Also, we can't simply record type sections in dwo_file because
10739          we record a pointer into the vector in dwo_unit.  As we collect more
10740          types we'll grow the vector and eventually have to reallocate space
10741          for it, invalidating all copies of pointers into the previous
10742          contents.  */
10743       *dwo_file_slot = dwo_file;
10744     }
10745   else
10746     {
10747       if (dwarf_read_debug)
10748         {
10749           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10750                               virtual_dwo_name.c_str ());
10751         }
10752       dwo_file = (struct dwo_file *) *dwo_file_slot;
10753     }
10754
10755   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10756   dwo_unit->dwo_file = dwo_file;
10757   dwo_unit->signature = signature;
10758   dwo_unit->section =
10759     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10760   *dwo_unit->section = sections.info_or_types;
10761   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10762
10763   return dwo_unit;
10764 }
10765
10766 /* Subroutine of create_dwo_unit_in_dwp_v2 to simplify it.
10767    Given a pointer to the containing section SECTION, and OFFSET,SIZE of the
10768    piece within that section used by a TU/CU, return a virtual section
10769    of just that piece.  */
10770
10771 static struct dwarf2_section_info
10772 create_dwp_v2_section (struct dwarf2_section_info *section,
10773                        bfd_size_type offset, bfd_size_type size)
10774 {
10775   struct dwarf2_section_info result;
10776   asection *sectp;
10777
10778   gdb_assert (section != NULL);
10779   gdb_assert (!section->is_virtual);
10780
10781   memset (&result, 0, sizeof (result));
10782   result.s.containing_section = section;
10783   result.is_virtual = 1;
10784
10785   if (size == 0)
10786     return result;
10787
10788   sectp = get_section_bfd_section (section);
10789
10790   /* Flag an error if the piece denoted by OFFSET,SIZE is outside the
10791      bounds of the real section.  This is a pretty-rare event, so just
10792      flag an error (easier) instead of a warning and trying to cope.  */
10793   if (sectp == NULL
10794       || offset + size > bfd_get_section_size (sectp))
10795     {
10796       bfd *abfd = sectp->owner;
10797
10798       error (_("Dwarf Error: Bad DWP V2 section info, doesn't fit"
10799                " in section %s [in module %s]"),
10800              sectp ? bfd_section_name (abfd, sectp) : "<unknown>",
10801              objfile_name (dwarf2_per_objfile->objfile));
10802     }
10803
10804   result.virtual_offset = offset;
10805   result.size = size;
10806   return result;
10807 }
10808
10809 /* Create a dwo_unit object for the DWO unit with signature SIGNATURE.
10810    UNIT_INDEX is the index of the DWO unit in the DWP hash table.
10811    COMP_DIR is the DW_AT_comp_dir attribute of the referencing CU.
10812    This is for DWP version 2 files.  */
10813
10814 static struct dwo_unit *
10815 create_dwo_unit_in_dwp_v2 (struct dwp_file *dwp_file,
10816                            uint32_t unit_index,
10817                            const char *comp_dir,
10818                            ULONGEST signature, int is_debug_types)
10819 {
10820   struct objfile *objfile = dwarf2_per_objfile->objfile;
10821   const struct dwp_hash_table *dwp_htab =
10822     is_debug_types ? dwp_file->tus : dwp_file->cus;
10823   bfd *dbfd = dwp_file->dbfd;
10824   const char *kind = is_debug_types ? "TU" : "CU";
10825   struct dwo_file *dwo_file;
10826   struct dwo_unit *dwo_unit;
10827   struct virtual_v2_dwo_sections sections;
10828   void **dwo_file_slot;
10829   int i;
10830
10831   gdb_assert (dwp_file->version == 2);
10832
10833   if (dwarf_read_debug)
10834     {
10835       fprintf_unfiltered (gdb_stdlog, "Reading %s %s/%s in DWP V2 file: %s\n",
10836                           kind,
10837                           pulongest (unit_index), hex_string (signature),
10838                           dwp_file->name);
10839     }
10840
10841   /* Fetch the section offsets of this DWO unit.  */
10842
10843   memset (&sections, 0, sizeof (sections));
10844
10845   for (i = 0; i < dwp_htab->nr_columns; ++i)
10846     {
10847       uint32_t offset = read_4_bytes (dbfd,
10848                                       dwp_htab->section_pool.v2.offsets
10849                                       + (((unit_index - 1) * dwp_htab->nr_columns
10850                                           + i)
10851                                          * sizeof (uint32_t)));
10852       uint32_t size = read_4_bytes (dbfd,
10853                                     dwp_htab->section_pool.v2.sizes
10854                                     + (((unit_index - 1) * dwp_htab->nr_columns
10855                                         + i)
10856                                        * sizeof (uint32_t)));
10857
10858       switch (dwp_htab->section_pool.v2.section_ids[i])
10859         {
10860         case DW_SECT_INFO:
10861         case DW_SECT_TYPES:
10862           sections.info_or_types_offset = offset;
10863           sections.info_or_types_size = size;
10864           break;
10865         case DW_SECT_ABBREV:
10866           sections.abbrev_offset = offset;
10867           sections.abbrev_size = size;
10868           break;
10869         case DW_SECT_LINE:
10870           sections.line_offset = offset;
10871           sections.line_size = size;
10872           break;
10873         case DW_SECT_LOC:
10874           sections.loc_offset = offset;
10875           sections.loc_size = size;
10876           break;
10877         case DW_SECT_STR_OFFSETS:
10878           sections.str_offsets_offset = offset;
10879           sections.str_offsets_size = size;
10880           break;
10881         case DW_SECT_MACINFO:
10882           sections.macinfo_offset = offset;
10883           sections.macinfo_size = size;
10884           break;
10885         case DW_SECT_MACRO:
10886           sections.macro_offset = offset;
10887           sections.macro_size = size;
10888           break;
10889         }
10890     }
10891
10892   /* It's easier for the rest of the code if we fake a struct dwo_file and
10893      have dwo_unit "live" in that.  At least for now.
10894
10895      The DWP file can be made up of a random collection of CUs and TUs.
10896      However, for each CU + set of TUs that came from the same original DWO
10897      file, we can combine them back into a virtual DWO file to save space
10898      (fewer struct dwo_file objects to allocate).  Remember that for really
10899      large apps there can be on the order of 8K CUs and 200K TUs, or more.  */
10900
10901   std::string virtual_dwo_name =
10902     string_printf ("virtual-dwo/%ld-%ld-%ld-%ld",
10903                    (long) (sections.abbrev_size ? sections.abbrev_offset : 0),
10904                    (long) (sections.line_size ? sections.line_offset : 0),
10905                    (long) (sections.loc_size ? sections.loc_offset : 0),
10906                    (long) (sections.str_offsets_size
10907                            ? sections.str_offsets_offset : 0));
10908   /* Can we use an existing virtual DWO file?  */
10909   dwo_file_slot = lookup_dwo_file_slot (virtual_dwo_name.c_str (), comp_dir);
10910   /* Create one if necessary.  */
10911   if (*dwo_file_slot == NULL)
10912     {
10913       if (dwarf_read_debug)
10914         {
10915           fprintf_unfiltered (gdb_stdlog, "Creating virtual DWO: %s\n",
10916                               virtual_dwo_name.c_str ());
10917         }
10918       dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
10919       dwo_file->dwo_name
10920         = (const char *) obstack_copy0 (&objfile->objfile_obstack,
10921                                         virtual_dwo_name.c_str (),
10922                                         virtual_dwo_name.size ());
10923       dwo_file->comp_dir = comp_dir;
10924       dwo_file->sections.abbrev =
10925         create_dwp_v2_section (&dwp_file->sections.abbrev,
10926                                sections.abbrev_offset, sections.abbrev_size);
10927       dwo_file->sections.line =
10928         create_dwp_v2_section (&dwp_file->sections.line,
10929                                sections.line_offset, sections.line_size);
10930       dwo_file->sections.loc =
10931         create_dwp_v2_section (&dwp_file->sections.loc,
10932                                sections.loc_offset, sections.loc_size);
10933       dwo_file->sections.macinfo =
10934         create_dwp_v2_section (&dwp_file->sections.macinfo,
10935                                sections.macinfo_offset, sections.macinfo_size);
10936       dwo_file->sections.macro =
10937         create_dwp_v2_section (&dwp_file->sections.macro,
10938                                sections.macro_offset, sections.macro_size);
10939       dwo_file->sections.str_offsets =
10940         create_dwp_v2_section (&dwp_file->sections.str_offsets,
10941                                sections.str_offsets_offset,
10942                                sections.str_offsets_size);
10943       /* The "str" section is global to the entire DWP file.  */
10944       dwo_file->sections.str = dwp_file->sections.str;
10945       /* The info or types section is assigned below to dwo_unit,
10946          there's no need to record it in dwo_file.
10947          Also, we can't simply record type sections in dwo_file because
10948          we record a pointer into the vector in dwo_unit.  As we collect more
10949          types we'll grow the vector and eventually have to reallocate space
10950          for it, invalidating all copies of pointers into the previous
10951          contents.  */
10952       *dwo_file_slot = dwo_file;
10953     }
10954   else
10955     {
10956       if (dwarf_read_debug)
10957         {
10958           fprintf_unfiltered (gdb_stdlog, "Using existing virtual DWO: %s\n",
10959                               virtual_dwo_name.c_str ());
10960         }
10961       dwo_file = (struct dwo_file *) *dwo_file_slot;
10962     }
10963
10964   dwo_unit = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_unit);
10965   dwo_unit->dwo_file = dwo_file;
10966   dwo_unit->signature = signature;
10967   dwo_unit->section =
10968     XOBNEW (&objfile->objfile_obstack, struct dwarf2_section_info);
10969   *dwo_unit->section = create_dwp_v2_section (is_debug_types
10970                                               ? &dwp_file->sections.types
10971                                               : &dwp_file->sections.info,
10972                                               sections.info_or_types_offset,
10973                                               sections.info_or_types_size);
10974   /* dwo_unit->{offset,length,type_offset_in_tu} are set later.  */
10975
10976   return dwo_unit;
10977 }
10978
10979 /* Lookup the DWO unit with SIGNATURE in DWP_FILE.
10980    Returns NULL if the signature isn't found.  */
10981
10982 static struct dwo_unit *
10983 lookup_dwo_unit_in_dwp (struct dwp_file *dwp_file, const char *comp_dir,
10984                         ULONGEST signature, int is_debug_types)
10985 {
10986   const struct dwp_hash_table *dwp_htab =
10987     is_debug_types ? dwp_file->tus : dwp_file->cus;
10988   bfd *dbfd = dwp_file->dbfd;
10989   uint32_t mask = dwp_htab->nr_slots - 1;
10990   uint32_t hash = signature & mask;
10991   uint32_t hash2 = ((signature >> 32) & mask) | 1;
10992   unsigned int i;
10993   void **slot;
10994   struct dwo_unit find_dwo_cu;
10995
10996   memset (&find_dwo_cu, 0, sizeof (find_dwo_cu));
10997   find_dwo_cu.signature = signature;
10998   slot = htab_find_slot (is_debug_types
10999                          ? dwp_file->loaded_tus
11000                          : dwp_file->loaded_cus,
11001                          &find_dwo_cu, INSERT);
11002
11003   if (*slot != NULL)
11004     return (struct dwo_unit *) *slot;
11005
11006   /* Use a for loop so that we don't loop forever on bad debug info.  */
11007   for (i = 0; i < dwp_htab->nr_slots; ++i)
11008     {
11009       ULONGEST signature_in_table;
11010
11011       signature_in_table =
11012         read_8_bytes (dbfd, dwp_htab->hash_table + hash * sizeof (uint64_t));
11013       if (signature_in_table == signature)
11014         {
11015           uint32_t unit_index =
11016             read_4_bytes (dbfd,
11017                           dwp_htab->unit_table + hash * sizeof (uint32_t));
11018
11019           if (dwp_file->version == 1)
11020             {
11021               *slot = create_dwo_unit_in_dwp_v1 (dwp_file, unit_index,
11022                                                  comp_dir, signature,
11023                                                  is_debug_types);
11024             }
11025           else
11026             {
11027               *slot = create_dwo_unit_in_dwp_v2 (dwp_file, unit_index,
11028                                                  comp_dir, signature,
11029                                                  is_debug_types);
11030             }
11031           return (struct dwo_unit *) *slot;
11032         }
11033       if (signature_in_table == 0)
11034         return NULL;
11035       hash = (hash + hash2) & mask;
11036     }
11037
11038   error (_("Dwarf Error: bad DWP hash table, lookup didn't terminate"
11039            " [in module %s]"),
11040          dwp_file->name);
11041 }
11042
11043 /* Subroutine of open_dwo_file,open_dwp_file to simplify them.
11044    Open the file specified by FILE_NAME and hand it off to BFD for
11045    preliminary analysis.  Return a newly initialized bfd *, which
11046    includes a canonicalized copy of FILE_NAME.
11047    If IS_DWP is TRUE, we're opening a DWP file, otherwise a DWO file.
11048    SEARCH_CWD is true if the current directory is to be searched.
11049    It will be searched before debug-file-directory.
11050    If successful, the file is added to the bfd include table of the
11051    objfile's bfd (see gdb_bfd_record_inclusion).
11052    If unable to find/open the file, return NULL.
11053    NOTE: This function is derived from symfile_bfd_open.  */
11054
11055 static gdb_bfd_ref_ptr
11056 try_open_dwop_file (const char *file_name, int is_dwp, int search_cwd)
11057 {
11058   int desc, flags;
11059   char *absolute_name;
11060   /* Blech.  OPF_TRY_CWD_FIRST also disables searching the path list if
11061      FILE_NAME contains a '/'.  So we can't use it.  Instead prepend "."
11062      to debug_file_directory.  */
11063   char *search_path;
11064   static const char dirname_separator_string[] = { DIRNAME_SEPARATOR, '\0' };
11065
11066   if (search_cwd)
11067     {
11068       if (*debug_file_directory != '\0')
11069         search_path = concat (".", dirname_separator_string,
11070                               debug_file_directory, (char *) NULL);
11071       else
11072         search_path = xstrdup (".");
11073     }
11074   else
11075     search_path = xstrdup (debug_file_directory);
11076
11077   flags = OPF_RETURN_REALPATH;
11078   if (is_dwp)
11079     flags |= OPF_SEARCH_IN_PATH;
11080   desc = openp (search_path, flags, file_name,
11081                 O_RDONLY | O_BINARY, &absolute_name);
11082   xfree (search_path);
11083   if (desc < 0)
11084     return NULL;
11085
11086   gdb_bfd_ref_ptr sym_bfd (gdb_bfd_open (absolute_name, gnutarget, desc));
11087   xfree (absolute_name);
11088   if (sym_bfd == NULL)
11089     return NULL;
11090   bfd_set_cacheable (sym_bfd.get (), 1);
11091
11092   if (!bfd_check_format (sym_bfd.get (), bfd_object))
11093     return NULL;
11094
11095   /* Success.  Record the bfd as having been included by the objfile's bfd.
11096      This is important because things like demangled_names_hash lives in the
11097      objfile's per_bfd space and may have references to things like symbol
11098      names that live in the DWO/DWP file's per_bfd space.  PR 16426.  */
11099   gdb_bfd_record_inclusion (dwarf2_per_objfile->objfile->obfd, sym_bfd.get ());
11100
11101   return sym_bfd;
11102 }
11103
11104 /* Try to open DWO file FILE_NAME.
11105    COMP_DIR is the DW_AT_comp_dir attribute.
11106    The result is the bfd handle of the file.
11107    If there is a problem finding or opening the file, return NULL.
11108    Upon success, the canonicalized path of the file is stored in the bfd,
11109    same as symfile_bfd_open.  */
11110
11111 static gdb_bfd_ref_ptr
11112 open_dwo_file (const char *file_name, const char *comp_dir)
11113 {
11114   if (IS_ABSOLUTE_PATH (file_name))
11115     return try_open_dwop_file (file_name, 0 /*is_dwp*/, 0 /*search_cwd*/);
11116
11117   /* Before trying the search path, try DWO_NAME in COMP_DIR.  */
11118
11119   if (comp_dir != NULL)
11120     {
11121       char *path_to_try = concat (comp_dir, SLASH_STRING,
11122                                   file_name, (char *) NULL);
11123
11124       /* NOTE: If comp_dir is a relative path, this will also try the
11125          search path, which seems useful.  */
11126       gdb_bfd_ref_ptr abfd (try_open_dwop_file (path_to_try, 0 /*is_dwp*/,
11127                                                 1 /*search_cwd*/));
11128       xfree (path_to_try);
11129       if (abfd != NULL)
11130         return abfd;
11131     }
11132
11133   /* That didn't work, try debug-file-directory, which, despite its name,
11134      is a list of paths.  */
11135
11136   if (*debug_file_directory == '\0')
11137     return NULL;
11138
11139   return try_open_dwop_file (file_name, 0 /*is_dwp*/, 1 /*search_cwd*/);
11140 }
11141
11142 /* This function is mapped across the sections and remembers the offset and
11143    size of each of the DWO debugging sections we are interested in.  */
11144
11145 static void
11146 dwarf2_locate_dwo_sections (bfd *abfd, asection *sectp, void *dwo_sections_ptr)
11147 {
11148   struct dwo_sections *dwo_sections = (struct dwo_sections *) dwo_sections_ptr;
11149   const struct dwop_section_names *names = &dwop_section_names;
11150
11151   if (section_is_p (sectp->name, &names->abbrev_dwo))
11152     {
11153       dwo_sections->abbrev.s.section = sectp;
11154       dwo_sections->abbrev.size = bfd_get_section_size (sectp);
11155     }
11156   else if (section_is_p (sectp->name, &names->info_dwo))
11157     {
11158       dwo_sections->info.s.section = sectp;
11159       dwo_sections->info.size = bfd_get_section_size (sectp);
11160     }
11161   else if (section_is_p (sectp->name, &names->line_dwo))
11162     {
11163       dwo_sections->line.s.section = sectp;
11164       dwo_sections->line.size = bfd_get_section_size (sectp);
11165     }
11166   else if (section_is_p (sectp->name, &names->loc_dwo))
11167     {
11168       dwo_sections->loc.s.section = sectp;
11169       dwo_sections->loc.size = bfd_get_section_size (sectp);
11170     }
11171   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11172     {
11173       dwo_sections->macinfo.s.section = sectp;
11174       dwo_sections->macinfo.size = bfd_get_section_size (sectp);
11175     }
11176   else if (section_is_p (sectp->name, &names->macro_dwo))
11177     {
11178       dwo_sections->macro.s.section = sectp;
11179       dwo_sections->macro.size = bfd_get_section_size (sectp);
11180     }
11181   else if (section_is_p (sectp->name, &names->str_dwo))
11182     {
11183       dwo_sections->str.s.section = sectp;
11184       dwo_sections->str.size = bfd_get_section_size (sectp);
11185     }
11186   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11187     {
11188       dwo_sections->str_offsets.s.section = sectp;
11189       dwo_sections->str_offsets.size = bfd_get_section_size (sectp);
11190     }
11191   else if (section_is_p (sectp->name, &names->types_dwo))
11192     {
11193       struct dwarf2_section_info type_section;
11194
11195       memset (&type_section, 0, sizeof (type_section));
11196       type_section.s.section = sectp;
11197       type_section.size = bfd_get_section_size (sectp);
11198       VEC_safe_push (dwarf2_section_info_def, dwo_sections->types,
11199                      &type_section);
11200     }
11201 }
11202
11203 /* Initialize the use of the DWO file specified by DWO_NAME and referenced
11204    by PER_CU.  This is for the non-DWP case.
11205    The result is NULL if DWO_NAME can't be found.  */
11206
11207 static struct dwo_file *
11208 open_and_init_dwo_file (struct dwarf2_per_cu_data *per_cu,
11209                         const char *dwo_name, const char *comp_dir)
11210 {
11211   struct objfile *objfile = dwarf2_per_objfile->objfile;
11212   struct dwo_file *dwo_file;
11213   struct cleanup *cleanups;
11214
11215   gdb_bfd_ref_ptr dbfd (open_dwo_file (dwo_name, comp_dir));
11216   if (dbfd == NULL)
11217     {
11218       if (dwarf_read_debug)
11219         fprintf_unfiltered (gdb_stdlog, "DWO file not found: %s\n", dwo_name);
11220       return NULL;
11221     }
11222   dwo_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwo_file);
11223   dwo_file->dwo_name = dwo_name;
11224   dwo_file->comp_dir = comp_dir;
11225   dwo_file->dbfd = dbfd.release ();
11226
11227   cleanups = make_cleanup (free_dwo_file_cleanup, dwo_file);
11228
11229   bfd_map_over_sections (dwo_file->dbfd, dwarf2_locate_dwo_sections,
11230                          &dwo_file->sections);
11231
11232   create_cus_hash_table (*dwo_file, dwo_file->sections.info, dwo_file->cus);
11233
11234   create_debug_types_hash_table (dwo_file, dwo_file->sections.types,
11235                                  dwo_file->tus);
11236
11237   discard_cleanups (cleanups);
11238
11239   if (dwarf_read_debug)
11240     fprintf_unfiltered (gdb_stdlog, "DWO file found: %s\n", dwo_name);
11241
11242   return dwo_file;
11243 }
11244
11245 /* This function is mapped across the sections and remembers the offset and
11246    size of each of the DWP debugging sections common to version 1 and 2 that
11247    we are interested in.  */
11248
11249 static void
11250 dwarf2_locate_common_dwp_sections (bfd *abfd, asection *sectp,
11251                                    void *dwp_file_ptr)
11252 {
11253   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11254   const struct dwop_section_names *names = &dwop_section_names;
11255   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11256
11257   /* Record the ELF section number for later lookup: this is what the
11258      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11259   gdb_assert (elf_section_nr < dwp_file->num_sections);
11260   dwp_file->elf_sections[elf_section_nr] = sectp;
11261
11262   /* Look for specific sections that we need.  */
11263   if (section_is_p (sectp->name, &names->str_dwo))
11264     {
11265       dwp_file->sections.str.s.section = sectp;
11266       dwp_file->sections.str.size = bfd_get_section_size (sectp);
11267     }
11268   else if (section_is_p (sectp->name, &names->cu_index))
11269     {
11270       dwp_file->sections.cu_index.s.section = sectp;
11271       dwp_file->sections.cu_index.size = bfd_get_section_size (sectp);
11272     }
11273   else if (section_is_p (sectp->name, &names->tu_index))
11274     {
11275       dwp_file->sections.tu_index.s.section = sectp;
11276       dwp_file->sections.tu_index.size = bfd_get_section_size (sectp);
11277     }
11278 }
11279
11280 /* This function is mapped across the sections and remembers the offset and
11281    size of each of the DWP version 2 debugging sections that we are interested
11282    in.  This is split into a separate function because we don't know if we
11283    have version 1 or 2 until we parse the cu_index/tu_index sections.  */
11284
11285 static void
11286 dwarf2_locate_v2_dwp_sections (bfd *abfd, asection *sectp, void *dwp_file_ptr)
11287 {
11288   struct dwp_file *dwp_file = (struct dwp_file *) dwp_file_ptr;
11289   const struct dwop_section_names *names = &dwop_section_names;
11290   unsigned int elf_section_nr = elf_section_data (sectp)->this_idx;
11291
11292   /* Record the ELF section number for later lookup: this is what the
11293      .debug_cu_index,.debug_tu_index tables use in DWP V1.  */
11294   gdb_assert (elf_section_nr < dwp_file->num_sections);
11295   dwp_file->elf_sections[elf_section_nr] = sectp;
11296
11297   /* Look for specific sections that we need.  */
11298   if (section_is_p (sectp->name, &names->abbrev_dwo))
11299     {
11300       dwp_file->sections.abbrev.s.section = sectp;
11301       dwp_file->sections.abbrev.size = bfd_get_section_size (sectp);
11302     }
11303   else if (section_is_p (sectp->name, &names->info_dwo))
11304     {
11305       dwp_file->sections.info.s.section = sectp;
11306       dwp_file->sections.info.size = bfd_get_section_size (sectp);
11307     }
11308   else if (section_is_p (sectp->name, &names->line_dwo))
11309     {
11310       dwp_file->sections.line.s.section = sectp;
11311       dwp_file->sections.line.size = bfd_get_section_size (sectp);
11312     }
11313   else if (section_is_p (sectp->name, &names->loc_dwo))
11314     {
11315       dwp_file->sections.loc.s.section = sectp;
11316       dwp_file->sections.loc.size = bfd_get_section_size (sectp);
11317     }
11318   else if (section_is_p (sectp->name, &names->macinfo_dwo))
11319     {
11320       dwp_file->sections.macinfo.s.section = sectp;
11321       dwp_file->sections.macinfo.size = bfd_get_section_size (sectp);
11322     }
11323   else if (section_is_p (sectp->name, &names->macro_dwo))
11324     {
11325       dwp_file->sections.macro.s.section = sectp;
11326       dwp_file->sections.macro.size = bfd_get_section_size (sectp);
11327     }
11328   else if (section_is_p (sectp->name, &names->str_offsets_dwo))
11329     {
11330       dwp_file->sections.str_offsets.s.section = sectp;
11331       dwp_file->sections.str_offsets.size = bfd_get_section_size (sectp);
11332     }
11333   else if (section_is_p (sectp->name, &names->types_dwo))
11334     {
11335       dwp_file->sections.types.s.section = sectp;
11336       dwp_file->sections.types.size = bfd_get_section_size (sectp);
11337     }
11338 }
11339
11340 /* Hash function for dwp_file loaded CUs/TUs.  */
11341
11342 static hashval_t
11343 hash_dwp_loaded_cutus (const void *item)
11344 {
11345   const struct dwo_unit *dwo_unit = (const struct dwo_unit *) item;
11346
11347   /* This drops the top 32 bits of the signature, but is ok for a hash.  */
11348   return dwo_unit->signature;
11349 }
11350
11351 /* Equality function for dwp_file loaded CUs/TUs.  */
11352
11353 static int
11354 eq_dwp_loaded_cutus (const void *a, const void *b)
11355 {
11356   const struct dwo_unit *dua = (const struct dwo_unit *) a;
11357   const struct dwo_unit *dub = (const struct dwo_unit *) b;
11358
11359   return dua->signature == dub->signature;
11360 }
11361
11362 /* Allocate a hash table for dwp_file loaded CUs/TUs.  */
11363
11364 static htab_t
11365 allocate_dwp_loaded_cutus_table (struct objfile *objfile)
11366 {
11367   return htab_create_alloc_ex (3,
11368                                hash_dwp_loaded_cutus,
11369                                eq_dwp_loaded_cutus,
11370                                NULL,
11371                                &objfile->objfile_obstack,
11372                                hashtab_obstack_allocate,
11373                                dummy_obstack_deallocate);
11374 }
11375
11376 /* Try to open DWP file FILE_NAME.
11377    The result is the bfd handle of the file.
11378    If there is a problem finding or opening the file, return NULL.
11379    Upon success, the canonicalized path of the file is stored in the bfd,
11380    same as symfile_bfd_open.  */
11381
11382 static gdb_bfd_ref_ptr
11383 open_dwp_file (const char *file_name)
11384 {
11385   gdb_bfd_ref_ptr abfd (try_open_dwop_file (file_name, 1 /*is_dwp*/,
11386                                             1 /*search_cwd*/));
11387   if (abfd != NULL)
11388     return abfd;
11389
11390   /* Work around upstream bug 15652.
11391      http://sourceware.org/bugzilla/show_bug.cgi?id=15652
11392      [Whether that's a "bug" is debatable, but it is getting in our way.]
11393      We have no real idea where the dwp file is, because gdb's realpath-ing
11394      of the executable's path may have discarded the needed info.
11395      [IWBN if the dwp file name was recorded in the executable, akin to
11396      .gnu_debuglink, but that doesn't exist yet.]
11397      Strip the directory from FILE_NAME and search again.  */
11398   if (*debug_file_directory != '\0')
11399     {
11400       /* Don't implicitly search the current directory here.
11401          If the user wants to search "." to handle this case,
11402          it must be added to debug-file-directory.  */
11403       return try_open_dwop_file (lbasename (file_name), 1 /*is_dwp*/,
11404                                  0 /*search_cwd*/);
11405     }
11406
11407   return NULL;
11408 }
11409
11410 /* Initialize the use of the DWP file for the current objfile.
11411    By convention the name of the DWP file is ${objfile}.dwp.
11412    The result is NULL if it can't be found.  */
11413
11414 static struct dwp_file *
11415 open_and_init_dwp_file (void)
11416 {
11417   struct objfile *objfile = dwarf2_per_objfile->objfile;
11418   struct dwp_file *dwp_file;
11419
11420   /* Try to find first .dwp for the binary file before any symbolic links
11421      resolving.  */
11422
11423   /* If the objfile is a debug file, find the name of the real binary
11424      file and get the name of dwp file from there.  */
11425   std::string dwp_name;
11426   if (objfile->separate_debug_objfile_backlink != NULL)
11427     {
11428       struct objfile *backlink = objfile->separate_debug_objfile_backlink;
11429       const char *backlink_basename = lbasename (backlink->original_name);
11430
11431       dwp_name = ldirname (objfile->original_name) + SLASH_STRING + backlink_basename;
11432     }
11433   else
11434     dwp_name = objfile->original_name;
11435
11436   dwp_name += ".dwp";
11437
11438   gdb_bfd_ref_ptr dbfd (open_dwp_file (dwp_name.c_str ()));
11439   if (dbfd == NULL
11440       && strcmp (objfile->original_name, objfile_name (objfile)) != 0)
11441     {
11442       /* Try to find .dwp for the binary file after gdb_realpath resolving.  */
11443       dwp_name = objfile_name (objfile);
11444       dwp_name += ".dwp";
11445       dbfd = open_dwp_file (dwp_name.c_str ());
11446     }
11447
11448   if (dbfd == NULL)
11449     {
11450       if (dwarf_read_debug)
11451         fprintf_unfiltered (gdb_stdlog, "DWP file not found: %s\n", dwp_name.c_str ());
11452       return NULL;
11453     }
11454   dwp_file = OBSTACK_ZALLOC (&objfile->objfile_obstack, struct dwp_file);
11455   dwp_file->name = bfd_get_filename (dbfd.get ());
11456   dwp_file->dbfd = dbfd.release ();
11457
11458   /* +1: section 0 is unused */
11459   dwp_file->num_sections = bfd_count_sections (dwp_file->dbfd) + 1;
11460   dwp_file->elf_sections =
11461     OBSTACK_CALLOC (&objfile->objfile_obstack,
11462                     dwp_file->num_sections, asection *);
11463
11464   bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_common_dwp_sections,
11465                          dwp_file);
11466
11467   dwp_file->cus = create_dwp_hash_table (dwp_file, 0);
11468
11469   dwp_file->tus = create_dwp_hash_table (dwp_file, 1);
11470
11471   /* The DWP file version is stored in the hash table.  Oh well.  */
11472   if (dwp_file->cus && dwp_file->tus
11473       && dwp_file->cus->version != dwp_file->tus->version)
11474     {
11475       /* Technically speaking, we should try to limp along, but this is
11476          pretty bizarre.  We use pulongest here because that's the established
11477          portability solution (e.g, we cannot use %u for uint32_t).  */
11478       error (_("Dwarf Error: DWP file CU version %s doesn't match"
11479                " TU version %s [in DWP file %s]"),
11480              pulongest (dwp_file->cus->version),
11481              pulongest (dwp_file->tus->version), dwp_name.c_str ());
11482     }
11483
11484   if (dwp_file->cus)
11485     dwp_file->version = dwp_file->cus->version;
11486   else if (dwp_file->tus)
11487     dwp_file->version = dwp_file->tus->version;
11488   else
11489     dwp_file->version = 2;
11490
11491   if (dwp_file->version == 2)
11492     bfd_map_over_sections (dwp_file->dbfd, dwarf2_locate_v2_dwp_sections,
11493                            dwp_file);
11494
11495   dwp_file->loaded_cus = allocate_dwp_loaded_cutus_table (objfile);
11496   dwp_file->loaded_tus = allocate_dwp_loaded_cutus_table (objfile);
11497
11498   if (dwarf_read_debug)
11499     {
11500       fprintf_unfiltered (gdb_stdlog, "DWP file found: %s\n", dwp_file->name);
11501       fprintf_unfiltered (gdb_stdlog,
11502                           "    %s CUs, %s TUs\n",
11503                           pulongest (dwp_file->cus ? dwp_file->cus->nr_units : 0),
11504                           pulongest (dwp_file->tus ? dwp_file->tus->nr_units : 0));
11505     }
11506
11507   return dwp_file;
11508 }
11509
11510 /* Wrapper around open_and_init_dwp_file, only open it once.  */
11511
11512 static struct dwp_file *
11513 get_dwp_file (void)
11514 {
11515   if (! dwarf2_per_objfile->dwp_checked)
11516     {
11517       dwarf2_per_objfile->dwp_file = open_and_init_dwp_file ();
11518       dwarf2_per_objfile->dwp_checked = 1;
11519     }
11520   return dwarf2_per_objfile->dwp_file;
11521 }
11522
11523 /* Subroutine of lookup_dwo_comp_unit, lookup_dwo_type_unit.
11524    Look up the CU/TU with signature SIGNATURE, either in DWO file DWO_NAME
11525    or in the DWP file for the objfile, referenced by THIS_UNIT.
11526    If non-NULL, comp_dir is the DW_AT_comp_dir attribute.
11527    IS_DEBUG_TYPES is non-zero if reading a TU, otherwise read a CU.
11528
11529    This is called, for example, when wanting to read a variable with a
11530    complex location.  Therefore we don't want to do file i/o for every call.
11531    Therefore we don't want to look for a DWO file on every call.
11532    Therefore we first see if we've already seen SIGNATURE in a DWP file,
11533    then we check if we've already seen DWO_NAME, and only THEN do we check
11534    for a DWO file.
11535
11536    The result is a pointer to the dwo_unit object or NULL if we didn't find it
11537    (dwo_id mismatch or couldn't find the DWO/DWP file).  */
11538
11539 static struct dwo_unit *
11540 lookup_dwo_cutu (struct dwarf2_per_cu_data *this_unit,
11541                  const char *dwo_name, const char *comp_dir,
11542                  ULONGEST signature, int is_debug_types)
11543 {
11544   struct objfile *objfile = dwarf2_per_objfile->objfile;
11545   const char *kind = is_debug_types ? "TU" : "CU";
11546   void **dwo_file_slot;
11547   struct dwo_file *dwo_file;
11548   struct dwp_file *dwp_file;
11549
11550   /* First see if there's a DWP file.
11551      If we have a DWP file but didn't find the DWO inside it, don't
11552      look for the original DWO file.  It makes gdb behave differently
11553      depending on whether one is debugging in the build tree.  */
11554
11555   dwp_file = get_dwp_file ();
11556   if (dwp_file != NULL)
11557     {
11558       const struct dwp_hash_table *dwp_htab =
11559         is_debug_types ? dwp_file->tus : dwp_file->cus;
11560
11561       if (dwp_htab != NULL)
11562         {
11563           struct dwo_unit *dwo_cutu =
11564             lookup_dwo_unit_in_dwp (dwp_file, comp_dir,
11565                                     signature, is_debug_types);
11566
11567           if (dwo_cutu != NULL)
11568             {
11569               if (dwarf_read_debug)
11570                 {
11571                   fprintf_unfiltered (gdb_stdlog,
11572                                       "Virtual DWO %s %s found: @%s\n",
11573                                       kind, hex_string (signature),
11574                                       host_address_to_string (dwo_cutu));
11575                 }
11576               return dwo_cutu;
11577             }
11578         }
11579     }
11580   else
11581     {
11582       /* No DWP file, look for the DWO file.  */
11583
11584       dwo_file_slot = lookup_dwo_file_slot (dwo_name, comp_dir);
11585       if (*dwo_file_slot == NULL)
11586         {
11587           /* Read in the file and build a table of the CUs/TUs it contains.  */
11588           *dwo_file_slot = open_and_init_dwo_file (this_unit, dwo_name, comp_dir);
11589         }
11590       /* NOTE: This will be NULL if unable to open the file.  */
11591       dwo_file = (struct dwo_file *) *dwo_file_slot;
11592
11593       if (dwo_file != NULL)
11594         {
11595           struct dwo_unit *dwo_cutu = NULL;
11596
11597           if (is_debug_types && dwo_file->tus)
11598             {
11599               struct dwo_unit find_dwo_cutu;
11600
11601               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11602               find_dwo_cutu.signature = signature;
11603               dwo_cutu
11604                 = (struct dwo_unit *) htab_find (dwo_file->tus, &find_dwo_cutu);
11605             }
11606           else if (!is_debug_types && dwo_file->cus)
11607             {
11608               struct dwo_unit find_dwo_cutu;
11609
11610               memset (&find_dwo_cutu, 0, sizeof (find_dwo_cutu));
11611               find_dwo_cutu.signature = signature;
11612               dwo_cutu = (struct dwo_unit *)htab_find (dwo_file->cus,
11613                                                        &find_dwo_cutu);
11614             }
11615
11616           if (dwo_cutu != NULL)
11617             {
11618               if (dwarf_read_debug)
11619                 {
11620                   fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) found: @%s\n",
11621                                       kind, dwo_name, hex_string (signature),
11622                                       host_address_to_string (dwo_cutu));
11623                 }
11624               return dwo_cutu;
11625             }
11626         }
11627     }
11628
11629   /* We didn't find it.  This could mean a dwo_id mismatch, or
11630      someone deleted the DWO/DWP file, or the search path isn't set up
11631      correctly to find the file.  */
11632
11633   if (dwarf_read_debug)
11634     {
11635       fprintf_unfiltered (gdb_stdlog, "DWO %s %s(%s) not found\n",
11636                           kind, dwo_name, hex_string (signature));
11637     }
11638
11639   /* This is a warning and not a complaint because it can be caused by
11640      pilot error (e.g., user accidentally deleting the DWO).  */
11641   {
11642     /* Print the name of the DWP file if we looked there, helps the user
11643        better diagnose the problem.  */
11644     std::string dwp_text;
11645
11646     if (dwp_file != NULL)
11647       dwp_text = string_printf (" [in DWP file %s]",
11648                                 lbasename (dwp_file->name));
11649
11650     warning (_("Could not find DWO %s %s(%s)%s referenced by %s at offset 0x%x"
11651                " [in module %s]"),
11652              kind, dwo_name, hex_string (signature),
11653              dwp_text.c_str (),
11654              this_unit->is_debug_types ? "TU" : "CU",
11655              to_underlying (this_unit->sect_off), objfile_name (objfile));
11656   }
11657   return NULL;
11658 }
11659
11660 /* Lookup the DWO CU DWO_NAME/SIGNATURE referenced from THIS_CU.
11661    See lookup_dwo_cutu_unit for details.  */
11662
11663 static struct dwo_unit *
11664 lookup_dwo_comp_unit (struct dwarf2_per_cu_data *this_cu,
11665                       const char *dwo_name, const char *comp_dir,
11666                       ULONGEST signature)
11667 {
11668   return lookup_dwo_cutu (this_cu, dwo_name, comp_dir, signature, 0);
11669 }
11670
11671 /* Lookup the DWO TU DWO_NAME/SIGNATURE referenced from THIS_TU.
11672    See lookup_dwo_cutu_unit for details.  */
11673
11674 static struct dwo_unit *
11675 lookup_dwo_type_unit (struct signatured_type *this_tu,
11676                       const char *dwo_name, const char *comp_dir)
11677 {
11678   return lookup_dwo_cutu (&this_tu->per_cu, dwo_name, comp_dir, this_tu->signature, 1);
11679 }
11680
11681 /* Traversal function for queue_and_load_all_dwo_tus.  */
11682
11683 static int
11684 queue_and_load_dwo_tu (void **slot, void *info)
11685 {
11686   struct dwo_unit *dwo_unit = (struct dwo_unit *) *slot;
11687   struct dwarf2_per_cu_data *per_cu = (struct dwarf2_per_cu_data *) info;
11688   ULONGEST signature = dwo_unit->signature;
11689   struct signatured_type *sig_type =
11690     lookup_dwo_signatured_type (per_cu->cu, signature);
11691
11692   if (sig_type != NULL)
11693     {
11694       struct dwarf2_per_cu_data *sig_cu = &sig_type->per_cu;
11695
11696       /* We pass NULL for DEPENDENT_CU because we don't yet know if there's
11697          a real dependency of PER_CU on SIG_TYPE.  That is detected later
11698          while processing PER_CU.  */
11699       if (maybe_queue_comp_unit (NULL, sig_cu, per_cu->cu->language))
11700         load_full_type_unit (sig_cu);
11701       VEC_safe_push (dwarf2_per_cu_ptr, per_cu->imported_symtabs, sig_cu);
11702     }
11703
11704   return 1;
11705 }
11706
11707 /* Queue all TUs contained in the DWO of PER_CU to be read in.
11708    The DWO may have the only definition of the type, though it may not be
11709    referenced anywhere in PER_CU.  Thus we have to load *all* its TUs.
11710    http://sourceware.org/bugzilla/show_bug.cgi?id=15021  */
11711
11712 static void
11713 queue_and_load_all_dwo_tus (struct dwarf2_per_cu_data *per_cu)
11714 {
11715   struct dwo_unit *dwo_unit;
11716   struct dwo_file *dwo_file;
11717
11718   gdb_assert (!per_cu->is_debug_types);
11719   gdb_assert (get_dwp_file () == NULL);
11720   gdb_assert (per_cu->cu != NULL);
11721
11722   dwo_unit = per_cu->cu->dwo_unit;
11723   gdb_assert (dwo_unit != NULL);
11724
11725   dwo_file = dwo_unit->dwo_file;
11726   if (dwo_file->tus != NULL)
11727     htab_traverse_noresize (dwo_file->tus, queue_and_load_dwo_tu, per_cu);
11728 }
11729
11730 /* Free all resources associated with DWO_FILE.
11731    Close the DWO file and munmap the sections.
11732    All memory should be on the objfile obstack.  */
11733
11734 static void
11735 free_dwo_file (struct dwo_file *dwo_file, struct objfile *objfile)
11736 {
11737
11738   /* Note: dbfd is NULL for virtual DWO files.  */
11739   gdb_bfd_unref (dwo_file->dbfd);
11740
11741   VEC_free (dwarf2_section_info_def, dwo_file->sections.types);
11742 }
11743
11744 /* Wrapper for free_dwo_file for use in cleanups.  */
11745
11746 static void
11747 free_dwo_file_cleanup (void *arg)
11748 {
11749   struct dwo_file *dwo_file = (struct dwo_file *) arg;
11750   struct objfile *objfile = dwarf2_per_objfile->objfile;
11751
11752   free_dwo_file (dwo_file, objfile);
11753 }
11754
11755 /* Traversal function for free_dwo_files.  */
11756
11757 static int
11758 free_dwo_file_from_slot (void **slot, void *info)
11759 {
11760   struct dwo_file *dwo_file = (struct dwo_file *) *slot;
11761   struct objfile *objfile = (struct objfile *) info;
11762
11763   free_dwo_file (dwo_file, objfile);
11764
11765   return 1;
11766 }
11767
11768 /* Free all resources associated with DWO_FILES.  */
11769
11770 static void
11771 free_dwo_files (htab_t dwo_files, struct objfile *objfile)
11772 {
11773   htab_traverse_noresize (dwo_files, free_dwo_file_from_slot, objfile);
11774 }
11775 \f
11776 /* Read in various DIEs.  */
11777
11778 /* DW_AT_abstract_origin inherits whole DIEs (not just their attributes).
11779    Inherit only the children of the DW_AT_abstract_origin DIE not being
11780    already referenced by DW_AT_abstract_origin from the children of the
11781    current DIE.  */
11782
11783 static void
11784 inherit_abstract_dies (struct die_info *die, struct dwarf2_cu *cu)
11785 {
11786   struct die_info *child_die;
11787   sect_offset *offsetp;
11788   /* Parent of DIE - referenced by DW_AT_abstract_origin.  */
11789   struct die_info *origin_die;
11790   /* Iterator of the ORIGIN_DIE children.  */
11791   struct die_info *origin_child_die;
11792   struct attribute *attr;
11793   struct dwarf2_cu *origin_cu;
11794   struct pending **origin_previous_list_in_scope;
11795
11796   attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
11797   if (!attr)
11798     return;
11799
11800   /* Note that following die references may follow to a die in a
11801      different cu.  */
11802
11803   origin_cu = cu;
11804   origin_die = follow_die_ref (die, attr, &origin_cu);
11805
11806   /* We're inheriting ORIGIN's children into the scope we'd put DIE's
11807      symbols in.  */
11808   origin_previous_list_in_scope = origin_cu->list_in_scope;
11809   origin_cu->list_in_scope = cu->list_in_scope;
11810
11811   if (die->tag != origin_die->tag
11812       && !(die->tag == DW_TAG_inlined_subroutine
11813            && origin_die->tag == DW_TAG_subprogram))
11814     complaint (&symfile_complaints,
11815                _("DIE 0x%x and its abstract origin 0x%x have different tags"),
11816                to_underlying (die->sect_off),
11817                to_underlying (origin_die->sect_off));
11818
11819   std::vector<sect_offset> offsets;
11820
11821   for (child_die = die->child;
11822        child_die && child_die->tag;
11823        child_die = sibling_die (child_die))
11824     {
11825       struct die_info *child_origin_die;
11826       struct dwarf2_cu *child_origin_cu;
11827
11828       /* We are trying to process concrete instance entries:
11829          DW_TAG_call_site DIEs indeed have a DW_AT_abstract_origin tag, but
11830          it's not relevant to our analysis here. i.e. detecting DIEs that are
11831          present in the abstract instance but not referenced in the concrete
11832          one.  */
11833       if (child_die->tag == DW_TAG_call_site
11834           || child_die->tag == DW_TAG_GNU_call_site)
11835         continue;
11836
11837       /* For each CHILD_DIE, find the corresponding child of
11838          ORIGIN_DIE.  If there is more than one layer of
11839          DW_AT_abstract_origin, follow them all; there shouldn't be,
11840          but GCC versions at least through 4.4 generate this (GCC PR
11841          40573).  */
11842       child_origin_die = child_die;
11843       child_origin_cu = cu;
11844       while (1)
11845         {
11846           attr = dwarf2_attr (child_origin_die, DW_AT_abstract_origin,
11847                               child_origin_cu);
11848           if (attr == NULL)
11849             break;
11850           child_origin_die = follow_die_ref (child_origin_die, attr,
11851                                              &child_origin_cu);
11852         }
11853
11854       /* According to DWARF3 3.3.8.2 #3 new entries without their abstract
11855          counterpart may exist.  */
11856       if (child_origin_die != child_die)
11857         {
11858           if (child_die->tag != child_origin_die->tag
11859               && !(child_die->tag == DW_TAG_inlined_subroutine
11860                    && child_origin_die->tag == DW_TAG_subprogram))
11861             complaint (&symfile_complaints,
11862                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11863                          "different tags"),
11864                        to_underlying (child_die->sect_off),
11865                        to_underlying (child_origin_die->sect_off));
11866           if (child_origin_die->parent != origin_die)
11867             complaint (&symfile_complaints,
11868                        _("Child DIE 0x%x and its abstract origin 0x%x have "
11869                          "different parents"),
11870                        to_underlying (child_die->sect_off),
11871                        to_underlying (child_origin_die->sect_off));
11872           else
11873             offsets.push_back (child_origin_die->sect_off);
11874         }
11875     }
11876   std::sort (offsets.begin (), offsets.end ());
11877   sect_offset *offsets_end = offsets.data () + offsets.size ();
11878   for (offsetp = offsets.data () + 1; offsetp < offsets_end; offsetp++)
11879     if (offsetp[-1] == *offsetp)
11880       complaint (&symfile_complaints,
11881                  _("Multiple children of DIE 0x%x refer "
11882                    "to DIE 0x%x as their abstract origin"),
11883                  to_underlying (die->sect_off), to_underlying (*offsetp));
11884
11885   offsetp = offsets.data ();
11886   origin_child_die = origin_die->child;
11887   while (origin_child_die && origin_child_die->tag)
11888     {
11889       /* Is ORIGIN_CHILD_DIE referenced by any of the DIE children?  */
11890       while (offsetp < offsets_end
11891              && *offsetp < origin_child_die->sect_off)
11892         offsetp++;
11893       if (offsetp >= offsets_end
11894           || *offsetp > origin_child_die->sect_off)
11895         {
11896           /* Found that ORIGIN_CHILD_DIE is really not referenced.
11897              Check whether we're already processing ORIGIN_CHILD_DIE.
11898              This can happen with mutually referenced abstract_origins.
11899              PR 16581.  */
11900           if (!origin_child_die->in_process)
11901             process_die (origin_child_die, origin_cu);
11902         }
11903       origin_child_die = sibling_die (origin_child_die);
11904     }
11905   origin_cu->list_in_scope = origin_previous_list_in_scope;
11906 }
11907
11908 static void
11909 read_func_scope (struct die_info *die, struct dwarf2_cu *cu)
11910 {
11911   struct objfile *objfile = cu->objfile;
11912   struct gdbarch *gdbarch = get_objfile_arch (objfile);
11913   struct context_stack *newobj;
11914   CORE_ADDR lowpc;
11915   CORE_ADDR highpc;
11916   struct die_info *child_die;
11917   struct attribute *attr, *call_line, *call_file;
11918   const char *name;
11919   CORE_ADDR baseaddr;
11920   struct block *block;
11921   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
11922   VEC (symbolp) *template_args = NULL;
11923   struct template_symbol *templ_func = NULL;
11924
11925   if (inlined_func)
11926     {
11927       /* If we do not have call site information, we can't show the
11928          caller of this inlined function.  That's too confusing, so
11929          only use the scope for local variables.  */
11930       call_line = dwarf2_attr (die, DW_AT_call_line, cu);
11931       call_file = dwarf2_attr (die, DW_AT_call_file, cu);
11932       if (call_line == NULL || call_file == NULL)
11933         {
11934           read_lexical_block_scope (die, cu);
11935           return;
11936         }
11937     }
11938
11939   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
11940
11941   name = dwarf2_name (die, cu);
11942
11943   /* Ignore functions with missing or empty names.  These are actually
11944      illegal according to the DWARF standard.  */
11945   if (name == NULL)
11946     {
11947       complaint (&symfile_complaints,
11948                  _("missing name for subprogram DIE at %d"),
11949                  to_underlying (die->sect_off));
11950       return;
11951     }
11952
11953   /* Ignore functions with missing or invalid low and high pc attributes.  */
11954   if (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL)
11955       <= PC_BOUNDS_INVALID)
11956     {
11957       attr = dwarf2_attr (die, DW_AT_external, cu);
11958       if (!attr || !DW_UNSND (attr))
11959         complaint (&symfile_complaints,
11960                    _("cannot get low and high bounds "
11961                      "for subprogram DIE at %d"),
11962                    to_underlying (die->sect_off));
11963       return;
11964     }
11965
11966   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
11967   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
11968
11969   /* If we have any template arguments, then we must allocate a
11970      different sort of symbol.  */
11971   for (child_die = die->child; child_die; child_die = sibling_die (child_die))
11972     {
11973       if (child_die->tag == DW_TAG_template_type_param
11974           || child_die->tag == DW_TAG_template_value_param)
11975         {
11976           templ_func = allocate_template_symbol (objfile);
11977           templ_func->base.is_cplus_template_function = 1;
11978           break;
11979         }
11980     }
11981
11982   newobj = push_context (0, lowpc);
11983   newobj->name = new_symbol_full (die, read_type_die (die, cu), cu,
11984                                (struct symbol *) templ_func);
11985
11986   /* If there is a location expression for DW_AT_frame_base, record
11987      it.  */
11988   attr = dwarf2_attr (die, DW_AT_frame_base, cu);
11989   if (attr)
11990     dwarf2_symbol_mark_computed (attr, newobj->name, cu, 1);
11991
11992   /* If there is a location for the static link, record it.  */
11993   newobj->static_link = NULL;
11994   attr = dwarf2_attr (die, DW_AT_static_link, cu);
11995   if (attr)
11996     {
11997       newobj->static_link
11998         = XOBNEW (&objfile->objfile_obstack, struct dynamic_prop);
11999       attr_to_dynamic_prop (attr, die, cu, newobj->static_link);
12000     }
12001
12002   cu->list_in_scope = &local_symbols;
12003
12004   if (die->child != NULL)
12005     {
12006       child_die = die->child;
12007       while (child_die && child_die->tag)
12008         {
12009           if (child_die->tag == DW_TAG_template_type_param
12010               || child_die->tag == DW_TAG_template_value_param)
12011             {
12012               struct symbol *arg = new_symbol (child_die, NULL, cu);
12013
12014               if (arg != NULL)
12015                 VEC_safe_push (symbolp, template_args, arg);
12016             }
12017           else
12018             process_die (child_die, cu);
12019           child_die = sibling_die (child_die);
12020         }
12021     }
12022
12023   inherit_abstract_dies (die, cu);
12024
12025   /* If we have a DW_AT_specification, we might need to import using
12026      directives from the context of the specification DIE.  See the
12027      comment in determine_prefix.  */
12028   if (cu->language == language_cplus
12029       && dwarf2_attr (die, DW_AT_specification, cu))
12030     {
12031       struct dwarf2_cu *spec_cu = cu;
12032       struct die_info *spec_die = die_specification (die, &spec_cu);
12033
12034       while (spec_die)
12035         {
12036           child_die = spec_die->child;
12037           while (child_die && child_die->tag)
12038             {
12039               if (child_die->tag == DW_TAG_imported_module)
12040                 process_die (child_die, spec_cu);
12041               child_die = sibling_die (child_die);
12042             }
12043
12044           /* In some cases, GCC generates specification DIEs that
12045              themselves contain DW_AT_specification attributes.  */
12046           spec_die = die_specification (spec_die, &spec_cu);
12047         }
12048     }
12049
12050   newobj = pop_context ();
12051   /* Make a block for the local symbols within.  */
12052   block = finish_block (newobj->name, &local_symbols, newobj->old_blocks,
12053                         newobj->static_link, lowpc, highpc);
12054
12055   /* For C++, set the block's scope.  */
12056   if ((cu->language == language_cplus
12057        || cu->language == language_fortran
12058        || cu->language == language_d
12059        || cu->language == language_rust)
12060       && cu->processing_has_namespace_info)
12061     block_set_scope (block, determine_prefix (die, cu),
12062                      &objfile->objfile_obstack);
12063
12064   /* If we have address ranges, record them.  */
12065   dwarf2_record_block_ranges (die, block, baseaddr, cu);
12066
12067   gdbarch_make_symbol_special (gdbarch, newobj->name, objfile);
12068
12069   /* Attach template arguments to function.  */
12070   if (! VEC_empty (symbolp, template_args))
12071     {
12072       gdb_assert (templ_func != NULL);
12073
12074       templ_func->n_template_arguments = VEC_length (symbolp, template_args);
12075       templ_func->template_arguments
12076         = XOBNEWVEC (&objfile->objfile_obstack, struct symbol *,
12077                      templ_func->n_template_arguments);
12078       memcpy (templ_func->template_arguments,
12079               VEC_address (symbolp, template_args),
12080               (templ_func->n_template_arguments * sizeof (struct symbol *)));
12081       VEC_free (symbolp, template_args);
12082     }
12083
12084   /* In C++, we can have functions nested inside functions (e.g., when
12085      a function declares a class that has methods).  This means that
12086      when we finish processing a function scope, we may need to go
12087      back to building a containing block's symbol lists.  */
12088   local_symbols = newobj->locals;
12089   local_using_directives = newobj->local_using_directives;
12090
12091   /* If we've finished processing a top-level function, subsequent
12092      symbols go in the file symbol list.  */
12093   if (outermost_context_p ())
12094     cu->list_in_scope = &file_symbols;
12095 }
12096
12097 /* Process all the DIES contained within a lexical block scope.  Start
12098    a new scope, process the dies, and then close the scope.  */
12099
12100 static void
12101 read_lexical_block_scope (struct die_info *die, struct dwarf2_cu *cu)
12102 {
12103   struct objfile *objfile = cu->objfile;
12104   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12105   struct context_stack *newobj;
12106   CORE_ADDR lowpc, highpc;
12107   struct die_info *child_die;
12108   CORE_ADDR baseaddr;
12109
12110   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12111
12112   /* Ignore blocks with missing or invalid low and high pc attributes.  */
12113   /* ??? Perhaps consider discontiguous blocks defined by DW_AT_ranges
12114      as multiple lexical blocks?  Handling children in a sane way would
12115      be nasty.  Might be easier to properly extend generic blocks to
12116      describe ranges.  */
12117   switch (dwarf2_get_pc_bounds (die, &lowpc, &highpc, cu, NULL))
12118     {
12119     case PC_BOUNDS_NOT_PRESENT:
12120       /* DW_TAG_lexical_block has no attributes, process its children as if
12121          there was no wrapping by that DW_TAG_lexical_block.
12122          GCC does no longer produces such DWARF since GCC r224161.  */
12123       for (child_die = die->child;
12124            child_die != NULL && child_die->tag;
12125            child_die = sibling_die (child_die))
12126         process_die (child_die, cu);
12127       return;
12128     case PC_BOUNDS_INVALID:
12129       return;
12130     }
12131   lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12132   highpc = gdbarch_adjust_dwarf2_addr (gdbarch, highpc + baseaddr);
12133
12134   push_context (0, lowpc);
12135   if (die->child != NULL)
12136     {
12137       child_die = die->child;
12138       while (child_die && child_die->tag)
12139         {
12140           process_die (child_die, cu);
12141           child_die = sibling_die (child_die);
12142         }
12143     }
12144   inherit_abstract_dies (die, cu);
12145   newobj = pop_context ();
12146
12147   if (local_symbols != NULL || local_using_directives != NULL)
12148     {
12149       struct block *block
12150         = finish_block (0, &local_symbols, newobj->old_blocks, NULL,
12151                         newobj->start_addr, highpc);
12152
12153       /* Note that recording ranges after traversing children, as we
12154          do here, means that recording a parent's ranges entails
12155          walking across all its children's ranges as they appear in
12156          the address map, which is quadratic behavior.
12157
12158          It would be nicer to record the parent's ranges before
12159          traversing its children, simply overriding whatever you find
12160          there.  But since we don't even decide whether to create a
12161          block until after we've traversed its children, that's hard
12162          to do.  */
12163       dwarf2_record_block_ranges (die, block, baseaddr, cu);
12164     }
12165   local_symbols = newobj->locals;
12166   local_using_directives = newobj->local_using_directives;
12167 }
12168
12169 /* Read in DW_TAG_call_site and insert it to CU->call_site_htab.  */
12170
12171 static void
12172 read_call_site_scope (struct die_info *die, struct dwarf2_cu *cu)
12173 {
12174   struct objfile *objfile = cu->objfile;
12175   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12176   CORE_ADDR pc, baseaddr;
12177   struct attribute *attr;
12178   struct call_site *call_site, call_site_local;
12179   void **slot;
12180   int nparams;
12181   struct die_info *child_die;
12182
12183   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12184
12185   attr = dwarf2_attr (die, DW_AT_call_return_pc, cu);
12186   if (attr == NULL)
12187     {
12188       /* This was a pre-DWARF-5 GNU extension alias
12189          for DW_AT_call_return_pc.  */
12190       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12191     }
12192   if (!attr)
12193     {
12194       complaint (&symfile_complaints,
12195                  _("missing DW_AT_call_return_pc for DW_TAG_call_site "
12196                    "DIE 0x%x [in module %s]"),
12197                  to_underlying (die->sect_off), objfile_name (objfile));
12198       return;
12199     }
12200   pc = attr_value_as_address (attr) + baseaddr;
12201   pc = gdbarch_adjust_dwarf2_addr (gdbarch, pc);
12202
12203   if (cu->call_site_htab == NULL)
12204     cu->call_site_htab = htab_create_alloc_ex (16, core_addr_hash, core_addr_eq,
12205                                                NULL, &objfile->objfile_obstack,
12206                                                hashtab_obstack_allocate, NULL);
12207   call_site_local.pc = pc;
12208   slot = htab_find_slot (cu->call_site_htab, &call_site_local, INSERT);
12209   if (*slot != NULL)
12210     {
12211       complaint (&symfile_complaints,
12212                  _("Duplicate PC %s for DW_TAG_call_site "
12213                    "DIE 0x%x [in module %s]"),
12214                  paddress (gdbarch, pc), to_underlying (die->sect_off),
12215                  objfile_name (objfile));
12216       return;
12217     }
12218
12219   /* Count parameters at the caller.  */
12220
12221   nparams = 0;
12222   for (child_die = die->child; child_die && child_die->tag;
12223        child_die = sibling_die (child_die))
12224     {
12225       if (child_die->tag != DW_TAG_call_site_parameter
12226           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12227         {
12228           complaint (&symfile_complaints,
12229                      _("Tag %d is not DW_TAG_call_site_parameter in "
12230                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12231                      child_die->tag, to_underlying (child_die->sect_off),
12232                      objfile_name (objfile));
12233           continue;
12234         }
12235
12236       nparams++;
12237     }
12238
12239   call_site
12240     = ((struct call_site *)
12241        obstack_alloc (&objfile->objfile_obstack,
12242                       sizeof (*call_site)
12243                       + (sizeof (*call_site->parameter) * (nparams - 1))));
12244   *slot = call_site;
12245   memset (call_site, 0, sizeof (*call_site) - sizeof (*call_site->parameter));
12246   call_site->pc = pc;
12247
12248   if (dwarf2_flag_true_p (die, DW_AT_call_tail_call, cu)
12249       || dwarf2_flag_true_p (die, DW_AT_GNU_tail_call, cu))
12250     {
12251       struct die_info *func_die;
12252
12253       /* Skip also over DW_TAG_inlined_subroutine.  */
12254       for (func_die = die->parent;
12255            func_die && func_die->tag != DW_TAG_subprogram
12256            && func_die->tag != DW_TAG_subroutine_type;
12257            func_die = func_die->parent);
12258
12259       /* DW_AT_call_all_calls is a superset
12260          of DW_AT_call_all_tail_calls.  */
12261       if (func_die
12262           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_calls, cu)
12263           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_call_sites, cu)
12264           && !dwarf2_flag_true_p (func_die, DW_AT_call_all_tail_calls, cu)
12265           && !dwarf2_flag_true_p (func_die, DW_AT_GNU_all_tail_call_sites, cu))
12266         {
12267           /* TYPE_TAIL_CALL_LIST is not interesting in functions where it is
12268              not complete.  But keep CALL_SITE for look ups via call_site_htab,
12269              both the initial caller containing the real return address PC and
12270              the final callee containing the current PC of a chain of tail
12271              calls do not need to have the tail call list complete.  But any
12272              function candidate for a virtual tail call frame searched via
12273              TYPE_TAIL_CALL_LIST must have the tail call list complete to be
12274              determined unambiguously.  */
12275         }
12276       else
12277         {
12278           struct type *func_type = NULL;
12279
12280           if (func_die)
12281             func_type = get_die_type (func_die, cu);
12282           if (func_type != NULL)
12283             {
12284               gdb_assert (TYPE_CODE (func_type) == TYPE_CODE_FUNC);
12285
12286               /* Enlist this call site to the function.  */
12287               call_site->tail_call_next = TYPE_TAIL_CALL_LIST (func_type);
12288               TYPE_TAIL_CALL_LIST (func_type) = call_site;
12289             }
12290           else
12291             complaint (&symfile_complaints,
12292                        _("Cannot find function owning DW_TAG_call_site "
12293                          "DIE 0x%x [in module %s]"),
12294                        to_underlying (die->sect_off), objfile_name (objfile));
12295         }
12296     }
12297
12298   attr = dwarf2_attr (die, DW_AT_call_target, cu);
12299   if (attr == NULL)
12300     attr = dwarf2_attr (die, DW_AT_GNU_call_site_target, cu);
12301   if (attr == NULL)
12302     attr = dwarf2_attr (die, DW_AT_call_origin, cu);
12303   if (attr == NULL)
12304     {
12305       /* This was a pre-DWARF-5 GNU extension alias for DW_AT_call_origin.  */
12306       attr = dwarf2_attr (die, DW_AT_abstract_origin, cu);
12307     }
12308   SET_FIELD_DWARF_BLOCK (call_site->target, NULL);
12309   if (!attr || (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0))
12310     /* Keep NULL DWARF_BLOCK.  */;
12311   else if (attr_form_is_block (attr))
12312     {
12313       struct dwarf2_locexpr_baton *dlbaton;
12314
12315       dlbaton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
12316       dlbaton->data = DW_BLOCK (attr)->data;
12317       dlbaton->size = DW_BLOCK (attr)->size;
12318       dlbaton->per_cu = cu->per_cu;
12319
12320       SET_FIELD_DWARF_BLOCK (call_site->target, dlbaton);
12321     }
12322   else if (attr_form_is_ref (attr))
12323     {
12324       struct dwarf2_cu *target_cu = cu;
12325       struct die_info *target_die;
12326
12327       target_die = follow_die_ref (die, attr, &target_cu);
12328       gdb_assert (target_cu->objfile == objfile);
12329       if (die_is_declaration (target_die, target_cu))
12330         {
12331           const char *target_physname;
12332
12333           /* Prefer the mangled name; otherwise compute the demangled one.  */
12334           target_physname = dw2_linkage_name (target_die, target_cu);
12335           if (target_physname == NULL)
12336             target_physname = dwarf2_physname (NULL, target_die, target_cu);
12337           if (target_physname == NULL)
12338             complaint (&symfile_complaints,
12339                        _("DW_AT_call_target target DIE has invalid "
12340                          "physname, for referencing DIE 0x%x [in module %s]"),
12341                        to_underlying (die->sect_off), objfile_name (objfile));
12342           else
12343             SET_FIELD_PHYSNAME (call_site->target, target_physname);
12344         }
12345       else
12346         {
12347           CORE_ADDR lowpc;
12348
12349           /* DW_AT_entry_pc should be preferred.  */
12350           if (dwarf2_get_pc_bounds (target_die, &lowpc, NULL, target_cu, NULL)
12351               <= PC_BOUNDS_INVALID)
12352             complaint (&symfile_complaints,
12353                        _("DW_AT_call_target target DIE has invalid "
12354                          "low pc, for referencing DIE 0x%x [in module %s]"),
12355                        to_underlying (die->sect_off), objfile_name (objfile));
12356           else
12357             {
12358               lowpc = gdbarch_adjust_dwarf2_addr (gdbarch, lowpc + baseaddr);
12359               SET_FIELD_PHYSADDR (call_site->target, lowpc);
12360             }
12361         }
12362     }
12363   else
12364     complaint (&symfile_complaints,
12365                _("DW_TAG_call_site DW_AT_call_target is neither "
12366                  "block nor reference, for DIE 0x%x [in module %s]"),
12367                to_underlying (die->sect_off), objfile_name (objfile));
12368
12369   call_site->per_cu = cu->per_cu;
12370
12371   for (child_die = die->child;
12372        child_die && child_die->tag;
12373        child_die = sibling_die (child_die))
12374     {
12375       struct call_site_parameter *parameter;
12376       struct attribute *loc, *origin;
12377
12378       if (child_die->tag != DW_TAG_call_site_parameter
12379           && child_die->tag != DW_TAG_GNU_call_site_parameter)
12380         {
12381           /* Already printed the complaint above.  */
12382           continue;
12383         }
12384
12385       gdb_assert (call_site->parameter_count < nparams);
12386       parameter = &call_site->parameter[call_site->parameter_count];
12387
12388       /* DW_AT_location specifies the register number or DW_AT_abstract_origin
12389          specifies DW_TAG_formal_parameter.  Value of the data assumed for the
12390          register is contained in DW_AT_call_value.  */
12391
12392       loc = dwarf2_attr (child_die, DW_AT_location, cu);
12393       origin = dwarf2_attr (child_die, DW_AT_call_parameter, cu);
12394       if (origin == NULL)
12395         {
12396           /* This was a pre-DWARF-5 GNU extension alias
12397              for DW_AT_call_parameter.  */
12398           origin = dwarf2_attr (child_die, DW_AT_abstract_origin, cu);
12399         }
12400       if (loc == NULL && origin != NULL && attr_form_is_ref (origin))
12401         {
12402           parameter->kind = CALL_SITE_PARAMETER_PARAM_OFFSET;
12403
12404           sect_offset sect_off
12405             = (sect_offset) dwarf2_get_ref_die_offset (origin);
12406           if (!offset_in_cu_p (&cu->header, sect_off))
12407             {
12408               /* As DW_OP_GNU_parameter_ref uses CU-relative offset this
12409                  binding can be done only inside one CU.  Such referenced DIE
12410                  therefore cannot be even moved to DW_TAG_partial_unit.  */
12411               complaint (&symfile_complaints,
12412                          _("DW_AT_call_parameter offset is not in CU for "
12413                            "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12414                          to_underlying (child_die->sect_off),
12415                          objfile_name (objfile));
12416               continue;
12417             }
12418           parameter->u.param_cu_off
12419             = (cu_offset) (sect_off - cu->header.sect_off);
12420         }
12421       else if (loc == NULL || origin != NULL || !attr_form_is_block (loc))
12422         {
12423           complaint (&symfile_complaints,
12424                      _("No DW_FORM_block* DW_AT_location for "
12425                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12426                      to_underlying (child_die->sect_off), objfile_name (objfile));
12427           continue;
12428         }
12429       else
12430         {
12431           parameter->u.dwarf_reg = dwarf_block_to_dwarf_reg
12432             (DW_BLOCK (loc)->data, &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size]);
12433           if (parameter->u.dwarf_reg != -1)
12434             parameter->kind = CALL_SITE_PARAMETER_DWARF_REG;
12435           else if (dwarf_block_to_sp_offset (gdbarch, DW_BLOCK (loc)->data,
12436                                     &DW_BLOCK (loc)->data[DW_BLOCK (loc)->size],
12437                                              &parameter->u.fb_offset))
12438             parameter->kind = CALL_SITE_PARAMETER_FB_OFFSET;
12439           else
12440             {
12441               complaint (&symfile_complaints,
12442                          _("Only single DW_OP_reg or DW_OP_fbreg is supported "
12443                            "for DW_FORM_block* DW_AT_location is supported for "
12444                            "DW_TAG_call_site child DIE 0x%x "
12445                            "[in module %s]"),
12446                          to_underlying (child_die->sect_off),
12447                          objfile_name (objfile));
12448               continue;
12449             }
12450         }
12451
12452       attr = dwarf2_attr (child_die, DW_AT_call_value, cu);
12453       if (attr == NULL)
12454         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_value, cu);
12455       if (!attr_form_is_block (attr))
12456         {
12457           complaint (&symfile_complaints,
12458                      _("No DW_FORM_block* DW_AT_call_value for "
12459                        "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12460                      to_underlying (child_die->sect_off),
12461                      objfile_name (objfile));
12462           continue;
12463         }
12464       parameter->value = DW_BLOCK (attr)->data;
12465       parameter->value_size = DW_BLOCK (attr)->size;
12466
12467       /* Parameters are not pre-cleared by memset above.  */
12468       parameter->data_value = NULL;
12469       parameter->data_value_size = 0;
12470       call_site->parameter_count++;
12471
12472       attr = dwarf2_attr (child_die, DW_AT_call_data_value, cu);
12473       if (attr == NULL)
12474         attr = dwarf2_attr (child_die, DW_AT_GNU_call_site_data_value, cu);
12475       if (attr)
12476         {
12477           if (!attr_form_is_block (attr))
12478             complaint (&symfile_complaints,
12479                        _("No DW_FORM_block* DW_AT_call_data_value for "
12480                          "DW_TAG_call_site child DIE 0x%x [in module %s]"),
12481                        to_underlying (child_die->sect_off),
12482                        objfile_name (objfile));
12483           else
12484             {
12485               parameter->data_value = DW_BLOCK (attr)->data;
12486               parameter->data_value_size = DW_BLOCK (attr)->size;
12487             }
12488         }
12489     }
12490 }
12491
12492 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET
12493    reading .debug_rnglists.
12494    Callback's type should be:
12495     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12496    Return true if the attributes are present and valid, otherwise,
12497    return false.  */
12498
12499 template <typename Callback>
12500 static bool
12501 dwarf2_rnglists_process (unsigned offset, struct dwarf2_cu *cu,
12502                          Callback &&callback)
12503 {
12504   struct objfile *objfile = cu->objfile;
12505   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12506   struct comp_unit_head *cu_header = &cu->header;
12507   bfd *obfd = objfile->obfd;
12508   unsigned int addr_size = cu_header->addr_size;
12509   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12510   /* Base address selection entry.  */
12511   CORE_ADDR base;
12512   int found_base;
12513   unsigned int dummy;
12514   const gdb_byte *buffer;
12515   CORE_ADDR low = 0;
12516   CORE_ADDR high = 0;
12517   CORE_ADDR baseaddr;
12518   bool overflow = false;
12519
12520   found_base = cu->base_known;
12521   base = cu->base_address;
12522
12523   dwarf2_read_section (objfile, &dwarf2_per_objfile->rnglists);
12524   if (offset >= dwarf2_per_objfile->rnglists.size)
12525     {
12526       complaint (&symfile_complaints,
12527                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12528                  offset);
12529       return false;
12530     }
12531   buffer = dwarf2_per_objfile->rnglists.buffer + offset;
12532
12533   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12534
12535   while (1)
12536     {
12537       /* Initialize it due to a false compiler warning.  */
12538       CORE_ADDR range_beginning = 0, range_end = 0;
12539       const gdb_byte *buf_end = (dwarf2_per_objfile->rnglists.buffer
12540                                  + dwarf2_per_objfile->rnglists.size);
12541       unsigned int bytes_read;
12542
12543       if (buffer == buf_end)
12544         {
12545           overflow = true;
12546           break;
12547         }
12548       const auto rlet = static_cast<enum dwarf_range_list_entry>(*buffer++);
12549       switch (rlet)
12550         {
12551         case DW_RLE_end_of_list:
12552           break;
12553         case DW_RLE_base_address:
12554           if (buffer + cu->header.addr_size > buf_end)
12555             {
12556               overflow = true;
12557               break;
12558             }
12559           base = read_address (obfd, buffer, cu, &bytes_read);
12560           found_base = 1;
12561           buffer += bytes_read;
12562           break;
12563         case DW_RLE_start_length:
12564           if (buffer + cu->header.addr_size > buf_end)
12565             {
12566               overflow = true;
12567               break;
12568             }
12569           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12570           buffer += bytes_read;
12571           range_end = (range_beginning
12572                        + read_unsigned_leb128 (obfd, buffer, &bytes_read));
12573           buffer += bytes_read;
12574           if (buffer > buf_end)
12575             {
12576               overflow = true;
12577               break;
12578             }
12579           break;
12580         case DW_RLE_offset_pair:
12581           range_beginning = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12582           buffer += bytes_read;
12583           if (buffer > buf_end)
12584             {
12585               overflow = true;
12586               break;
12587             }
12588           range_end = read_unsigned_leb128 (obfd, buffer, &bytes_read);
12589           buffer += bytes_read;
12590           if (buffer > buf_end)
12591             {
12592               overflow = true;
12593               break;
12594             }
12595           break;
12596         case DW_RLE_start_end:
12597           if (buffer + 2 * cu->header.addr_size > buf_end)
12598             {
12599               overflow = true;
12600               break;
12601             }
12602           range_beginning = read_address (obfd, buffer, cu, &bytes_read);
12603           buffer += bytes_read;
12604           range_end = read_address (obfd, buffer, cu, &bytes_read);
12605           buffer += bytes_read;
12606           break;
12607         default:
12608           complaint (&symfile_complaints,
12609                      _("Invalid .debug_rnglists data (no base address)"));
12610           return false;
12611         }
12612       if (rlet == DW_RLE_end_of_list || overflow)
12613         break;
12614       if (rlet == DW_RLE_base_address)
12615         continue;
12616
12617       if (!found_base)
12618         {
12619           /* We have no valid base address for the ranges
12620              data.  */
12621           complaint (&symfile_complaints,
12622                      _("Invalid .debug_rnglists data (no base address)"));
12623           return false;
12624         }
12625
12626       if (range_beginning > range_end)
12627         {
12628           /* Inverted range entries are invalid.  */
12629           complaint (&symfile_complaints,
12630                      _("Invalid .debug_rnglists data (inverted range)"));
12631           return false;
12632         }
12633
12634       /* Empty range entries have no effect.  */
12635       if (range_beginning == range_end)
12636         continue;
12637
12638       range_beginning += base;
12639       range_end += base;
12640
12641       /* A not-uncommon case of bad debug info.
12642          Don't pollute the addrmap with bad data.  */
12643       if (range_beginning + baseaddr == 0
12644           && !dwarf2_per_objfile->has_section_at_zero)
12645         {
12646           complaint (&symfile_complaints,
12647                      _(".debug_rnglists entry has start address of zero"
12648                        " [in module %s]"), objfile_name (objfile));
12649           continue;
12650         }
12651
12652       callback (range_beginning, range_end);
12653     }
12654
12655   if (overflow)
12656     {
12657       complaint (&symfile_complaints,
12658                  _("Offset %d is not terminated "
12659                    "for DW_AT_ranges attribute"),
12660                  offset);
12661       return false;
12662     }
12663
12664   return true;
12665 }
12666
12667 /* Call CALLBACK from DW_AT_ranges attribute value OFFSET reading .debug_ranges.
12668    Callback's type should be:
12669     void (CORE_ADDR range_beginning, CORE_ADDR range_end)
12670    Return 1 if the attributes are present and valid, otherwise, return 0.  */
12671
12672 template <typename Callback>
12673 static int
12674 dwarf2_ranges_process (unsigned offset, struct dwarf2_cu *cu,
12675                        Callback &&callback)
12676 {
12677   struct objfile *objfile = cu->objfile;
12678   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12679   struct comp_unit_head *cu_header = &cu->header;
12680   bfd *obfd = objfile->obfd;
12681   unsigned int addr_size = cu_header->addr_size;
12682   CORE_ADDR mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
12683   /* Base address selection entry.  */
12684   CORE_ADDR base;
12685   int found_base;
12686   unsigned int dummy;
12687   const gdb_byte *buffer;
12688   CORE_ADDR baseaddr;
12689
12690   if (cu_header->version >= 5)
12691     return dwarf2_rnglists_process (offset, cu, callback);
12692
12693   found_base = cu->base_known;
12694   base = cu->base_address;
12695
12696   dwarf2_read_section (objfile, &dwarf2_per_objfile->ranges);
12697   if (offset >= dwarf2_per_objfile->ranges.size)
12698     {
12699       complaint (&symfile_complaints,
12700                  _("Offset %d out of bounds for DW_AT_ranges attribute"),
12701                  offset);
12702       return 0;
12703     }
12704   buffer = dwarf2_per_objfile->ranges.buffer + offset;
12705
12706   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
12707
12708   while (1)
12709     {
12710       CORE_ADDR range_beginning, range_end;
12711
12712       range_beginning = read_address (obfd, buffer, cu, &dummy);
12713       buffer += addr_size;
12714       range_end = read_address (obfd, buffer, cu, &dummy);
12715       buffer += addr_size;
12716       offset += 2 * addr_size;
12717
12718       /* An end of list marker is a pair of zero addresses.  */
12719       if (range_beginning == 0 && range_end == 0)
12720         /* Found the end of list entry.  */
12721         break;
12722
12723       /* Each base address selection entry is a pair of 2 values.
12724          The first is the largest possible address, the second is
12725          the base address.  Check for a base address here.  */
12726       if ((range_beginning & mask) == mask)
12727         {
12728           /* If we found the largest possible address, then we already
12729              have the base address in range_end.  */
12730           base = range_end;
12731           found_base = 1;
12732           continue;
12733         }
12734
12735       if (!found_base)
12736         {
12737           /* We have no valid base address for the ranges
12738              data.  */
12739           complaint (&symfile_complaints,
12740                      _("Invalid .debug_ranges data (no base address)"));
12741           return 0;
12742         }
12743
12744       if (range_beginning > range_end)
12745         {
12746           /* Inverted range entries are invalid.  */
12747           complaint (&symfile_complaints,
12748                      _("Invalid .debug_ranges data (inverted range)"));
12749           return 0;
12750         }
12751
12752       /* Empty range entries have no effect.  */
12753       if (range_beginning == range_end)
12754         continue;
12755
12756       range_beginning += base;
12757       range_end += base;
12758
12759       /* A not-uncommon case of bad debug info.
12760          Don't pollute the addrmap with bad data.  */
12761       if (range_beginning + baseaddr == 0
12762           && !dwarf2_per_objfile->has_section_at_zero)
12763         {
12764           complaint (&symfile_complaints,
12765                      _(".debug_ranges entry has start address of zero"
12766                        " [in module %s]"), objfile_name (objfile));
12767           continue;
12768         }
12769
12770       callback (range_beginning, range_end);
12771     }
12772
12773   return 1;
12774 }
12775
12776 /* Get low and high pc attributes from DW_AT_ranges attribute value OFFSET.
12777    Return 1 if the attributes are present and valid, otherwise, return 0.
12778    If RANGES_PST is not NULL we should setup `objfile->psymtabs_addrmap'.  */
12779
12780 static int
12781 dwarf2_ranges_read (unsigned offset, CORE_ADDR *low_return,
12782                     CORE_ADDR *high_return, struct dwarf2_cu *cu,
12783                     struct partial_symtab *ranges_pst)
12784 {
12785   struct objfile *objfile = cu->objfile;
12786   struct gdbarch *gdbarch = get_objfile_arch (objfile);
12787   const CORE_ADDR baseaddr = ANOFFSET (objfile->section_offsets,
12788                                        SECT_OFF_TEXT (objfile));
12789   int low_set = 0;
12790   CORE_ADDR low = 0;
12791   CORE_ADDR high = 0;
12792   int retval;
12793
12794   retval = dwarf2_ranges_process (offset, cu,
12795     [&] (CORE_ADDR range_beginning, CORE_ADDR range_end)
12796     {
12797       if (ranges_pst != NULL)
12798         {
12799           CORE_ADDR lowpc;
12800           CORE_ADDR highpc;
12801
12802           lowpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12803                                               range_beginning + baseaddr);
12804           highpc = gdbarch_adjust_dwarf2_addr (gdbarch,
12805                                                range_end + baseaddr);
12806           addrmap_set_empty (objfile->psymtabs_addrmap, lowpc, highpc - 1,
12807                              ranges_pst);
12808         }
12809
12810       /* FIXME: This is recording everything as a low-high
12811          segment of consecutive addresses.  We should have a
12812          data structure for discontiguous block ranges
12813          instead.  */
12814       if (! low_set)
12815         {
12816           low = range_beginning;
12817           high = range_end;
12818           low_set = 1;
12819         }
12820       else
12821         {
12822           if (range_beginning < low)
12823             low = range_beginning;
12824           if (range_end > high)
12825             high = range_end;
12826         }
12827     });
12828   if (!retval)
12829     return 0;
12830
12831   if (! low_set)
12832     /* If the first entry is an end-of-list marker, the range
12833        describes an empty scope, i.e. no instructions.  */
12834     return 0;
12835
12836   if (low_return)
12837     *low_return = low;
12838   if (high_return)
12839     *high_return = high;
12840   return 1;
12841 }
12842
12843 /* Get low and high pc attributes from a die.  See enum pc_bounds_kind
12844    definition for the return value.  *LOWPC and *HIGHPC are set iff
12845    neither PC_BOUNDS_NOT_PRESENT nor PC_BOUNDS_INVALID are returned.  */
12846
12847 static enum pc_bounds_kind
12848 dwarf2_get_pc_bounds (struct die_info *die, CORE_ADDR *lowpc,
12849                       CORE_ADDR *highpc, struct dwarf2_cu *cu,
12850                       struct partial_symtab *pst)
12851 {
12852   struct attribute *attr;
12853   struct attribute *attr_high;
12854   CORE_ADDR low = 0;
12855   CORE_ADDR high = 0;
12856   enum pc_bounds_kind ret;
12857
12858   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
12859   if (attr_high)
12860     {
12861       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
12862       if (attr)
12863         {
12864           low = attr_value_as_address (attr);
12865           high = attr_value_as_address (attr_high);
12866           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
12867             high += low;
12868         }
12869       else
12870         /* Found high w/o low attribute.  */
12871         return PC_BOUNDS_INVALID;
12872
12873       /* Found consecutive range of addresses.  */
12874       ret = PC_BOUNDS_HIGH_LOW;
12875     }
12876   else
12877     {
12878       attr = dwarf2_attr (die, DW_AT_ranges, cu);
12879       if (attr != NULL)
12880         {
12881           /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
12882              We take advantage of the fact that DW_AT_ranges does not appear
12883              in DW_TAG_compile_unit of DWO files.  */
12884           int need_ranges_base = die->tag != DW_TAG_compile_unit;
12885           unsigned int ranges_offset = (DW_UNSND (attr)
12886                                         + (need_ranges_base
12887                                            ? cu->ranges_base
12888                                            : 0));
12889
12890           /* Value of the DW_AT_ranges attribute is the offset in the
12891              .debug_ranges section.  */
12892           if (!dwarf2_ranges_read (ranges_offset, &low, &high, cu, pst))
12893             return PC_BOUNDS_INVALID;
12894           /* Found discontinuous range of addresses.  */
12895           ret = PC_BOUNDS_RANGES;
12896         }
12897       else
12898         return PC_BOUNDS_NOT_PRESENT;
12899     }
12900
12901   /* read_partial_die has also the strict LOW < HIGH requirement.  */
12902   if (high <= low)
12903     return PC_BOUNDS_INVALID;
12904
12905   /* When using the GNU linker, .gnu.linkonce. sections are used to
12906      eliminate duplicate copies of functions and vtables and such.
12907      The linker will arbitrarily choose one and discard the others.
12908      The AT_*_pc values for such functions refer to local labels in
12909      these sections.  If the section from that file was discarded, the
12910      labels are not in the output, so the relocs get a value of 0.
12911      If this is a discarded function, mark the pc bounds as invalid,
12912      so that GDB will ignore it.  */
12913   if (low == 0 && !dwarf2_per_objfile->has_section_at_zero)
12914     return PC_BOUNDS_INVALID;
12915
12916   *lowpc = low;
12917   if (highpc)
12918     *highpc = high;
12919   return ret;
12920 }
12921
12922 /* Assuming that DIE represents a subprogram DIE or a lexical block, get
12923    its low and high PC addresses.  Do nothing if these addresses could not
12924    be determined.  Otherwise, set LOWPC to the low address if it is smaller,
12925    and HIGHPC to the high address if greater than HIGHPC.  */
12926
12927 static void
12928 dwarf2_get_subprogram_pc_bounds (struct die_info *die,
12929                                  CORE_ADDR *lowpc, CORE_ADDR *highpc,
12930                                  struct dwarf2_cu *cu)
12931 {
12932   CORE_ADDR low, high;
12933   struct die_info *child = die->child;
12934
12935   if (dwarf2_get_pc_bounds (die, &low, &high, cu, NULL) >= PC_BOUNDS_RANGES)
12936     {
12937       *lowpc = std::min (*lowpc, low);
12938       *highpc = std::max (*highpc, high);
12939     }
12940
12941   /* If the language does not allow nested subprograms (either inside
12942      subprograms or lexical blocks), we're done.  */
12943   if (cu->language != language_ada)
12944     return;
12945
12946   /* Check all the children of the given DIE.  If it contains nested
12947      subprograms, then check their pc bounds.  Likewise, we need to
12948      check lexical blocks as well, as they may also contain subprogram
12949      definitions.  */
12950   while (child && child->tag)
12951     {
12952       if (child->tag == DW_TAG_subprogram
12953           || child->tag == DW_TAG_lexical_block)
12954         dwarf2_get_subprogram_pc_bounds (child, lowpc, highpc, cu);
12955       child = sibling_die (child);
12956     }
12957 }
12958
12959 /* Get the low and high pc's represented by the scope DIE, and store
12960    them in *LOWPC and *HIGHPC.  If the correct values can't be
12961    determined, set *LOWPC to -1 and *HIGHPC to 0.  */
12962
12963 static void
12964 get_scope_pc_bounds (struct die_info *die,
12965                      CORE_ADDR *lowpc, CORE_ADDR *highpc,
12966                      struct dwarf2_cu *cu)
12967 {
12968   CORE_ADDR best_low = (CORE_ADDR) -1;
12969   CORE_ADDR best_high = (CORE_ADDR) 0;
12970   CORE_ADDR current_low, current_high;
12971
12972   if (dwarf2_get_pc_bounds (die, &current_low, &current_high, cu, NULL)
12973       >= PC_BOUNDS_RANGES)
12974     {
12975       best_low = current_low;
12976       best_high = current_high;
12977     }
12978   else
12979     {
12980       struct die_info *child = die->child;
12981
12982       while (child && child->tag)
12983         {
12984           switch (child->tag) {
12985           case DW_TAG_subprogram:
12986             dwarf2_get_subprogram_pc_bounds (child, &best_low, &best_high, cu);
12987             break;
12988           case DW_TAG_namespace:
12989           case DW_TAG_module:
12990             /* FIXME: carlton/2004-01-16: Should we do this for
12991                DW_TAG_class_type/DW_TAG_structure_type, too?  I think
12992                that current GCC's always emit the DIEs corresponding
12993                to definitions of methods of classes as children of a
12994                DW_TAG_compile_unit or DW_TAG_namespace (as opposed to
12995                the DIEs giving the declarations, which could be
12996                anywhere).  But I don't see any reason why the
12997                standards says that they have to be there.  */
12998             get_scope_pc_bounds (child, &current_low, &current_high, cu);
12999
13000             if (current_low != ((CORE_ADDR) -1))
13001               {
13002                 best_low = std::min (best_low, current_low);
13003                 best_high = std::max (best_high, current_high);
13004               }
13005             break;
13006           default:
13007             /* Ignore.  */
13008             break;
13009           }
13010
13011           child = sibling_die (child);
13012         }
13013     }
13014
13015   *lowpc = best_low;
13016   *highpc = best_high;
13017 }
13018
13019 /* Record the address ranges for BLOCK, offset by BASEADDR, as given
13020    in DIE.  */
13021
13022 static void
13023 dwarf2_record_block_ranges (struct die_info *die, struct block *block,
13024                             CORE_ADDR baseaddr, struct dwarf2_cu *cu)
13025 {
13026   struct objfile *objfile = cu->objfile;
13027   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13028   struct attribute *attr;
13029   struct attribute *attr_high;
13030
13031   attr_high = dwarf2_attr (die, DW_AT_high_pc, cu);
13032   if (attr_high)
13033     {
13034       attr = dwarf2_attr (die, DW_AT_low_pc, cu);
13035       if (attr)
13036         {
13037           CORE_ADDR low = attr_value_as_address (attr);
13038           CORE_ADDR high = attr_value_as_address (attr_high);
13039
13040           if (cu->header.version >= 4 && attr_form_is_constant (attr_high))
13041             high += low;
13042
13043           low = gdbarch_adjust_dwarf2_addr (gdbarch, low + baseaddr);
13044           high = gdbarch_adjust_dwarf2_addr (gdbarch, high + baseaddr);
13045           record_block_range (block, low, high - 1);
13046         }
13047     }
13048
13049   attr = dwarf2_attr (die, DW_AT_ranges, cu);
13050   if (attr)
13051     {
13052       bfd *obfd = objfile->obfd;
13053       /* DW_AT_ranges_base does not apply to DIEs from the DWO skeleton.
13054          We take advantage of the fact that DW_AT_ranges does not appear
13055          in DW_TAG_compile_unit of DWO files.  */
13056       int need_ranges_base = die->tag != DW_TAG_compile_unit;
13057
13058       /* The value of the DW_AT_ranges attribute is the offset of the
13059          address range list in the .debug_ranges section.  */
13060       unsigned long offset = (DW_UNSND (attr)
13061                               + (need_ranges_base ? cu->ranges_base : 0));
13062       const gdb_byte *buffer;
13063
13064       /* For some target architectures, but not others, the
13065          read_address function sign-extends the addresses it returns.
13066          To recognize base address selection entries, we need a
13067          mask.  */
13068       unsigned int addr_size = cu->header.addr_size;
13069       CORE_ADDR base_select_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1));
13070
13071       /* The base address, to which the next pair is relative.  Note
13072          that this 'base' is a DWARF concept: most entries in a range
13073          list are relative, to reduce the number of relocs against the
13074          debugging information.  This is separate from this function's
13075          'baseaddr' argument, which GDB uses to relocate debugging
13076          information from a shared library based on the address at
13077          which the library was loaded.  */
13078       CORE_ADDR base = cu->base_address;
13079       int base_known = cu->base_known;
13080
13081       dwarf2_ranges_process (offset, cu,
13082         [&] (CORE_ADDR start, CORE_ADDR end)
13083         {
13084           start += baseaddr;
13085           end += baseaddr;
13086           start = gdbarch_adjust_dwarf2_addr (gdbarch, start);
13087           end = gdbarch_adjust_dwarf2_addr (gdbarch, end);
13088           record_block_range (block, start, end - 1);
13089         });
13090     }
13091 }
13092
13093 /* Check whether the producer field indicates either of GCC < 4.6, or the
13094    Intel C/C++ compiler, and cache the result in CU.  */
13095
13096 static void
13097 check_producer (struct dwarf2_cu *cu)
13098 {
13099   int major, minor;
13100
13101   if (cu->producer == NULL)
13102     {
13103       /* For unknown compilers expect their behavior is DWARF version
13104          compliant.
13105
13106          GCC started to support .debug_types sections by -gdwarf-4 since
13107          gcc-4.5.x.  As the .debug_types sections are missing DW_AT_producer
13108          for their space efficiency GDB cannot workaround gcc-4.5.x -gdwarf-4
13109          combination.  gcc-4.5.x -gdwarf-4 binaries have DW_AT_accessibility
13110          interpreted incorrectly by GDB now - GCC PR debug/48229.  */
13111     }
13112   else if (producer_is_gcc (cu->producer, &major, &minor))
13113     {
13114       cu->producer_is_gxx_lt_4_6 = major < 4 || (major == 4 && minor < 6);
13115       cu->producer_is_gcc_lt_4_3 = major < 4 || (major == 4 && minor < 3);
13116     }
13117   else if (producer_is_icc (cu->producer, &major, &minor))
13118     cu->producer_is_icc_lt_14 = major < 14;
13119   else
13120     {
13121       /* For other non-GCC compilers, expect their behavior is DWARF version
13122          compliant.  */
13123     }
13124
13125   cu->checked_producer = 1;
13126 }
13127
13128 /* Check for GCC PR debug/45124 fix which is not present in any G++ version up
13129    to 4.5.any while it is present already in G++ 4.6.0 - the PR has been fixed
13130    during 4.6.0 experimental.  */
13131
13132 static int
13133 producer_is_gxx_lt_4_6 (struct dwarf2_cu *cu)
13134 {
13135   if (!cu->checked_producer)
13136     check_producer (cu);
13137
13138   return cu->producer_is_gxx_lt_4_6;
13139 }
13140
13141 /* Return the default accessibility type if it is not overriden by
13142    DW_AT_accessibility.  */
13143
13144 static enum dwarf_access_attribute
13145 dwarf2_default_access_attribute (struct die_info *die, struct dwarf2_cu *cu)
13146 {
13147   if (cu->header.version < 3 || producer_is_gxx_lt_4_6 (cu))
13148     {
13149       /* The default DWARF 2 accessibility for members is public, the default
13150          accessibility for inheritance is private.  */
13151
13152       if (die->tag != DW_TAG_inheritance)
13153         return DW_ACCESS_public;
13154       else
13155         return DW_ACCESS_private;
13156     }
13157   else
13158     {
13159       /* DWARF 3+ defines the default accessibility a different way.  The same
13160          rules apply now for DW_TAG_inheritance as for the members and it only
13161          depends on the container kind.  */
13162
13163       if (die->parent->tag == DW_TAG_class_type)
13164         return DW_ACCESS_private;
13165       else
13166         return DW_ACCESS_public;
13167     }
13168 }
13169
13170 /* Look for DW_AT_data_member_location.  Set *OFFSET to the byte
13171    offset.  If the attribute was not found return 0, otherwise return
13172    1.  If it was found but could not properly be handled, set *OFFSET
13173    to 0.  */
13174
13175 static int
13176 handle_data_member_location (struct die_info *die, struct dwarf2_cu *cu,
13177                              LONGEST *offset)
13178 {
13179   struct attribute *attr;
13180
13181   attr = dwarf2_attr (die, DW_AT_data_member_location, cu);
13182   if (attr != NULL)
13183     {
13184       *offset = 0;
13185
13186       /* Note that we do not check for a section offset first here.
13187          This is because DW_AT_data_member_location is new in DWARF 4,
13188          so if we see it, we can assume that a constant form is really
13189          a constant and not a section offset.  */
13190       if (attr_form_is_constant (attr))
13191         *offset = dwarf2_get_attr_constant_value (attr, 0);
13192       else if (attr_form_is_section_offset (attr))
13193         dwarf2_complex_location_expr_complaint ();
13194       else if (attr_form_is_block (attr))
13195         *offset = decode_locdesc (DW_BLOCK (attr), cu);
13196       else
13197         dwarf2_complex_location_expr_complaint ();
13198
13199       return 1;
13200     }
13201
13202   return 0;
13203 }
13204
13205 /* Add an aggregate field to the field list.  */
13206
13207 static void
13208 dwarf2_add_field (struct field_info *fip, struct die_info *die,
13209                   struct dwarf2_cu *cu)
13210 {
13211   struct objfile *objfile = cu->objfile;
13212   struct gdbarch *gdbarch = get_objfile_arch (objfile);
13213   struct nextfield *new_field;
13214   struct attribute *attr;
13215   struct field *fp;
13216   const char *fieldname = "";
13217
13218   /* Allocate a new field list entry and link it in.  */
13219   new_field = XNEW (struct nextfield);
13220   make_cleanup (xfree, new_field);
13221   memset (new_field, 0, sizeof (struct nextfield));
13222
13223   if (die->tag == DW_TAG_inheritance)
13224     {
13225       new_field->next = fip->baseclasses;
13226       fip->baseclasses = new_field;
13227     }
13228   else
13229     {
13230       new_field->next = fip->fields;
13231       fip->fields = new_field;
13232     }
13233   fip->nfields++;
13234
13235   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13236   if (attr)
13237     new_field->accessibility = DW_UNSND (attr);
13238   else
13239     new_field->accessibility = dwarf2_default_access_attribute (die, cu);
13240   if (new_field->accessibility != DW_ACCESS_public)
13241     fip->non_public_fields = 1;
13242
13243   attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13244   if (attr)
13245     new_field->virtuality = DW_UNSND (attr);
13246   else
13247     new_field->virtuality = DW_VIRTUALITY_none;
13248
13249   fp = &new_field->field;
13250
13251   if (die->tag == DW_TAG_member && ! die_is_declaration (die, cu))
13252     {
13253       LONGEST offset;
13254
13255       /* Data member other than a C++ static data member.  */
13256
13257       /* Get type of field.  */
13258       fp->type = die_type (die, cu);
13259
13260       SET_FIELD_BITPOS (*fp, 0);
13261
13262       /* Get bit size of field (zero if none).  */
13263       attr = dwarf2_attr (die, DW_AT_bit_size, cu);
13264       if (attr)
13265         {
13266           FIELD_BITSIZE (*fp) = DW_UNSND (attr);
13267         }
13268       else
13269         {
13270           FIELD_BITSIZE (*fp) = 0;
13271         }
13272
13273       /* Get bit offset of field.  */
13274       if (handle_data_member_location (die, cu, &offset))
13275         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13276       attr = dwarf2_attr (die, DW_AT_bit_offset, cu);
13277       if (attr)
13278         {
13279           if (gdbarch_bits_big_endian (gdbarch))
13280             {
13281               /* For big endian bits, the DW_AT_bit_offset gives the
13282                  additional bit offset from the MSB of the containing
13283                  anonymous object to the MSB of the field.  We don't
13284                  have to do anything special since we don't need to
13285                  know the size of the anonymous object.  */
13286               SET_FIELD_BITPOS (*fp, FIELD_BITPOS (*fp) + DW_UNSND (attr));
13287             }
13288           else
13289             {
13290               /* For little endian bits, compute the bit offset to the
13291                  MSB of the anonymous object, subtract off the number of
13292                  bits from the MSB of the field to the MSB of the
13293                  object, and then subtract off the number of bits of
13294                  the field itself.  The result is the bit offset of
13295                  the LSB of the field.  */
13296               int anonymous_size;
13297               int bit_offset = DW_UNSND (attr);
13298
13299               attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13300               if (attr)
13301                 {
13302                   /* The size of the anonymous object containing
13303                      the bit field is explicit, so use the
13304                      indicated size (in bytes).  */
13305                   anonymous_size = DW_UNSND (attr);
13306                 }
13307               else
13308                 {
13309                   /* The size of the anonymous object containing
13310                      the bit field must be inferred from the type
13311                      attribute of the data member containing the
13312                      bit field.  */
13313                   anonymous_size = TYPE_LENGTH (fp->type);
13314                 }
13315               SET_FIELD_BITPOS (*fp,
13316                                 (FIELD_BITPOS (*fp)
13317                                  + anonymous_size * bits_per_byte
13318                                  - bit_offset - FIELD_BITSIZE (*fp)));
13319             }
13320         }
13321       attr = dwarf2_attr (die, DW_AT_data_bit_offset, cu);
13322       if (attr != NULL)
13323         SET_FIELD_BITPOS (*fp, (FIELD_BITPOS (*fp)
13324                                 + dwarf2_get_attr_constant_value (attr, 0)));
13325
13326       /* Get name of field.  */
13327       fieldname = dwarf2_name (die, cu);
13328       if (fieldname == NULL)
13329         fieldname = "";
13330
13331       /* The name is already allocated along with this objfile, so we don't
13332          need to duplicate it for the type.  */
13333       fp->name = fieldname;
13334
13335       /* Change accessibility for artificial fields (e.g. virtual table
13336          pointer or virtual base class pointer) to private.  */
13337       if (dwarf2_attr (die, DW_AT_artificial, cu))
13338         {
13339           FIELD_ARTIFICIAL (*fp) = 1;
13340           new_field->accessibility = DW_ACCESS_private;
13341           fip->non_public_fields = 1;
13342         }
13343     }
13344   else if (die->tag == DW_TAG_member || die->tag == DW_TAG_variable)
13345     {
13346       /* C++ static member.  */
13347
13348       /* NOTE: carlton/2002-11-05: It should be a DW_TAG_member that
13349          is a declaration, but all versions of G++ as of this writing
13350          (so through at least 3.2.1) incorrectly generate
13351          DW_TAG_variable tags.  */
13352
13353       const char *physname;
13354
13355       /* Get name of field.  */
13356       fieldname = dwarf2_name (die, cu);
13357       if (fieldname == NULL)
13358         return;
13359
13360       attr = dwarf2_attr (die, DW_AT_const_value, cu);
13361       if (attr
13362           /* Only create a symbol if this is an external value.
13363              new_symbol checks this and puts the value in the global symbol
13364              table, which we want.  If it is not external, new_symbol
13365              will try to put the value in cu->list_in_scope which is wrong.  */
13366           && dwarf2_flag_true_p (die, DW_AT_external, cu))
13367         {
13368           /* A static const member, not much different than an enum as far as
13369              we're concerned, except that we can support more types.  */
13370           new_symbol (die, NULL, cu);
13371         }
13372
13373       /* Get physical name.  */
13374       physname = dwarf2_physname (fieldname, die, cu);
13375
13376       /* The name is already allocated along with this objfile, so we don't
13377          need to duplicate it for the type.  */
13378       SET_FIELD_PHYSNAME (*fp, physname ? physname : "");
13379       FIELD_TYPE (*fp) = die_type (die, cu);
13380       FIELD_NAME (*fp) = fieldname;
13381     }
13382   else if (die->tag == DW_TAG_inheritance)
13383     {
13384       LONGEST offset;
13385
13386       /* C++ base class field.  */
13387       if (handle_data_member_location (die, cu, &offset))
13388         SET_FIELD_BITPOS (*fp, offset * bits_per_byte);
13389       FIELD_BITSIZE (*fp) = 0;
13390       FIELD_TYPE (*fp) = die_type (die, cu);
13391       FIELD_NAME (*fp) = type_name_no_tag (fp->type);
13392       fip->nbaseclasses++;
13393     }
13394 }
13395
13396 /* Add a typedef defined in the scope of the FIP's class.  */
13397
13398 static void
13399 dwarf2_add_typedef (struct field_info *fip, struct die_info *die,
13400                     struct dwarf2_cu *cu)
13401 {
13402   struct typedef_field_list *new_field;
13403   struct typedef_field *fp;
13404
13405   /* Allocate a new field list entry and link it in.  */
13406   new_field = XCNEW (struct typedef_field_list);
13407   make_cleanup (xfree, new_field);
13408
13409   gdb_assert (die->tag == DW_TAG_typedef);
13410
13411   fp = &new_field->field;
13412
13413   /* Get name of field.  */
13414   fp->name = dwarf2_name (die, cu);
13415   if (fp->name == NULL)
13416     return;
13417
13418   fp->type = read_type_die (die, cu);
13419
13420   /* Save accessibility.  */
13421   enum dwarf_access_attribute accessibility;
13422   struct attribute *attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13423   if (attr != NULL)
13424     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13425   else
13426     accessibility = dwarf2_default_access_attribute (die, cu);
13427   switch (accessibility)
13428     {
13429     case DW_ACCESS_public:
13430       /* The assumed value if neither private nor protected.  */
13431       break;
13432     case DW_ACCESS_private:
13433       fp->is_private = 1;
13434       break;
13435     case DW_ACCESS_protected:
13436       fp->is_protected = 1;
13437       break;
13438     default:
13439       complaint (&symfile_complaints,
13440                  _("Unhandled DW_AT_accessibility value (%x)"), accessibility);
13441     }
13442
13443   new_field->next = fip->typedef_field_list;
13444   fip->typedef_field_list = new_field;
13445   fip->typedef_field_list_count++;
13446 }
13447
13448 /* Create the vector of fields, and attach it to the type.  */
13449
13450 static void
13451 dwarf2_attach_fields_to_type (struct field_info *fip, struct type *type,
13452                               struct dwarf2_cu *cu)
13453 {
13454   int nfields = fip->nfields;
13455
13456   /* Record the field count, allocate space for the array of fields,
13457      and create blank accessibility bitfields if necessary.  */
13458   TYPE_NFIELDS (type) = nfields;
13459   TYPE_FIELDS (type) = (struct field *)
13460     TYPE_ALLOC (type, sizeof (struct field) * nfields);
13461   memset (TYPE_FIELDS (type), 0, sizeof (struct field) * nfields);
13462
13463   if (fip->non_public_fields && cu->language != language_ada)
13464     {
13465       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13466
13467       TYPE_FIELD_PRIVATE_BITS (type) =
13468         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13469       B_CLRALL (TYPE_FIELD_PRIVATE_BITS (type), nfields);
13470
13471       TYPE_FIELD_PROTECTED_BITS (type) =
13472         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13473       B_CLRALL (TYPE_FIELD_PROTECTED_BITS (type), nfields);
13474
13475       TYPE_FIELD_IGNORE_BITS (type) =
13476         (B_TYPE *) TYPE_ALLOC (type, B_BYTES (nfields));
13477       B_CLRALL (TYPE_FIELD_IGNORE_BITS (type), nfields);
13478     }
13479
13480   /* If the type has baseclasses, allocate and clear a bit vector for
13481      TYPE_FIELD_VIRTUAL_BITS.  */
13482   if (fip->nbaseclasses && cu->language != language_ada)
13483     {
13484       int num_bytes = B_BYTES (fip->nbaseclasses);
13485       unsigned char *pointer;
13486
13487       ALLOCATE_CPLUS_STRUCT_TYPE (type);
13488       pointer = (unsigned char *) TYPE_ALLOC (type, num_bytes);
13489       TYPE_FIELD_VIRTUAL_BITS (type) = pointer;
13490       B_CLRALL (TYPE_FIELD_VIRTUAL_BITS (type), fip->nbaseclasses);
13491       TYPE_N_BASECLASSES (type) = fip->nbaseclasses;
13492     }
13493
13494   /* Copy the saved-up fields into the field vector.  Start from the head of
13495      the list, adding to the tail of the field array, so that they end up in
13496      the same order in the array in which they were added to the list.  */
13497   while (nfields-- > 0)
13498     {
13499       struct nextfield *fieldp;
13500
13501       if (fip->fields)
13502         {
13503           fieldp = fip->fields;
13504           fip->fields = fieldp->next;
13505         }
13506       else
13507         {
13508           fieldp = fip->baseclasses;
13509           fip->baseclasses = fieldp->next;
13510         }
13511
13512       TYPE_FIELD (type, nfields) = fieldp->field;
13513       switch (fieldp->accessibility)
13514         {
13515         case DW_ACCESS_private:
13516           if (cu->language != language_ada)
13517             SET_TYPE_FIELD_PRIVATE (type, nfields);
13518           break;
13519
13520         case DW_ACCESS_protected:
13521           if (cu->language != language_ada)
13522             SET_TYPE_FIELD_PROTECTED (type, nfields);
13523           break;
13524
13525         case DW_ACCESS_public:
13526           break;
13527
13528         default:
13529           /* Unknown accessibility.  Complain and treat it as public.  */
13530           {
13531             complaint (&symfile_complaints, _("unsupported accessibility %d"),
13532                        fieldp->accessibility);
13533           }
13534           break;
13535         }
13536       if (nfields < fip->nbaseclasses)
13537         {
13538           switch (fieldp->virtuality)
13539             {
13540             case DW_VIRTUALITY_virtual:
13541             case DW_VIRTUALITY_pure_virtual:
13542               if (cu->language == language_ada)
13543                 error (_("unexpected virtuality in component of Ada type"));
13544               SET_TYPE_FIELD_VIRTUAL (type, nfields);
13545               break;
13546             }
13547         }
13548     }
13549 }
13550
13551 /* Return true if this member function is a constructor, false
13552    otherwise.  */
13553
13554 static int
13555 dwarf2_is_constructor (struct die_info *die, struct dwarf2_cu *cu)
13556 {
13557   const char *fieldname;
13558   const char *type_name;
13559   int len;
13560
13561   if (die->parent == NULL)
13562     return 0;
13563
13564   if (die->parent->tag != DW_TAG_structure_type
13565       && die->parent->tag != DW_TAG_union_type
13566       && die->parent->tag != DW_TAG_class_type)
13567     return 0;
13568
13569   fieldname = dwarf2_name (die, cu);
13570   type_name = dwarf2_name (die->parent, cu);
13571   if (fieldname == NULL || type_name == NULL)
13572     return 0;
13573
13574   len = strlen (fieldname);
13575   return (strncmp (fieldname, type_name, len) == 0
13576           && (type_name[len] == '\0' || type_name[len] == '<'));
13577 }
13578
13579 /* Add a member function to the proper fieldlist.  */
13580
13581 static void
13582 dwarf2_add_member_fn (struct field_info *fip, struct die_info *die,
13583                       struct type *type, struct dwarf2_cu *cu)
13584 {
13585   struct objfile *objfile = cu->objfile;
13586   struct attribute *attr;
13587   struct fnfieldlist *flp;
13588   int i;
13589   struct fn_field *fnp;
13590   const char *fieldname;
13591   struct nextfnfield *new_fnfield;
13592   struct type *this_type;
13593   enum dwarf_access_attribute accessibility;
13594
13595   if (cu->language == language_ada)
13596     error (_("unexpected member function in Ada type"));
13597
13598   /* Get name of member function.  */
13599   fieldname = dwarf2_name (die, cu);
13600   if (fieldname == NULL)
13601     return;
13602
13603   /* Look up member function name in fieldlist.  */
13604   for (i = 0; i < fip->nfnfields; i++)
13605     {
13606       if (strcmp (fip->fnfieldlists[i].name, fieldname) == 0)
13607         break;
13608     }
13609
13610   /* Create new list element if necessary.  */
13611   if (i < fip->nfnfields)
13612     flp = &fip->fnfieldlists[i];
13613   else
13614     {
13615       if ((fip->nfnfields % DW_FIELD_ALLOC_CHUNK) == 0)
13616         {
13617           fip->fnfieldlists = (struct fnfieldlist *)
13618             xrealloc (fip->fnfieldlists,
13619                       (fip->nfnfields + DW_FIELD_ALLOC_CHUNK)
13620                       * sizeof (struct fnfieldlist));
13621           if (fip->nfnfields == 0)
13622             make_cleanup (free_current_contents, &fip->fnfieldlists);
13623         }
13624       flp = &fip->fnfieldlists[fip->nfnfields];
13625       flp->name = fieldname;
13626       flp->length = 0;
13627       flp->head = NULL;
13628       i = fip->nfnfields++;
13629     }
13630
13631   /* Create a new member function field and chain it to the field list
13632      entry.  */
13633   new_fnfield = XNEW (struct nextfnfield);
13634   make_cleanup (xfree, new_fnfield);
13635   memset (new_fnfield, 0, sizeof (struct nextfnfield));
13636   new_fnfield->next = flp->head;
13637   flp->head = new_fnfield;
13638   flp->length++;
13639
13640   /* Fill in the member function field info.  */
13641   fnp = &new_fnfield->fnfield;
13642
13643   /* Delay processing of the physname until later.  */
13644   if (cu->language == language_cplus)
13645     {
13646       add_to_method_list (type, i, flp->length - 1, fieldname,
13647                           die, cu);
13648     }
13649   else
13650     {
13651       const char *physname = dwarf2_physname (fieldname, die, cu);
13652       fnp->physname = physname ? physname : "";
13653     }
13654
13655   fnp->type = alloc_type (objfile);
13656   this_type = read_type_die (die, cu);
13657   if (this_type && TYPE_CODE (this_type) == TYPE_CODE_FUNC)
13658     {
13659       int nparams = TYPE_NFIELDS (this_type);
13660
13661       /* TYPE is the domain of this method, and THIS_TYPE is the type
13662            of the method itself (TYPE_CODE_METHOD).  */
13663       smash_to_method_type (fnp->type, type,
13664                             TYPE_TARGET_TYPE (this_type),
13665                             TYPE_FIELDS (this_type),
13666                             TYPE_NFIELDS (this_type),
13667                             TYPE_VARARGS (this_type));
13668
13669       /* Handle static member functions.
13670          Dwarf2 has no clean way to discern C++ static and non-static
13671          member functions.  G++ helps GDB by marking the first
13672          parameter for non-static member functions (which is the this
13673          pointer) as artificial.  We obtain this information from
13674          read_subroutine_type via TYPE_FIELD_ARTIFICIAL.  */
13675       if (nparams == 0 || TYPE_FIELD_ARTIFICIAL (this_type, 0) == 0)
13676         fnp->voffset = VOFFSET_STATIC;
13677     }
13678   else
13679     complaint (&symfile_complaints, _("member function type missing for '%s'"),
13680                dwarf2_full_name (fieldname, die, cu));
13681
13682   /* Get fcontext from DW_AT_containing_type if present.  */
13683   if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
13684     fnp->fcontext = die_containing_type (die, cu);
13685
13686   /* dwarf2 doesn't have stubbed physical names, so the setting of is_const and
13687      is_volatile is irrelevant, as it is needed by gdb_mangle_name only.  */
13688
13689   /* Get accessibility.  */
13690   attr = dwarf2_attr (die, DW_AT_accessibility, cu);
13691   if (attr)
13692     accessibility = (enum dwarf_access_attribute) DW_UNSND (attr);
13693   else
13694     accessibility = dwarf2_default_access_attribute (die, cu);
13695   switch (accessibility)
13696     {
13697     case DW_ACCESS_private:
13698       fnp->is_private = 1;
13699       break;
13700     case DW_ACCESS_protected:
13701       fnp->is_protected = 1;
13702       break;
13703     }
13704
13705   /* Check for artificial methods.  */
13706   attr = dwarf2_attr (die, DW_AT_artificial, cu);
13707   if (attr && DW_UNSND (attr) != 0)
13708     fnp->is_artificial = 1;
13709
13710   fnp->is_constructor = dwarf2_is_constructor (die, cu);
13711
13712   /* Get index in virtual function table if it is a virtual member
13713      function.  For older versions of GCC, this is an offset in the
13714      appropriate virtual table, as specified by DW_AT_containing_type.
13715      For everyone else, it is an expression to be evaluated relative
13716      to the object address.  */
13717
13718   attr = dwarf2_attr (die, DW_AT_vtable_elem_location, cu);
13719   if (attr)
13720     {
13721       if (attr_form_is_block (attr) && DW_BLOCK (attr)->size > 0)
13722         {
13723           if (DW_BLOCK (attr)->data[0] == DW_OP_constu)
13724             {
13725               /* Old-style GCC.  */
13726               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu) + 2;
13727             }
13728           else if (DW_BLOCK (attr)->data[0] == DW_OP_deref
13729                    || (DW_BLOCK (attr)->size > 1
13730                        && DW_BLOCK (attr)->data[0] == DW_OP_deref_size
13731                        && DW_BLOCK (attr)->data[1] == cu->header.addr_size))
13732             {
13733               fnp->voffset = decode_locdesc (DW_BLOCK (attr), cu);
13734               if ((fnp->voffset % cu->header.addr_size) != 0)
13735                 dwarf2_complex_location_expr_complaint ();
13736               else
13737                 fnp->voffset /= cu->header.addr_size;
13738               fnp->voffset += 2;
13739             }
13740           else
13741             dwarf2_complex_location_expr_complaint ();
13742
13743           if (!fnp->fcontext)
13744             {
13745               /* If there is no `this' field and no DW_AT_containing_type,
13746                  we cannot actually find a base class context for the
13747                  vtable!  */
13748               if (TYPE_NFIELDS (this_type) == 0
13749                   || !TYPE_FIELD_ARTIFICIAL (this_type, 0))
13750                 {
13751                   complaint (&symfile_complaints,
13752                              _("cannot determine context for virtual member "
13753                                "function \"%s\" (offset %d)"),
13754                              fieldname, to_underlying (die->sect_off));
13755                 }
13756               else
13757                 {
13758                   fnp->fcontext
13759                     = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (this_type, 0));
13760                 }
13761             }
13762         }
13763       else if (attr_form_is_section_offset (attr))
13764         {
13765           dwarf2_complex_location_expr_complaint ();
13766         }
13767       else
13768         {
13769           dwarf2_invalid_attrib_class_complaint ("DW_AT_vtable_elem_location",
13770                                                  fieldname);
13771         }
13772     }
13773   else
13774     {
13775       attr = dwarf2_attr (die, DW_AT_virtuality, cu);
13776       if (attr && DW_UNSND (attr))
13777         {
13778           /* GCC does this, as of 2008-08-25; PR debug/37237.  */
13779           complaint (&symfile_complaints,
13780                      _("Member function \"%s\" (offset %d) is virtual "
13781                        "but the vtable offset is not specified"),
13782                      fieldname, to_underlying (die->sect_off));
13783           ALLOCATE_CPLUS_STRUCT_TYPE (type);
13784           TYPE_CPLUS_DYNAMIC (type) = 1;
13785         }
13786     }
13787 }
13788
13789 /* Create the vector of member function fields, and attach it to the type.  */
13790
13791 static void
13792 dwarf2_attach_fn_fields_to_type (struct field_info *fip, struct type *type,
13793                                  struct dwarf2_cu *cu)
13794 {
13795   struct fnfieldlist *flp;
13796   int i;
13797
13798   if (cu->language == language_ada)
13799     error (_("unexpected member functions in Ada type"));
13800
13801   ALLOCATE_CPLUS_STRUCT_TYPE (type);
13802   TYPE_FN_FIELDLISTS (type) = (struct fn_fieldlist *)
13803     TYPE_ALLOC (type, sizeof (struct fn_fieldlist) * fip->nfnfields);
13804
13805   for (i = 0, flp = fip->fnfieldlists; i < fip->nfnfields; i++, flp++)
13806     {
13807       struct nextfnfield *nfp = flp->head;
13808       struct fn_fieldlist *fn_flp = &TYPE_FN_FIELDLIST (type, i);
13809       int k;
13810
13811       TYPE_FN_FIELDLIST_NAME (type, i) = flp->name;
13812       TYPE_FN_FIELDLIST_LENGTH (type, i) = flp->length;
13813       fn_flp->fn_fields = (struct fn_field *)
13814         TYPE_ALLOC (type, sizeof (struct fn_field) * flp->length);
13815       for (k = flp->length; (k--, nfp); nfp = nfp->next)
13816         fn_flp->fn_fields[k] = nfp->fnfield;
13817     }
13818
13819   TYPE_NFN_FIELDS (type) = fip->nfnfields;
13820 }
13821
13822 /* Returns non-zero if NAME is the name of a vtable member in CU's
13823    language, zero otherwise.  */
13824 static int
13825 is_vtable_name (const char *name, struct dwarf2_cu *cu)
13826 {
13827   static const char vptr[] = "_vptr";
13828   static const char vtable[] = "vtable";
13829
13830   /* Look for the C++ form of the vtable.  */
13831   if (startswith (name, vptr) && is_cplus_marker (name[sizeof (vptr) - 1]))
13832     return 1;
13833
13834   return 0;
13835 }
13836
13837 /* GCC outputs unnamed structures that are really pointers to member
13838    functions, with the ABI-specified layout.  If TYPE describes
13839    such a structure, smash it into a member function type.
13840
13841    GCC shouldn't do this; it should just output pointer to member DIEs.
13842    This is GCC PR debug/28767.  */
13843
13844 static void
13845 quirk_gcc_member_function_pointer (struct type *type, struct objfile *objfile)
13846 {
13847   struct type *pfn_type, *self_type, *new_type;
13848
13849   /* Check for a structure with no name and two children.  */
13850   if (TYPE_CODE (type) != TYPE_CODE_STRUCT || TYPE_NFIELDS (type) != 2)
13851     return;
13852
13853   /* Check for __pfn and __delta members.  */
13854   if (TYPE_FIELD_NAME (type, 0) == NULL
13855       || strcmp (TYPE_FIELD_NAME (type, 0), "__pfn") != 0
13856       || TYPE_FIELD_NAME (type, 1) == NULL
13857       || strcmp (TYPE_FIELD_NAME (type, 1), "__delta") != 0)
13858     return;
13859
13860   /* Find the type of the method.  */
13861   pfn_type = TYPE_FIELD_TYPE (type, 0);
13862   if (pfn_type == NULL
13863       || TYPE_CODE (pfn_type) != TYPE_CODE_PTR
13864       || TYPE_CODE (TYPE_TARGET_TYPE (pfn_type)) != TYPE_CODE_FUNC)
13865     return;
13866
13867   /* Look for the "this" argument.  */
13868   pfn_type = TYPE_TARGET_TYPE (pfn_type);
13869   if (TYPE_NFIELDS (pfn_type) == 0
13870       /* || TYPE_FIELD_TYPE (pfn_type, 0) == NULL */
13871       || TYPE_CODE (TYPE_FIELD_TYPE (pfn_type, 0)) != TYPE_CODE_PTR)
13872     return;
13873
13874   self_type = TYPE_TARGET_TYPE (TYPE_FIELD_TYPE (pfn_type, 0));
13875   new_type = alloc_type (objfile);
13876   smash_to_method_type (new_type, self_type, TYPE_TARGET_TYPE (pfn_type),
13877                         TYPE_FIELDS (pfn_type), TYPE_NFIELDS (pfn_type),
13878                         TYPE_VARARGS (pfn_type));
13879   smash_to_methodptr_type (type, new_type);
13880 }
13881
13882
13883 /* Called when we find the DIE that starts a structure or union scope
13884    (definition) to create a type for the structure or union.  Fill in
13885    the type's name and general properties; the members will not be
13886    processed until process_structure_scope.  A symbol table entry for
13887    the type will also not be done until process_structure_scope (assuming
13888    the type has a name).
13889
13890    NOTE: we need to call these functions regardless of whether or not the
13891    DIE has a DW_AT_name attribute, since it might be an anonymous
13892    structure or union.  This gets the type entered into our set of
13893    user defined types.  */
13894
13895 static struct type *
13896 read_structure_type (struct die_info *die, struct dwarf2_cu *cu)
13897 {
13898   struct objfile *objfile = cu->objfile;
13899   struct type *type;
13900   struct attribute *attr;
13901   const char *name;
13902
13903   /* If the definition of this type lives in .debug_types, read that type.
13904      Don't follow DW_AT_specification though, that will take us back up
13905      the chain and we want to go down.  */
13906   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
13907   if (attr)
13908     {
13909       type = get_DW_AT_signature_type (die, attr, cu);
13910
13911       /* The type's CU may not be the same as CU.
13912          Ensure TYPE is recorded with CU in die_type_hash.  */
13913       return set_die_type (die, type, cu);
13914     }
13915
13916   type = alloc_type (objfile);
13917   INIT_CPLUS_SPECIFIC (type);
13918
13919   name = dwarf2_name (die, cu);
13920   if (name != NULL)
13921     {
13922       if (cu->language == language_cplus
13923           || cu->language == language_d
13924           || cu->language == language_rust)
13925         {
13926           const char *full_name = dwarf2_full_name (name, die, cu);
13927
13928           /* dwarf2_full_name might have already finished building the DIE's
13929              type.  If so, there is no need to continue.  */
13930           if (get_die_type (die, cu) != NULL)
13931             return get_die_type (die, cu);
13932
13933           TYPE_TAG_NAME (type) = full_name;
13934           if (die->tag == DW_TAG_structure_type
13935               || die->tag == DW_TAG_class_type)
13936             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13937         }
13938       else
13939         {
13940           /* The name is already allocated along with this objfile, so
13941              we don't need to duplicate it for the type.  */
13942           TYPE_TAG_NAME (type) = name;
13943           if (die->tag == DW_TAG_class_type)
13944             TYPE_NAME (type) = TYPE_TAG_NAME (type);
13945         }
13946     }
13947
13948   if (die->tag == DW_TAG_structure_type)
13949     {
13950       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13951     }
13952   else if (die->tag == DW_TAG_union_type)
13953     {
13954       TYPE_CODE (type) = TYPE_CODE_UNION;
13955     }
13956   else
13957     {
13958       TYPE_CODE (type) = TYPE_CODE_STRUCT;
13959     }
13960
13961   if (cu->language == language_cplus && die->tag == DW_TAG_class_type)
13962     TYPE_DECLARED_CLASS (type) = 1;
13963
13964   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
13965   if (attr)
13966     {
13967       if (attr_form_is_constant (attr))
13968         TYPE_LENGTH (type) = DW_UNSND (attr);
13969       else
13970         {
13971           /* For the moment, dynamic type sizes are not supported
13972              by GDB's struct type.  The actual size is determined
13973              on-demand when resolving the type of a given object,
13974              so set the type's length to zero for now.  Otherwise,
13975              we record an expression as the length, and that expression
13976              could lead to a very large value, which could eventually
13977              lead to us trying to allocate that much memory when creating
13978              a value of that type.  */
13979           TYPE_LENGTH (type) = 0;
13980         }
13981     }
13982   else
13983     {
13984       TYPE_LENGTH (type) = 0;
13985     }
13986
13987   if (producer_is_icc_lt_14 (cu) && (TYPE_LENGTH (type) == 0))
13988     {
13989       /* ICC<14 does not output the required DW_AT_declaration on
13990          incomplete types, but gives them a size of zero.  */
13991       TYPE_STUB (type) = 1;
13992     }
13993   else
13994     TYPE_STUB_SUPPORTED (type) = 1;
13995
13996   if (die_is_declaration (die, cu))
13997     TYPE_STUB (type) = 1;
13998   else if (attr == NULL && die->child == NULL
13999            && producer_is_realview (cu->producer))
14000     /* RealView does not output the required DW_AT_declaration
14001        on incomplete types.  */
14002     TYPE_STUB (type) = 1;
14003
14004   /* We need to add the type field to the die immediately so we don't
14005      infinitely recurse when dealing with pointers to the structure
14006      type within the structure itself.  */
14007   set_die_type (die, type, cu);
14008
14009   /* set_die_type should be already done.  */
14010   set_descriptive_type (type, die, cu);
14011
14012   return type;
14013 }
14014
14015 /* Finish creating a structure or union type, including filling in
14016    its members and creating a symbol for it.  */
14017
14018 static void
14019 process_structure_scope (struct die_info *die, struct dwarf2_cu *cu)
14020 {
14021   struct objfile *objfile = cu->objfile;
14022   struct die_info *child_die;
14023   struct type *type;
14024
14025   type = get_die_type (die, cu);
14026   if (type == NULL)
14027     type = read_structure_type (die, cu);
14028
14029   if (die->child != NULL && ! die_is_declaration (die, cu))
14030     {
14031       struct field_info fi;
14032       VEC (symbolp) *template_args = NULL;
14033       struct cleanup *back_to = make_cleanup (null_cleanup, 0);
14034
14035       memset (&fi, 0, sizeof (struct field_info));
14036
14037       child_die = die->child;
14038
14039       while (child_die && child_die->tag)
14040         {
14041           if (child_die->tag == DW_TAG_member
14042               || child_die->tag == DW_TAG_variable)
14043             {
14044               /* NOTE: carlton/2002-11-05: A C++ static data member
14045                  should be a DW_TAG_member that is a declaration, but
14046                  all versions of G++ as of this writing (so through at
14047                  least 3.2.1) incorrectly generate DW_TAG_variable
14048                  tags for them instead.  */
14049               dwarf2_add_field (&fi, child_die, cu);
14050             }
14051           else if (child_die->tag == DW_TAG_subprogram)
14052             {
14053               /* Rust doesn't have member functions in the C++ sense.
14054                  However, it does emit ordinary functions as children
14055                  of a struct DIE.  */
14056               if (cu->language == language_rust)
14057                 read_func_scope (child_die, cu);
14058               else
14059                 {
14060                   /* C++ member function.  */
14061                   dwarf2_add_member_fn (&fi, child_die, type, cu);
14062                 }
14063             }
14064           else if (child_die->tag == DW_TAG_inheritance)
14065             {
14066               /* C++ base class field.  */
14067               dwarf2_add_field (&fi, child_die, cu);
14068             }
14069           else if (child_die->tag == DW_TAG_typedef)
14070             dwarf2_add_typedef (&fi, child_die, cu);
14071           else if (child_die->tag == DW_TAG_template_type_param
14072                    || child_die->tag == DW_TAG_template_value_param)
14073             {
14074               struct symbol *arg = new_symbol (child_die, NULL, cu);
14075
14076               if (arg != NULL)
14077                 VEC_safe_push (symbolp, template_args, arg);
14078             }
14079
14080           child_die = sibling_die (child_die);
14081         }
14082
14083       /* Attach template arguments to type.  */
14084       if (! VEC_empty (symbolp, template_args))
14085         {
14086           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14087           TYPE_N_TEMPLATE_ARGUMENTS (type)
14088             = VEC_length (symbolp, template_args);
14089           TYPE_TEMPLATE_ARGUMENTS (type)
14090             = XOBNEWVEC (&objfile->objfile_obstack,
14091                          struct symbol *,
14092                          TYPE_N_TEMPLATE_ARGUMENTS (type));
14093           memcpy (TYPE_TEMPLATE_ARGUMENTS (type),
14094                   VEC_address (symbolp, template_args),
14095                   (TYPE_N_TEMPLATE_ARGUMENTS (type)
14096                    * sizeof (struct symbol *)));
14097           VEC_free (symbolp, template_args);
14098         }
14099
14100       /* Attach fields and member functions to the type.  */
14101       if (fi.nfields)
14102         dwarf2_attach_fields_to_type (&fi, type, cu);
14103       if (fi.nfnfields)
14104         {
14105           dwarf2_attach_fn_fields_to_type (&fi, type, cu);
14106
14107           /* Get the type which refers to the base class (possibly this
14108              class itself) which contains the vtable pointer for the current
14109              class from the DW_AT_containing_type attribute.  This use of
14110              DW_AT_containing_type is a GNU extension.  */
14111
14112           if (dwarf2_attr (die, DW_AT_containing_type, cu) != NULL)
14113             {
14114               struct type *t = die_containing_type (die, cu);
14115
14116               set_type_vptr_basetype (type, t);
14117               if (type == t)
14118                 {
14119                   int i;
14120
14121                   /* Our own class provides vtbl ptr.  */
14122                   for (i = TYPE_NFIELDS (t) - 1;
14123                        i >= TYPE_N_BASECLASSES (t);
14124                        --i)
14125                     {
14126                       const char *fieldname = TYPE_FIELD_NAME (t, i);
14127
14128                       if (is_vtable_name (fieldname, cu))
14129                         {
14130                           set_type_vptr_fieldno (type, i);
14131                           break;
14132                         }
14133                     }
14134
14135                   /* Complain if virtual function table field not found.  */
14136                   if (i < TYPE_N_BASECLASSES (t))
14137                     complaint (&symfile_complaints,
14138                                _("virtual function table pointer "
14139                                  "not found when defining class '%s'"),
14140                                TYPE_TAG_NAME (type) ? TYPE_TAG_NAME (type) :
14141                                "");
14142                 }
14143               else
14144                 {
14145                   set_type_vptr_fieldno (type, TYPE_VPTR_FIELDNO (t));
14146                 }
14147             }
14148           else if (cu->producer
14149                    && startswith (cu->producer, "IBM(R) XL C/C++ Advanced Edition"))
14150             {
14151               /* The IBM XLC compiler does not provide direct indication
14152                  of the containing type, but the vtable pointer is
14153                  always named __vfp.  */
14154
14155               int i;
14156
14157               for (i = TYPE_NFIELDS (type) - 1;
14158                    i >= TYPE_N_BASECLASSES (type);
14159                    --i)
14160                 {
14161                   if (strcmp (TYPE_FIELD_NAME (type, i), "__vfp") == 0)
14162                     {
14163                       set_type_vptr_fieldno (type, i);
14164                       set_type_vptr_basetype (type, type);
14165                       break;
14166                     }
14167                 }
14168             }
14169         }
14170
14171       /* Copy fi.typedef_field_list linked list elements content into the
14172          allocated array TYPE_TYPEDEF_FIELD_ARRAY (type).  */
14173       if (fi.typedef_field_list)
14174         {
14175           int i = fi.typedef_field_list_count;
14176
14177           ALLOCATE_CPLUS_STRUCT_TYPE (type);
14178           TYPE_TYPEDEF_FIELD_ARRAY (type)
14179             = ((struct typedef_field *)
14180                TYPE_ALLOC (type, sizeof (TYPE_TYPEDEF_FIELD (type, 0)) * i));
14181           TYPE_TYPEDEF_FIELD_COUNT (type) = i;
14182
14183           /* Reverse the list order to keep the debug info elements order.  */
14184           while (--i >= 0)
14185             {
14186               struct typedef_field *dest, *src;
14187
14188               dest = &TYPE_TYPEDEF_FIELD (type, i);
14189               src = &fi.typedef_field_list->field;
14190               fi.typedef_field_list = fi.typedef_field_list->next;
14191               *dest = *src;
14192             }
14193         }
14194
14195       do_cleanups (back_to);
14196     }
14197
14198   quirk_gcc_member_function_pointer (type, objfile);
14199
14200   /* NOTE: carlton/2004-03-16: GCC 3.4 (or at least one of its
14201      snapshots) has been known to create a die giving a declaration
14202      for a class that has, as a child, a die giving a definition for a
14203      nested class.  So we have to process our children even if the
14204      current die is a declaration.  Normally, of course, a declaration
14205      won't have any children at all.  */
14206
14207   child_die = die->child;
14208
14209   while (child_die != NULL && child_die->tag)
14210     {
14211       if (child_die->tag == DW_TAG_member
14212           || child_die->tag == DW_TAG_variable
14213           || child_die->tag == DW_TAG_inheritance
14214           || child_die->tag == DW_TAG_template_value_param
14215           || child_die->tag == DW_TAG_template_type_param)
14216         {
14217           /* Do nothing.  */
14218         }
14219       else
14220         process_die (child_die, cu);
14221
14222       child_die = sibling_die (child_die);
14223     }
14224
14225   /* Do not consider external references.  According to the DWARF standard,
14226      these DIEs are identified by the fact that they have no byte_size
14227      attribute, and a declaration attribute.  */
14228   if (dwarf2_attr (die, DW_AT_byte_size, cu) != NULL
14229       || !die_is_declaration (die, cu))
14230     new_symbol (die, type, cu);
14231 }
14232
14233 /* Assuming DIE is an enumeration type, and TYPE is its associated type,
14234    update TYPE using some information only available in DIE's children.  */
14235
14236 static void
14237 update_enumeration_type_from_children (struct die_info *die,
14238                                        struct type *type,
14239                                        struct dwarf2_cu *cu)
14240 {
14241   struct die_info *child_die;
14242   int unsigned_enum = 1;
14243   int flag_enum = 1;
14244   ULONGEST mask = 0;
14245
14246   auto_obstack obstack;
14247
14248   for (child_die = die->child;
14249        child_die != NULL && child_die->tag;
14250        child_die = sibling_die (child_die))
14251     {
14252       struct attribute *attr;
14253       LONGEST value;
14254       const gdb_byte *bytes;
14255       struct dwarf2_locexpr_baton *baton;
14256       const char *name;
14257
14258       if (child_die->tag != DW_TAG_enumerator)
14259         continue;
14260
14261       attr = dwarf2_attr (child_die, DW_AT_const_value, cu);
14262       if (attr == NULL)
14263         continue;
14264
14265       name = dwarf2_name (child_die, cu);
14266       if (name == NULL)
14267         name = "<anonymous enumerator>";
14268
14269       dwarf2_const_value_attr (attr, type, name, &obstack, cu,
14270                                &value, &bytes, &baton);
14271       if (value < 0)
14272         {
14273           unsigned_enum = 0;
14274           flag_enum = 0;
14275         }
14276       else if ((mask & value) != 0)
14277         flag_enum = 0;
14278       else
14279         mask |= value;
14280
14281       /* If we already know that the enum type is neither unsigned, nor
14282          a flag type, no need to look at the rest of the enumerates.  */
14283       if (!unsigned_enum && !flag_enum)
14284         break;
14285     }
14286
14287   if (unsigned_enum)
14288     TYPE_UNSIGNED (type) = 1;
14289   if (flag_enum)
14290     TYPE_FLAG_ENUM (type) = 1;
14291 }
14292
14293 /* Given a DW_AT_enumeration_type die, set its type.  We do not
14294    complete the type's fields yet, or create any symbols.  */
14295
14296 static struct type *
14297 read_enumeration_type (struct die_info *die, struct dwarf2_cu *cu)
14298 {
14299   struct objfile *objfile = cu->objfile;
14300   struct type *type;
14301   struct attribute *attr;
14302   const char *name;
14303
14304   /* If the definition of this type lives in .debug_types, read that type.
14305      Don't follow DW_AT_specification though, that will take us back up
14306      the chain and we want to go down.  */
14307   attr = dwarf2_attr_no_follow (die, DW_AT_signature);
14308   if (attr)
14309     {
14310       type = get_DW_AT_signature_type (die, attr, cu);
14311
14312       /* The type's CU may not be the same as CU.
14313          Ensure TYPE is recorded with CU in die_type_hash.  */
14314       return set_die_type (die, type, cu);
14315     }
14316
14317   type = alloc_type (objfile);
14318
14319   TYPE_CODE (type) = TYPE_CODE_ENUM;
14320   name = dwarf2_full_name (NULL, die, cu);
14321   if (name != NULL)
14322     TYPE_TAG_NAME (type) = name;
14323
14324   attr = dwarf2_attr (die, DW_AT_type, cu);
14325   if (attr != NULL)
14326     {
14327       struct type *underlying_type = die_type (die, cu);
14328
14329       TYPE_TARGET_TYPE (type) = underlying_type;
14330     }
14331
14332   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14333   if (attr)
14334     {
14335       TYPE_LENGTH (type) = DW_UNSND (attr);
14336     }
14337   else
14338     {
14339       TYPE_LENGTH (type) = 0;
14340     }
14341
14342   /* The enumeration DIE can be incomplete.  In Ada, any type can be
14343      declared as private in the package spec, and then defined only
14344      inside the package body.  Such types are known as Taft Amendment
14345      Types.  When another package uses such a type, an incomplete DIE
14346      may be generated by the compiler.  */
14347   if (die_is_declaration (die, cu))
14348     TYPE_STUB (type) = 1;
14349
14350   /* Finish the creation of this type by using the enum's children.
14351      We must call this even when the underlying type has been provided
14352      so that we can determine if we're looking at a "flag" enum.  */
14353   update_enumeration_type_from_children (die, type, cu);
14354
14355   /* If this type has an underlying type that is not a stub, then we
14356      may use its attributes.  We always use the "unsigned" attribute
14357      in this situation, because ordinarily we guess whether the type
14358      is unsigned -- but the guess can be wrong and the underlying type
14359      can tell us the reality.  However, we defer to a local size
14360      attribute if one exists, because this lets the compiler override
14361      the underlying type if needed.  */
14362   if (TYPE_TARGET_TYPE (type) != NULL && !TYPE_STUB (TYPE_TARGET_TYPE (type)))
14363     {
14364       TYPE_UNSIGNED (type) = TYPE_UNSIGNED (TYPE_TARGET_TYPE (type));
14365       if (TYPE_LENGTH (type) == 0)
14366         TYPE_LENGTH (type) = TYPE_LENGTH (TYPE_TARGET_TYPE (type));
14367     }
14368
14369   TYPE_DECLARED_CLASS (type) = dwarf2_flag_true_p (die, DW_AT_enum_class, cu);
14370
14371   return set_die_type (die, type, cu);
14372 }
14373
14374 /* Given a pointer to a die which begins an enumeration, process all
14375    the dies that define the members of the enumeration, and create the
14376    symbol for the enumeration type.
14377
14378    NOTE: We reverse the order of the element list.  */
14379
14380 static void
14381 process_enumeration_scope (struct die_info *die, struct dwarf2_cu *cu)
14382 {
14383   struct type *this_type;
14384
14385   this_type = get_die_type (die, cu);
14386   if (this_type == NULL)
14387     this_type = read_enumeration_type (die, cu);
14388
14389   if (die->child != NULL)
14390     {
14391       struct die_info *child_die;
14392       struct symbol *sym;
14393       struct field *fields = NULL;
14394       int num_fields = 0;
14395       const char *name;
14396
14397       child_die = die->child;
14398       while (child_die && child_die->tag)
14399         {
14400           if (child_die->tag != DW_TAG_enumerator)
14401             {
14402               process_die (child_die, cu);
14403             }
14404           else
14405             {
14406               name = dwarf2_name (child_die, cu);
14407               if (name)
14408                 {
14409                   sym = new_symbol (child_die, this_type, cu);
14410
14411                   if ((num_fields % DW_FIELD_ALLOC_CHUNK) == 0)
14412                     {
14413                       fields = (struct field *)
14414                         xrealloc (fields,
14415                                   (num_fields + DW_FIELD_ALLOC_CHUNK)
14416                                   * sizeof (struct field));
14417                     }
14418
14419                   FIELD_NAME (fields[num_fields]) = SYMBOL_LINKAGE_NAME (sym);
14420                   FIELD_TYPE (fields[num_fields]) = NULL;
14421                   SET_FIELD_ENUMVAL (fields[num_fields], SYMBOL_VALUE (sym));
14422                   FIELD_BITSIZE (fields[num_fields]) = 0;
14423
14424                   num_fields++;
14425                 }
14426             }
14427
14428           child_die = sibling_die (child_die);
14429         }
14430
14431       if (num_fields)
14432         {
14433           TYPE_NFIELDS (this_type) = num_fields;
14434           TYPE_FIELDS (this_type) = (struct field *)
14435             TYPE_ALLOC (this_type, sizeof (struct field) * num_fields);
14436           memcpy (TYPE_FIELDS (this_type), fields,
14437                   sizeof (struct field) * num_fields);
14438           xfree (fields);
14439         }
14440     }
14441
14442   /* If we are reading an enum from a .debug_types unit, and the enum
14443      is a declaration, and the enum is not the signatured type in the
14444      unit, then we do not want to add a symbol for it.  Adding a
14445      symbol would in some cases obscure the true definition of the
14446      enum, giving users an incomplete type when the definition is
14447      actually available.  Note that we do not want to do this for all
14448      enums which are just declarations, because C++0x allows forward
14449      enum declarations.  */
14450   if (cu->per_cu->is_debug_types
14451       && die_is_declaration (die, cu))
14452     {
14453       struct signatured_type *sig_type;
14454
14455       sig_type = (struct signatured_type *) cu->per_cu;
14456       gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
14457       if (sig_type->type_offset_in_section != die->sect_off)
14458         return;
14459     }
14460
14461   new_symbol (die, this_type, cu);
14462 }
14463
14464 /* Extract all information from a DW_TAG_array_type DIE and put it in
14465    the DIE's type field.  For now, this only handles one dimensional
14466    arrays.  */
14467
14468 static struct type *
14469 read_array_type (struct die_info *die, struct dwarf2_cu *cu)
14470 {
14471   struct objfile *objfile = cu->objfile;
14472   struct die_info *child_die;
14473   struct type *type;
14474   struct type *element_type, *range_type, *index_type;
14475   struct attribute *attr;
14476   const char *name;
14477   unsigned int bit_stride = 0;
14478
14479   element_type = die_type (die, cu);
14480
14481   /* The die_type call above may have already set the type for this DIE.  */
14482   type = get_die_type (die, cu);
14483   if (type)
14484     return type;
14485
14486   attr = dwarf2_attr (die, DW_AT_byte_stride, cu);
14487   if (attr != NULL)
14488     bit_stride = DW_UNSND (attr) * 8;
14489
14490   attr = dwarf2_attr (die, DW_AT_bit_stride, cu);
14491   if (attr != NULL)
14492     bit_stride = DW_UNSND (attr);
14493
14494   /* Irix 6.2 native cc creates array types without children for
14495      arrays with unspecified length.  */
14496   if (die->child == NULL)
14497     {
14498       index_type = objfile_type (objfile)->builtin_int;
14499       range_type = create_static_range_type (NULL, index_type, 0, -1);
14500       type = create_array_type_with_stride (NULL, element_type, range_type,
14501                                             bit_stride);
14502       return set_die_type (die, type, cu);
14503     }
14504
14505   std::vector<struct type *> range_types;
14506   child_die = die->child;
14507   while (child_die && child_die->tag)
14508     {
14509       if (child_die->tag == DW_TAG_subrange_type)
14510         {
14511           struct type *child_type = read_type_die (child_die, cu);
14512
14513           if (child_type != NULL)
14514             {
14515               /* The range type was succesfully read.  Save it for the
14516                  array type creation.  */
14517               range_types.push_back (child_type);
14518             }
14519         }
14520       child_die = sibling_die (child_die);
14521     }
14522
14523   /* Dwarf2 dimensions are output from left to right, create the
14524      necessary array types in backwards order.  */
14525
14526   type = element_type;
14527
14528   if (read_array_order (die, cu) == DW_ORD_col_major)
14529     {
14530       int i = 0;
14531
14532       while (i < range_types.size ())
14533         type = create_array_type_with_stride (NULL, type, range_types[i++],
14534                                               bit_stride);
14535     }
14536   else
14537     {
14538       size_t ndim = range_types.size ();
14539       while (ndim-- > 0)
14540         type = create_array_type_with_stride (NULL, type, range_types[ndim],
14541                                               bit_stride);
14542     }
14543
14544   /* Understand Dwarf2 support for vector types (like they occur on
14545      the PowerPC w/ AltiVec).  Gcc just adds another attribute to the
14546      array type.  This is not part of the Dwarf2/3 standard yet, but a
14547      custom vendor extension.  The main difference between a regular
14548      array and the vector variant is that vectors are passed by value
14549      to functions.  */
14550   attr = dwarf2_attr (die, DW_AT_GNU_vector, cu);
14551   if (attr)
14552     make_vector_type (type);
14553
14554   /* The DIE may have DW_AT_byte_size set.  For example an OpenCL
14555      implementation may choose to implement triple vectors using this
14556      attribute.  */
14557   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14558   if (attr)
14559     {
14560       if (DW_UNSND (attr) >= TYPE_LENGTH (type))
14561         TYPE_LENGTH (type) = DW_UNSND (attr);
14562       else
14563         complaint (&symfile_complaints,
14564                    _("DW_AT_byte_size for array type smaller "
14565                      "than the total size of elements"));
14566     }
14567
14568   name = dwarf2_name (die, cu);
14569   if (name)
14570     TYPE_NAME (type) = name;
14571
14572   /* Install the type in the die.  */
14573   set_die_type (die, type, cu);
14574
14575   /* set_die_type should be already done.  */
14576   set_descriptive_type (type, die, cu);
14577
14578   return type;
14579 }
14580
14581 static enum dwarf_array_dim_ordering
14582 read_array_order (struct die_info *die, struct dwarf2_cu *cu)
14583 {
14584   struct attribute *attr;
14585
14586   attr = dwarf2_attr (die, DW_AT_ordering, cu);
14587
14588   if (attr)
14589     return (enum dwarf_array_dim_ordering) DW_SND (attr);
14590
14591   /* GNU F77 is a special case, as at 08/2004 array type info is the
14592      opposite order to the dwarf2 specification, but data is still
14593      laid out as per normal fortran.
14594
14595      FIXME: dsl/2004-8-20: If G77 is ever fixed, this will also need
14596      version checking.  */
14597
14598   if (cu->language == language_fortran
14599       && cu->producer && strstr (cu->producer, "GNU F77"))
14600     {
14601       return DW_ORD_row_major;
14602     }
14603
14604   switch (cu->language_defn->la_array_ordering)
14605     {
14606     case array_column_major:
14607       return DW_ORD_col_major;
14608     case array_row_major:
14609     default:
14610       return DW_ORD_row_major;
14611     };
14612 }
14613
14614 /* Extract all information from a DW_TAG_set_type DIE and put it in
14615    the DIE's type field.  */
14616
14617 static struct type *
14618 read_set_type (struct die_info *die, struct dwarf2_cu *cu)
14619 {
14620   struct type *domain_type, *set_type;
14621   struct attribute *attr;
14622
14623   domain_type = die_type (die, cu);
14624
14625   /* The die_type call above may have already set the type for this DIE.  */
14626   set_type = get_die_type (die, cu);
14627   if (set_type)
14628     return set_type;
14629
14630   set_type = create_set_type (NULL, domain_type);
14631
14632   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
14633   if (attr)
14634     TYPE_LENGTH (set_type) = DW_UNSND (attr);
14635
14636   return set_die_type (die, set_type, cu);
14637 }
14638
14639 /* A helper for read_common_block that creates a locexpr baton.
14640    SYM is the symbol which we are marking as computed.
14641    COMMON_DIE is the DIE for the common block.
14642    COMMON_LOC is the location expression attribute for the common
14643    block itself.
14644    MEMBER_LOC is the location expression attribute for the particular
14645    member of the common block that we are processing.
14646    CU is the CU from which the above come.  */
14647
14648 static void
14649 mark_common_block_symbol_computed (struct symbol *sym,
14650                                    struct die_info *common_die,
14651                                    struct attribute *common_loc,
14652                                    struct attribute *member_loc,
14653                                    struct dwarf2_cu *cu)
14654 {
14655   struct objfile *objfile = dwarf2_per_objfile->objfile;
14656   struct dwarf2_locexpr_baton *baton;
14657   gdb_byte *ptr;
14658   unsigned int cu_off;
14659   enum bfd_endian byte_order = gdbarch_byte_order (get_objfile_arch (objfile));
14660   LONGEST offset = 0;
14661
14662   gdb_assert (common_loc && member_loc);
14663   gdb_assert (attr_form_is_block (common_loc));
14664   gdb_assert (attr_form_is_block (member_loc)
14665               || attr_form_is_constant (member_loc));
14666
14667   baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
14668   baton->per_cu = cu->per_cu;
14669   gdb_assert (baton->per_cu);
14670
14671   baton->size = 5 /* DW_OP_call4 */ + 1 /* DW_OP_plus */;
14672
14673   if (attr_form_is_constant (member_loc))
14674     {
14675       offset = dwarf2_get_attr_constant_value (member_loc, 0);
14676       baton->size += 1 /* DW_OP_addr */ + cu->header.addr_size;
14677     }
14678   else
14679     baton->size += DW_BLOCK (member_loc)->size;
14680
14681   ptr = (gdb_byte *) obstack_alloc (&objfile->objfile_obstack, baton->size);
14682   baton->data = ptr;
14683
14684   *ptr++ = DW_OP_call4;
14685   cu_off = common_die->sect_off - cu->per_cu->sect_off;
14686   store_unsigned_integer (ptr, 4, byte_order, cu_off);
14687   ptr += 4;
14688
14689   if (attr_form_is_constant (member_loc))
14690     {
14691       *ptr++ = DW_OP_addr;
14692       store_unsigned_integer (ptr, cu->header.addr_size, byte_order, offset);
14693       ptr += cu->header.addr_size;
14694     }
14695   else
14696     {
14697       /* We have to copy the data here, because DW_OP_call4 will only
14698          use a DW_AT_location attribute.  */
14699       memcpy (ptr, DW_BLOCK (member_loc)->data, DW_BLOCK (member_loc)->size);
14700       ptr += DW_BLOCK (member_loc)->size;
14701     }
14702
14703   *ptr++ = DW_OP_plus;
14704   gdb_assert (ptr - baton->data == baton->size);
14705
14706   SYMBOL_LOCATION_BATON (sym) = baton;
14707   SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
14708 }
14709
14710 /* Create appropriate locally-scoped variables for all the
14711    DW_TAG_common_block entries.  Also create a struct common_block
14712    listing all such variables for `info common'.  COMMON_BLOCK_DOMAIN
14713    is used to sepate the common blocks name namespace from regular
14714    variable names.  */
14715
14716 static void
14717 read_common_block (struct die_info *die, struct dwarf2_cu *cu)
14718 {
14719   struct attribute *attr;
14720
14721   attr = dwarf2_attr (die, DW_AT_location, cu);
14722   if (attr)
14723     {
14724       /* Support the .debug_loc offsets.  */
14725       if (attr_form_is_block (attr))
14726         {
14727           /* Ok.  */
14728         }
14729       else if (attr_form_is_section_offset (attr))
14730         {
14731           dwarf2_complex_location_expr_complaint ();
14732           attr = NULL;
14733         }
14734       else
14735         {
14736           dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
14737                                                  "common block member");
14738           attr = NULL;
14739         }
14740     }
14741
14742   if (die->child != NULL)
14743     {
14744       struct objfile *objfile = cu->objfile;
14745       struct die_info *child_die;
14746       size_t n_entries = 0, size;
14747       struct common_block *common_block;
14748       struct symbol *sym;
14749
14750       for (child_die = die->child;
14751            child_die && child_die->tag;
14752            child_die = sibling_die (child_die))
14753         ++n_entries;
14754
14755       size = (sizeof (struct common_block)
14756               + (n_entries - 1) * sizeof (struct symbol *));
14757       common_block
14758         = (struct common_block *) obstack_alloc (&objfile->objfile_obstack,
14759                                                  size);
14760       memset (common_block->contents, 0, n_entries * sizeof (struct symbol *));
14761       common_block->n_entries = 0;
14762
14763       for (child_die = die->child;
14764            child_die && child_die->tag;
14765            child_die = sibling_die (child_die))
14766         {
14767           /* Create the symbol in the DW_TAG_common_block block in the current
14768              symbol scope.  */
14769           sym = new_symbol (child_die, NULL, cu);
14770           if (sym != NULL)
14771             {
14772               struct attribute *member_loc;
14773
14774               common_block->contents[common_block->n_entries++] = sym;
14775
14776               member_loc = dwarf2_attr (child_die, DW_AT_data_member_location,
14777                                         cu);
14778               if (member_loc)
14779                 {
14780                   /* GDB has handled this for a long time, but it is
14781                      not specified by DWARF.  It seems to have been
14782                      emitted by gfortran at least as recently as:
14783                      http://gcc.gnu.org/bugzilla/show_bug.cgi?id=23057.  */
14784                   complaint (&symfile_complaints,
14785                              _("Variable in common block has "
14786                                "DW_AT_data_member_location "
14787                                "- DIE at 0x%x [in module %s]"),
14788                              to_underlying (child_die->sect_off),
14789                              objfile_name (cu->objfile));
14790
14791                   if (attr_form_is_section_offset (member_loc))
14792                     dwarf2_complex_location_expr_complaint ();
14793                   else if (attr_form_is_constant (member_loc)
14794                            || attr_form_is_block (member_loc))
14795                     {
14796                       if (attr)
14797                         mark_common_block_symbol_computed (sym, die, attr,
14798                                                            member_loc, cu);
14799                     }
14800                   else
14801                     dwarf2_complex_location_expr_complaint ();
14802                 }
14803             }
14804         }
14805
14806       sym = new_symbol (die, objfile_type (objfile)->builtin_void, cu);
14807       SYMBOL_VALUE_COMMON_BLOCK (sym) = common_block;
14808     }
14809 }
14810
14811 /* Create a type for a C++ namespace.  */
14812
14813 static struct type *
14814 read_namespace_type (struct die_info *die, struct dwarf2_cu *cu)
14815 {
14816   struct objfile *objfile = cu->objfile;
14817   const char *previous_prefix, *name;
14818   int is_anonymous;
14819   struct type *type;
14820
14821   /* For extensions, reuse the type of the original namespace.  */
14822   if (dwarf2_attr (die, DW_AT_extension, cu) != NULL)
14823     {
14824       struct die_info *ext_die;
14825       struct dwarf2_cu *ext_cu = cu;
14826
14827       ext_die = dwarf2_extension (die, &ext_cu);
14828       type = read_type_die (ext_die, ext_cu);
14829
14830       /* EXT_CU may not be the same as CU.
14831          Ensure TYPE is recorded with CU in die_type_hash.  */
14832       return set_die_type (die, type, cu);
14833     }
14834
14835   name = namespace_name (die, &is_anonymous, cu);
14836
14837   /* Now build the name of the current namespace.  */
14838
14839   previous_prefix = determine_prefix (die, cu);
14840   if (previous_prefix[0] != '\0')
14841     name = typename_concat (&objfile->objfile_obstack,
14842                             previous_prefix, name, 0, cu);
14843
14844   /* Create the type.  */
14845   type = init_type (objfile, TYPE_CODE_NAMESPACE, 0, name);
14846   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14847
14848   return set_die_type (die, type, cu);
14849 }
14850
14851 /* Read a namespace scope.  */
14852
14853 static void
14854 read_namespace (struct die_info *die, struct dwarf2_cu *cu)
14855 {
14856   struct objfile *objfile = cu->objfile;
14857   int is_anonymous;
14858
14859   /* Add a symbol associated to this if we haven't seen the namespace
14860      before.  Also, add a using directive if it's an anonymous
14861      namespace.  */
14862
14863   if (dwarf2_attr (die, DW_AT_extension, cu) == NULL)
14864     {
14865       struct type *type;
14866
14867       type = read_type_die (die, cu);
14868       new_symbol (die, type, cu);
14869
14870       namespace_name (die, &is_anonymous, cu);
14871       if (is_anonymous)
14872         {
14873           const char *previous_prefix = determine_prefix (die, cu);
14874
14875           std::vector<const char *> excludes;
14876           add_using_directive (using_directives (cu->language),
14877                                previous_prefix, TYPE_NAME (type), NULL,
14878                                NULL, excludes, 0, &objfile->objfile_obstack);
14879         }
14880     }
14881
14882   if (die->child != NULL)
14883     {
14884       struct die_info *child_die = die->child;
14885
14886       while (child_die && child_die->tag)
14887         {
14888           process_die (child_die, cu);
14889           child_die = sibling_die (child_die);
14890         }
14891     }
14892 }
14893
14894 /* Read a Fortran module as type.  This DIE can be only a declaration used for
14895    imported module.  Still we need that type as local Fortran "use ... only"
14896    declaration imports depend on the created type in determine_prefix.  */
14897
14898 static struct type *
14899 read_module_type (struct die_info *die, struct dwarf2_cu *cu)
14900 {
14901   struct objfile *objfile = cu->objfile;
14902   const char *module_name;
14903   struct type *type;
14904
14905   module_name = dwarf2_name (die, cu);
14906   if (!module_name)
14907     complaint (&symfile_complaints,
14908                _("DW_TAG_module has no name, offset 0x%x"),
14909                to_underlying (die->sect_off));
14910   type = init_type (objfile, TYPE_CODE_MODULE, 0, module_name);
14911
14912   /* determine_prefix uses TYPE_TAG_NAME.  */
14913   TYPE_TAG_NAME (type) = TYPE_NAME (type);
14914
14915   return set_die_type (die, type, cu);
14916 }
14917
14918 /* Read a Fortran module.  */
14919
14920 static void
14921 read_module (struct die_info *die, struct dwarf2_cu *cu)
14922 {
14923   struct die_info *child_die = die->child;
14924   struct type *type;
14925
14926   type = read_type_die (die, cu);
14927   new_symbol (die, type, cu);
14928
14929   while (child_die && child_die->tag)
14930     {
14931       process_die (child_die, cu);
14932       child_die = sibling_die (child_die);
14933     }
14934 }
14935
14936 /* Return the name of the namespace represented by DIE.  Set
14937    *IS_ANONYMOUS to tell whether or not the namespace is an anonymous
14938    namespace.  */
14939
14940 static const char *
14941 namespace_name (struct die_info *die, int *is_anonymous, struct dwarf2_cu *cu)
14942 {
14943   struct die_info *current_die;
14944   const char *name = NULL;
14945
14946   /* Loop through the extensions until we find a name.  */
14947
14948   for (current_die = die;
14949        current_die != NULL;
14950        current_die = dwarf2_extension (die, &cu))
14951     {
14952       /* We don't use dwarf2_name here so that we can detect the absence
14953          of a name -> anonymous namespace.  */
14954       name = dwarf2_string_attr (die, DW_AT_name, cu);
14955
14956       if (name != NULL)
14957         break;
14958     }
14959
14960   /* Is it an anonymous namespace?  */
14961
14962   *is_anonymous = (name == NULL);
14963   if (*is_anonymous)
14964     name = CP_ANONYMOUS_NAMESPACE_STR;
14965
14966   return name;
14967 }
14968
14969 /* Extract all information from a DW_TAG_pointer_type DIE and add to
14970    the user defined type vector.  */
14971
14972 static struct type *
14973 read_tag_pointer_type (struct die_info *die, struct dwarf2_cu *cu)
14974 {
14975   struct gdbarch *gdbarch = get_objfile_arch (cu->objfile);
14976   struct comp_unit_head *cu_header = &cu->header;
14977   struct type *type;
14978   struct attribute *attr_byte_size;
14979   struct attribute *attr_address_class;
14980   int byte_size, addr_class;
14981   struct type *target_type;
14982
14983   target_type = die_type (die, cu);
14984
14985   /* The die_type call above may have already set the type for this DIE.  */
14986   type = get_die_type (die, cu);
14987   if (type)
14988     return type;
14989
14990   type = lookup_pointer_type (target_type);
14991
14992   attr_byte_size = dwarf2_attr (die, DW_AT_byte_size, cu);
14993   if (attr_byte_size)
14994     byte_size = DW_UNSND (attr_byte_size);
14995   else
14996     byte_size = cu_header->addr_size;
14997
14998   attr_address_class = dwarf2_attr (die, DW_AT_address_class, cu);
14999   if (attr_address_class)
15000     addr_class = DW_UNSND (attr_address_class);
15001   else
15002     addr_class = DW_ADDR_none;
15003
15004   /* If the pointer size or address class is different than the
15005      default, create a type variant marked as such and set the
15006      length accordingly.  */
15007   if (TYPE_LENGTH (type) != byte_size || addr_class != DW_ADDR_none)
15008     {
15009       if (gdbarch_address_class_type_flags_p (gdbarch))
15010         {
15011           int type_flags;
15012
15013           type_flags = gdbarch_address_class_type_flags
15014                          (gdbarch, byte_size, addr_class);
15015           gdb_assert ((type_flags & ~TYPE_INSTANCE_FLAG_ADDRESS_CLASS_ALL)
15016                       == 0);
15017           type = make_type_with_address_space (type, type_flags);
15018         }
15019       else if (TYPE_LENGTH (type) != byte_size)
15020         {
15021           complaint (&symfile_complaints,
15022                      _("invalid pointer size %d"), byte_size);
15023         }
15024       else
15025         {
15026           /* Should we also complain about unhandled address classes?  */
15027         }
15028     }
15029
15030   TYPE_LENGTH (type) = byte_size;
15031   return set_die_type (die, type, cu);
15032 }
15033
15034 /* Extract all information from a DW_TAG_ptr_to_member_type DIE and add to
15035    the user defined type vector.  */
15036
15037 static struct type *
15038 read_tag_ptr_to_member_type (struct die_info *die, struct dwarf2_cu *cu)
15039 {
15040   struct type *type;
15041   struct type *to_type;
15042   struct type *domain;
15043
15044   to_type = die_type (die, cu);
15045   domain = die_containing_type (die, cu);
15046
15047   /* The calls above may have already set the type for this DIE.  */
15048   type = get_die_type (die, cu);
15049   if (type)
15050     return type;
15051
15052   if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_METHOD)
15053     type = lookup_methodptr_type (to_type);
15054   else if (TYPE_CODE (check_typedef (to_type)) == TYPE_CODE_FUNC)
15055     {
15056       struct type *new_type = alloc_type (cu->objfile);
15057
15058       smash_to_method_type (new_type, domain, TYPE_TARGET_TYPE (to_type),
15059                             TYPE_FIELDS (to_type), TYPE_NFIELDS (to_type),
15060                             TYPE_VARARGS (to_type));
15061       type = lookup_methodptr_type (new_type);
15062     }
15063   else
15064     type = lookup_memberptr_type (to_type, domain);
15065
15066   return set_die_type (die, type, cu);
15067 }
15068
15069 /* Extract all information from a DW_TAG_{rvalue_,}reference_type DIE and add to
15070    the user defined type vector.  */
15071
15072 static struct type *
15073 read_tag_reference_type (struct die_info *die, struct dwarf2_cu *cu,
15074                           enum type_code refcode)
15075 {
15076   struct comp_unit_head *cu_header = &cu->header;
15077   struct type *type, *target_type;
15078   struct attribute *attr;
15079
15080   gdb_assert (refcode == TYPE_CODE_REF || refcode == TYPE_CODE_RVALUE_REF);
15081
15082   target_type = die_type (die, cu);
15083
15084   /* The die_type call above may have already set the type for this DIE.  */
15085   type = get_die_type (die, cu);
15086   if (type)
15087     return type;
15088
15089   type = lookup_reference_type (target_type, refcode);
15090   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15091   if (attr)
15092     {
15093       TYPE_LENGTH (type) = DW_UNSND (attr);
15094     }
15095   else
15096     {
15097       TYPE_LENGTH (type) = cu_header->addr_size;
15098     }
15099   return set_die_type (die, type, cu);
15100 }
15101
15102 /* Add the given cv-qualifiers to the element type of the array.  GCC
15103    outputs DWARF type qualifiers that apply to an array, not the
15104    element type.  But GDB relies on the array element type to carry
15105    the cv-qualifiers.  This mimics section 6.7.3 of the C99
15106    specification.  */
15107
15108 static struct type *
15109 add_array_cv_type (struct die_info *die, struct dwarf2_cu *cu,
15110                    struct type *base_type, int cnst, int voltl)
15111 {
15112   struct type *el_type, *inner_array;
15113
15114   base_type = copy_type (base_type);
15115   inner_array = base_type;
15116
15117   while (TYPE_CODE (TYPE_TARGET_TYPE (inner_array)) == TYPE_CODE_ARRAY)
15118     {
15119       TYPE_TARGET_TYPE (inner_array) =
15120         copy_type (TYPE_TARGET_TYPE (inner_array));
15121       inner_array = TYPE_TARGET_TYPE (inner_array);
15122     }
15123
15124   el_type = TYPE_TARGET_TYPE (inner_array);
15125   cnst |= TYPE_CONST (el_type);
15126   voltl |= TYPE_VOLATILE (el_type);
15127   TYPE_TARGET_TYPE (inner_array) = make_cv_type (cnst, voltl, el_type, NULL);
15128
15129   return set_die_type (die, base_type, cu);
15130 }
15131
15132 static struct type *
15133 read_tag_const_type (struct die_info *die, struct dwarf2_cu *cu)
15134 {
15135   struct type *base_type, *cv_type;
15136
15137   base_type = die_type (die, cu);
15138
15139   /* The die_type call above may have already set the type for this DIE.  */
15140   cv_type = get_die_type (die, cu);
15141   if (cv_type)
15142     return cv_type;
15143
15144   /* In case the const qualifier is applied to an array type, the element type
15145      is so qualified, not the array type (section 6.7.3 of C99).  */
15146   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15147     return add_array_cv_type (die, cu, base_type, 1, 0);
15148
15149   cv_type = make_cv_type (1, TYPE_VOLATILE (base_type), base_type, 0);
15150   return set_die_type (die, cv_type, cu);
15151 }
15152
15153 static struct type *
15154 read_tag_volatile_type (struct die_info *die, struct dwarf2_cu *cu)
15155 {
15156   struct type *base_type, *cv_type;
15157
15158   base_type = die_type (die, cu);
15159
15160   /* The die_type call above may have already set the type for this DIE.  */
15161   cv_type = get_die_type (die, cu);
15162   if (cv_type)
15163     return cv_type;
15164
15165   /* In case the volatile qualifier is applied to an array type, the
15166      element type is so qualified, not the array type (section 6.7.3
15167      of C99).  */
15168   if (TYPE_CODE (base_type) == TYPE_CODE_ARRAY)
15169     return add_array_cv_type (die, cu, base_type, 0, 1);
15170
15171   cv_type = make_cv_type (TYPE_CONST (base_type), 1, base_type, 0);
15172   return set_die_type (die, cv_type, cu);
15173 }
15174
15175 /* Handle DW_TAG_restrict_type.  */
15176
15177 static struct type *
15178 read_tag_restrict_type (struct die_info *die, struct dwarf2_cu *cu)
15179 {
15180   struct type *base_type, *cv_type;
15181
15182   base_type = die_type (die, cu);
15183
15184   /* The die_type call above may have already set the type for this DIE.  */
15185   cv_type = get_die_type (die, cu);
15186   if (cv_type)
15187     return cv_type;
15188
15189   cv_type = make_restrict_type (base_type);
15190   return set_die_type (die, cv_type, cu);
15191 }
15192
15193 /* Handle DW_TAG_atomic_type.  */
15194
15195 static struct type *
15196 read_tag_atomic_type (struct die_info *die, struct dwarf2_cu *cu)
15197 {
15198   struct type *base_type, *cv_type;
15199
15200   base_type = die_type (die, cu);
15201
15202   /* The die_type call above may have already set the type for this DIE.  */
15203   cv_type = get_die_type (die, cu);
15204   if (cv_type)
15205     return cv_type;
15206
15207   cv_type = make_atomic_type (base_type);
15208   return set_die_type (die, cv_type, cu);
15209 }
15210
15211 /* Extract all information from a DW_TAG_string_type DIE and add to
15212    the user defined type vector.  It isn't really a user defined type,
15213    but it behaves like one, with other DIE's using an AT_user_def_type
15214    attribute to reference it.  */
15215
15216 static struct type *
15217 read_tag_string_type (struct die_info *die, struct dwarf2_cu *cu)
15218 {
15219   struct objfile *objfile = cu->objfile;
15220   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15221   struct type *type, *range_type, *index_type, *char_type;
15222   struct attribute *attr;
15223   unsigned int length;
15224
15225   attr = dwarf2_attr (die, DW_AT_string_length, cu);
15226   if (attr)
15227     {
15228       length = DW_UNSND (attr);
15229     }
15230   else
15231     {
15232       /* Check for the DW_AT_byte_size attribute.  */
15233       attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15234       if (attr)
15235         {
15236           length = DW_UNSND (attr);
15237         }
15238       else
15239         {
15240           length = 1;
15241         }
15242     }
15243
15244   index_type = objfile_type (objfile)->builtin_int;
15245   range_type = create_static_range_type (NULL, index_type, 1, length);
15246   char_type = language_string_char_type (cu->language_defn, gdbarch);
15247   type = create_string_type (NULL, char_type, range_type);
15248
15249   return set_die_type (die, type, cu);
15250 }
15251
15252 /* Assuming that DIE corresponds to a function, returns nonzero
15253    if the function is prototyped.  */
15254
15255 static int
15256 prototyped_function_p (struct die_info *die, struct dwarf2_cu *cu)
15257 {
15258   struct attribute *attr;
15259
15260   attr = dwarf2_attr (die, DW_AT_prototyped, cu);
15261   if (attr && (DW_UNSND (attr) != 0))
15262     return 1;
15263
15264   /* The DWARF standard implies that the DW_AT_prototyped attribute
15265      is only meaninful for C, but the concept also extends to other
15266      languages that allow unprototyped functions (Eg: Objective C).
15267      For all other languages, assume that functions are always
15268      prototyped.  */
15269   if (cu->language != language_c
15270       && cu->language != language_objc
15271       && cu->language != language_opencl)
15272     return 1;
15273
15274   /* RealView does not emit DW_AT_prototyped.  We can not distinguish
15275      prototyped and unprototyped functions; default to prototyped,
15276      since that is more common in modern code (and RealView warns
15277      about unprototyped functions).  */
15278   if (producer_is_realview (cu->producer))
15279     return 1;
15280
15281   return 0;
15282 }
15283
15284 /* Handle DIES due to C code like:
15285
15286    struct foo
15287    {
15288    int (*funcp)(int a, long l);
15289    int b;
15290    };
15291
15292    ('funcp' generates a DW_TAG_subroutine_type DIE).  */
15293
15294 static struct type *
15295 read_subroutine_type (struct die_info *die, struct dwarf2_cu *cu)
15296 {
15297   struct objfile *objfile = cu->objfile;
15298   struct type *type;            /* Type that this function returns.  */
15299   struct type *ftype;           /* Function that returns above type.  */
15300   struct attribute *attr;
15301
15302   type = die_type (die, cu);
15303
15304   /* The die_type call above may have already set the type for this DIE.  */
15305   ftype = get_die_type (die, cu);
15306   if (ftype)
15307     return ftype;
15308
15309   ftype = lookup_function_type (type);
15310
15311   if (prototyped_function_p (die, cu))
15312     TYPE_PROTOTYPED (ftype) = 1;
15313
15314   /* Store the calling convention in the type if it's available in
15315      the subroutine die.  Otherwise set the calling convention to
15316      the default value DW_CC_normal.  */
15317   attr = dwarf2_attr (die, DW_AT_calling_convention, cu);
15318   if (attr)
15319     TYPE_CALLING_CONVENTION (ftype) = DW_UNSND (attr);
15320   else if (cu->producer && strstr (cu->producer, "IBM XL C for OpenCL"))
15321     TYPE_CALLING_CONVENTION (ftype) = DW_CC_GDB_IBM_OpenCL;
15322   else
15323     TYPE_CALLING_CONVENTION (ftype) = DW_CC_normal;
15324
15325   /* Record whether the function returns normally to its caller or not
15326      if the DWARF producer set that information.  */
15327   attr = dwarf2_attr (die, DW_AT_noreturn, cu);
15328   if (attr && (DW_UNSND (attr) != 0))
15329     TYPE_NO_RETURN (ftype) = 1;
15330
15331   /* We need to add the subroutine type to the die immediately so
15332      we don't infinitely recurse when dealing with parameters
15333      declared as the same subroutine type.  */
15334   set_die_type (die, ftype, cu);
15335
15336   if (die->child != NULL)
15337     {
15338       struct type *void_type = objfile_type (objfile)->builtin_void;
15339       struct die_info *child_die;
15340       int nparams, iparams;
15341
15342       /* Count the number of parameters.
15343          FIXME: GDB currently ignores vararg functions, but knows about
15344          vararg member functions.  */
15345       nparams = 0;
15346       child_die = die->child;
15347       while (child_die && child_die->tag)
15348         {
15349           if (child_die->tag == DW_TAG_formal_parameter)
15350             nparams++;
15351           else if (child_die->tag == DW_TAG_unspecified_parameters)
15352             TYPE_VARARGS (ftype) = 1;
15353           child_die = sibling_die (child_die);
15354         }
15355
15356       /* Allocate storage for parameters and fill them in.  */
15357       TYPE_NFIELDS (ftype) = nparams;
15358       TYPE_FIELDS (ftype) = (struct field *)
15359         TYPE_ZALLOC (ftype, nparams * sizeof (struct field));
15360
15361       /* TYPE_FIELD_TYPE must never be NULL.  Pre-fill the array to ensure it
15362          even if we error out during the parameters reading below.  */
15363       for (iparams = 0; iparams < nparams; iparams++)
15364         TYPE_FIELD_TYPE (ftype, iparams) = void_type;
15365
15366       iparams = 0;
15367       child_die = die->child;
15368       while (child_die && child_die->tag)
15369         {
15370           if (child_die->tag == DW_TAG_formal_parameter)
15371             {
15372               struct type *arg_type;
15373
15374               /* DWARF version 2 has no clean way to discern C++
15375                  static and non-static member functions.  G++ helps
15376                  GDB by marking the first parameter for non-static
15377                  member functions (which is the this pointer) as
15378                  artificial.  We pass this information to
15379                  dwarf2_add_member_fn via TYPE_FIELD_ARTIFICIAL.
15380
15381                  DWARF version 3 added DW_AT_object_pointer, which GCC
15382                  4.5 does not yet generate.  */
15383               attr = dwarf2_attr (child_die, DW_AT_artificial, cu);
15384               if (attr)
15385                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = DW_UNSND (attr);
15386               else
15387                 TYPE_FIELD_ARTIFICIAL (ftype, iparams) = 0;
15388               arg_type = die_type (child_die, cu);
15389
15390               /* RealView does not mark THIS as const, which the testsuite
15391                  expects.  GCC marks THIS as const in method definitions,
15392                  but not in the class specifications (GCC PR 43053).  */
15393               if (cu->language == language_cplus && !TYPE_CONST (arg_type)
15394                   && TYPE_FIELD_ARTIFICIAL (ftype, iparams))
15395                 {
15396                   int is_this = 0;
15397                   struct dwarf2_cu *arg_cu = cu;
15398                   const char *name = dwarf2_name (child_die, cu);
15399
15400                   attr = dwarf2_attr (die, DW_AT_object_pointer, cu);
15401                   if (attr)
15402                     {
15403                       /* If the compiler emits this, use it.  */
15404                       if (follow_die_ref (die, attr, &arg_cu) == child_die)
15405                         is_this = 1;
15406                     }
15407                   else if (name && strcmp (name, "this") == 0)
15408                     /* Function definitions will have the argument names.  */
15409                     is_this = 1;
15410                   else if (name == NULL && iparams == 0)
15411                     /* Declarations may not have the names, so like
15412                        elsewhere in GDB, assume an artificial first
15413                        argument is "this".  */
15414                     is_this = 1;
15415
15416                   if (is_this)
15417                     arg_type = make_cv_type (1, TYPE_VOLATILE (arg_type),
15418                                              arg_type, 0);
15419                 }
15420
15421               TYPE_FIELD_TYPE (ftype, iparams) = arg_type;
15422               iparams++;
15423             }
15424           child_die = sibling_die (child_die);
15425         }
15426     }
15427
15428   return ftype;
15429 }
15430
15431 static struct type *
15432 read_typedef (struct die_info *die, struct dwarf2_cu *cu)
15433 {
15434   struct objfile *objfile = cu->objfile;
15435   const char *name = NULL;
15436   struct type *this_type, *target_type;
15437
15438   name = dwarf2_full_name (NULL, die, cu);
15439   this_type = init_type (objfile, TYPE_CODE_TYPEDEF, 0, name);
15440   TYPE_TARGET_STUB (this_type) = 1;
15441   set_die_type (die, this_type, cu);
15442   target_type = die_type (die, cu);
15443   if (target_type != this_type)
15444     TYPE_TARGET_TYPE (this_type) = target_type;
15445   else
15446     {
15447       /* Self-referential typedefs are, it seems, not allowed by the DWARF
15448          spec and cause infinite loops in GDB.  */
15449       complaint (&symfile_complaints,
15450                  _("Self-referential DW_TAG_typedef "
15451                    "- DIE at 0x%x [in module %s]"),
15452                  to_underlying (die->sect_off), objfile_name (objfile));
15453       TYPE_TARGET_TYPE (this_type) = NULL;
15454     }
15455   return this_type;
15456 }
15457
15458 /* Allocate a floating-point type of size BITS and name NAME.  Pass NAME_HINT
15459    (which may be different from NAME) to the architecture back-end to allow
15460    it to guess the correct format if necessary.  */
15461
15462 static struct type *
15463 dwarf2_init_float_type (struct objfile *objfile, int bits, const char *name,
15464                         const char *name_hint)
15465 {
15466   struct gdbarch *gdbarch = get_objfile_arch (objfile);
15467   const struct floatformat **format;
15468   struct type *type;
15469
15470   format = gdbarch_floatformat_for_type (gdbarch, name_hint, bits);
15471   if (format)
15472     type = init_float_type (objfile, bits, name, format);
15473   else
15474     type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15475
15476   return type;
15477 }
15478
15479 /* Find a representation of a given base type and install
15480    it in the TYPE field of the die.  */
15481
15482 static struct type *
15483 read_base_type (struct die_info *die, struct dwarf2_cu *cu)
15484 {
15485   struct objfile *objfile = cu->objfile;
15486   struct type *type;
15487   struct attribute *attr;
15488   int encoding = 0, bits = 0;
15489   const char *name;
15490
15491   attr = dwarf2_attr (die, DW_AT_encoding, cu);
15492   if (attr)
15493     {
15494       encoding = DW_UNSND (attr);
15495     }
15496   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15497   if (attr)
15498     {
15499       bits = DW_UNSND (attr) * TARGET_CHAR_BIT;
15500     }
15501   name = dwarf2_name (die, cu);
15502   if (!name)
15503     {
15504       complaint (&symfile_complaints,
15505                  _("DW_AT_name missing from DW_TAG_base_type"));
15506     }
15507
15508   switch (encoding)
15509     {
15510       case DW_ATE_address:
15511         /* Turn DW_ATE_address into a void * pointer.  */
15512         type = init_type (objfile, TYPE_CODE_VOID, TARGET_CHAR_BIT, NULL);
15513         type = init_pointer_type (objfile, bits, name, type);
15514         break;
15515       case DW_ATE_boolean:
15516         type = init_boolean_type (objfile, bits, 1, name);
15517         break;
15518       case DW_ATE_complex_float:
15519         type = dwarf2_init_float_type (objfile, bits / 2, NULL, name);
15520         type = init_complex_type (objfile, name, type);
15521         break;
15522       case DW_ATE_decimal_float:
15523         type = init_decfloat_type (objfile, bits, name);
15524         break;
15525       case DW_ATE_float:
15526         type = dwarf2_init_float_type (objfile, bits, name, name);
15527         break;
15528       case DW_ATE_signed:
15529         type = init_integer_type (objfile, bits, 0, name);
15530         break;
15531       case DW_ATE_unsigned:
15532         if (cu->language == language_fortran
15533             && name
15534             && startswith (name, "character("))
15535           type = init_character_type (objfile, bits, 1, name);
15536         else
15537           type = init_integer_type (objfile, bits, 1, name);
15538         break;
15539       case DW_ATE_signed_char:
15540         if (cu->language == language_ada || cu->language == language_m2
15541             || cu->language == language_pascal
15542             || cu->language == language_fortran)
15543           type = init_character_type (objfile, bits, 0, name);
15544         else
15545           type = init_integer_type (objfile, bits, 0, name);
15546         break;
15547       case DW_ATE_unsigned_char:
15548         if (cu->language == language_ada || cu->language == language_m2
15549             || cu->language == language_pascal
15550             || cu->language == language_fortran
15551             || cu->language == language_rust)
15552           type = init_character_type (objfile, bits, 1, name);
15553         else
15554           type = init_integer_type (objfile, bits, 1, name);
15555         break;
15556       case DW_ATE_UTF:
15557         {
15558           gdbarch *arch = get_objfile_arch (objfile);
15559
15560           if (bits == 16)
15561             type = builtin_type (arch)->builtin_char16;
15562           else if (bits == 32)
15563             type = builtin_type (arch)->builtin_char32;
15564           else
15565             {
15566               complaint (&symfile_complaints,
15567                          _("unsupported DW_ATE_UTF bit size: '%d'"),
15568                          bits);
15569               type = init_integer_type (objfile, bits, 1, name);
15570             }
15571           return set_die_type (die, type, cu);
15572         }
15573         break;
15574
15575       default:
15576         complaint (&symfile_complaints, _("unsupported DW_AT_encoding: '%s'"),
15577                    dwarf_type_encoding_name (encoding));
15578         type = init_type (objfile, TYPE_CODE_ERROR, bits, name);
15579         break;
15580     }
15581
15582   if (name && strcmp (name, "char") == 0)
15583     TYPE_NOSIGN (type) = 1;
15584
15585   return set_die_type (die, type, cu);
15586 }
15587
15588 /* Parse dwarf attribute if it's a block, reference or constant and put the
15589    resulting value of the attribute into struct bound_prop.
15590    Returns 1 if ATTR could be resolved into PROP, 0 otherwise.  */
15591
15592 static int
15593 attr_to_dynamic_prop (const struct attribute *attr, struct die_info *die,
15594                       struct dwarf2_cu *cu, struct dynamic_prop *prop)
15595 {
15596   struct dwarf2_property_baton *baton;
15597   struct obstack *obstack = &cu->objfile->objfile_obstack;
15598
15599   if (attr == NULL || prop == NULL)
15600     return 0;
15601
15602   if (attr_form_is_block (attr))
15603     {
15604       baton = XOBNEW (obstack, struct dwarf2_property_baton);
15605       baton->referenced_type = NULL;
15606       baton->locexpr.per_cu = cu->per_cu;
15607       baton->locexpr.size = DW_BLOCK (attr)->size;
15608       baton->locexpr.data = DW_BLOCK (attr)->data;
15609       prop->data.baton = baton;
15610       prop->kind = PROP_LOCEXPR;
15611       gdb_assert (prop->data.baton != NULL);
15612     }
15613   else if (attr_form_is_ref (attr))
15614     {
15615       struct dwarf2_cu *target_cu = cu;
15616       struct die_info *target_die;
15617       struct attribute *target_attr;
15618
15619       target_die = follow_die_ref (die, attr, &target_cu);
15620       target_attr = dwarf2_attr (target_die, DW_AT_location, target_cu);
15621       if (target_attr == NULL)
15622         target_attr = dwarf2_attr (target_die, DW_AT_data_member_location,
15623                                    target_cu);
15624       if (target_attr == NULL)
15625         return 0;
15626
15627       switch (target_attr->name)
15628         {
15629           case DW_AT_location:
15630             if (attr_form_is_section_offset (target_attr))
15631               {
15632                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15633                 baton->referenced_type = die_type (target_die, target_cu);
15634                 fill_in_loclist_baton (cu, &baton->loclist, target_attr);
15635                 prop->data.baton = baton;
15636                 prop->kind = PROP_LOCLIST;
15637                 gdb_assert (prop->data.baton != NULL);
15638               }
15639             else if (attr_form_is_block (target_attr))
15640               {
15641                 baton = XOBNEW (obstack, struct dwarf2_property_baton);
15642                 baton->referenced_type = die_type (target_die, target_cu);
15643                 baton->locexpr.per_cu = cu->per_cu;
15644                 baton->locexpr.size = DW_BLOCK (target_attr)->size;
15645                 baton->locexpr.data = DW_BLOCK (target_attr)->data;
15646                 prop->data.baton = baton;
15647                 prop->kind = PROP_LOCEXPR;
15648                 gdb_assert (prop->data.baton != NULL);
15649               }
15650             else
15651               {
15652                 dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
15653                                                        "dynamic property");
15654                 return 0;
15655               }
15656             break;
15657           case DW_AT_data_member_location:
15658             {
15659               LONGEST offset;
15660
15661               if (!handle_data_member_location (target_die, target_cu,
15662                                                 &offset))
15663                 return 0;
15664
15665               baton = XOBNEW (obstack, struct dwarf2_property_baton);
15666               baton->referenced_type = read_type_die (target_die->parent,
15667                                                       target_cu);
15668               baton->offset_info.offset = offset;
15669               baton->offset_info.type = die_type (target_die, target_cu);
15670               prop->data.baton = baton;
15671               prop->kind = PROP_ADDR_OFFSET;
15672               break;
15673             }
15674         }
15675     }
15676   else if (attr_form_is_constant (attr))
15677     {
15678       prop->data.const_val = dwarf2_get_attr_constant_value (attr, 0);
15679       prop->kind = PROP_CONST;
15680     }
15681   else
15682     {
15683       dwarf2_invalid_attrib_class_complaint (dwarf_form_name (attr->form),
15684                                              dwarf2_name (die, cu));
15685       return 0;
15686     }
15687
15688   return 1;
15689 }
15690
15691 /* Read the given DW_AT_subrange DIE.  */
15692
15693 static struct type *
15694 read_subrange_type (struct die_info *die, struct dwarf2_cu *cu)
15695 {
15696   struct type *base_type, *orig_base_type;
15697   struct type *range_type;
15698   struct attribute *attr;
15699   struct dynamic_prop low, high;
15700   int low_default_is_valid;
15701   int high_bound_is_count = 0;
15702   const char *name;
15703   LONGEST negative_mask;
15704
15705   orig_base_type = die_type (die, cu);
15706   /* If ORIG_BASE_TYPE is a typedef, it will not be TYPE_UNSIGNED,
15707      whereas the real type might be.  So, we use ORIG_BASE_TYPE when
15708      creating the range type, but we use the result of check_typedef
15709      when examining properties of the type.  */
15710   base_type = check_typedef (orig_base_type);
15711
15712   /* The die_type call above may have already set the type for this DIE.  */
15713   range_type = get_die_type (die, cu);
15714   if (range_type)
15715     return range_type;
15716
15717   low.kind = PROP_CONST;
15718   high.kind = PROP_CONST;
15719   high.data.const_val = 0;
15720
15721   /* Set LOW_DEFAULT_IS_VALID if current language and DWARF version allow
15722      omitting DW_AT_lower_bound.  */
15723   switch (cu->language)
15724     {
15725     case language_c:
15726     case language_cplus:
15727       low.data.const_val = 0;
15728       low_default_is_valid = 1;
15729       break;
15730     case language_fortran:
15731       low.data.const_val = 1;
15732       low_default_is_valid = 1;
15733       break;
15734     case language_d:
15735     case language_objc:
15736     case language_rust:
15737       low.data.const_val = 0;
15738       low_default_is_valid = (cu->header.version >= 4);
15739       break;
15740     case language_ada:
15741     case language_m2:
15742     case language_pascal:
15743       low.data.const_val = 1;
15744       low_default_is_valid = (cu->header.version >= 4);
15745       break;
15746     default:
15747       low.data.const_val = 0;
15748       low_default_is_valid = 0;
15749       break;
15750     }
15751
15752   attr = dwarf2_attr (die, DW_AT_lower_bound, cu);
15753   if (attr)
15754     attr_to_dynamic_prop (attr, die, cu, &low);
15755   else if (!low_default_is_valid)
15756     complaint (&symfile_complaints, _("Missing DW_AT_lower_bound "
15757                                       "- DIE at 0x%x [in module %s]"),
15758                to_underlying (die->sect_off), objfile_name (cu->objfile));
15759
15760   attr = dwarf2_attr (die, DW_AT_upper_bound, cu);
15761   if (!attr_to_dynamic_prop (attr, die, cu, &high))
15762     {
15763       attr = dwarf2_attr (die, DW_AT_count, cu);
15764       if (attr_to_dynamic_prop (attr, die, cu, &high))
15765         {
15766           /* If bounds are constant do the final calculation here.  */
15767           if (low.kind == PROP_CONST && high.kind == PROP_CONST)
15768             high.data.const_val = low.data.const_val + high.data.const_val - 1;
15769           else
15770             high_bound_is_count = 1;
15771         }
15772     }
15773
15774   /* Dwarf-2 specifications explicitly allows to create subrange types
15775      without specifying a base type.
15776      In that case, the base type must be set to the type of
15777      the lower bound, upper bound or count, in that order, if any of these
15778      three attributes references an object that has a type.
15779      If no base type is found, the Dwarf-2 specifications say that
15780      a signed integer type of size equal to the size of an address should
15781      be used.
15782      For the following C code: `extern char gdb_int [];'
15783      GCC produces an empty range DIE.
15784      FIXME: muller/2010-05-28: Possible references to object for low bound,
15785      high bound or count are not yet handled by this code.  */
15786   if (TYPE_CODE (base_type) == TYPE_CODE_VOID)
15787     {
15788       struct objfile *objfile = cu->objfile;
15789       struct gdbarch *gdbarch = get_objfile_arch (objfile);
15790       int addr_size = gdbarch_addr_bit (gdbarch) /8;
15791       struct type *int_type = objfile_type (objfile)->builtin_int;
15792
15793       /* Test "int", "long int", and "long long int" objfile types,
15794          and select the first one having a size above or equal to the
15795          architecture address size.  */
15796       if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15797         base_type = int_type;
15798       else
15799         {
15800           int_type = objfile_type (objfile)->builtin_long;
15801           if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15802             base_type = int_type;
15803           else
15804             {
15805               int_type = objfile_type (objfile)->builtin_long_long;
15806               if (int_type && TYPE_LENGTH (int_type) >= addr_size)
15807                 base_type = int_type;
15808             }
15809         }
15810     }
15811
15812   /* Normally, the DWARF producers are expected to use a signed
15813      constant form (Eg. DW_FORM_sdata) to express negative bounds.
15814      But this is unfortunately not always the case, as witnessed
15815      with GCC, for instance, where the ambiguous DW_FORM_dataN form
15816      is used instead.  To work around that ambiguity, we treat
15817      the bounds as signed, and thus sign-extend their values, when
15818      the base type is signed.  */
15819   negative_mask =
15820     -((LONGEST) 1 << (TYPE_LENGTH (base_type) * TARGET_CHAR_BIT - 1));
15821   if (low.kind == PROP_CONST
15822       && !TYPE_UNSIGNED (base_type) && (low.data.const_val & negative_mask))
15823     low.data.const_val |= negative_mask;
15824   if (high.kind == PROP_CONST
15825       && !TYPE_UNSIGNED (base_type) && (high.data.const_val & negative_mask))
15826     high.data.const_val |= negative_mask;
15827
15828   range_type = create_range_type (NULL, orig_base_type, &low, &high);
15829
15830   if (high_bound_is_count)
15831     TYPE_RANGE_DATA (range_type)->flag_upper_bound_is_count = 1;
15832
15833   /* Ada expects an empty array on no boundary attributes.  */
15834   if (attr == NULL && cu->language != language_ada)
15835     TYPE_HIGH_BOUND_KIND (range_type) = PROP_UNDEFINED;
15836
15837   name = dwarf2_name (die, cu);
15838   if (name)
15839     TYPE_NAME (range_type) = name;
15840
15841   attr = dwarf2_attr (die, DW_AT_byte_size, cu);
15842   if (attr)
15843     TYPE_LENGTH (range_type) = DW_UNSND (attr);
15844
15845   set_die_type (die, range_type, cu);
15846
15847   /* set_die_type should be already done.  */
15848   set_descriptive_type (range_type, die, cu);
15849
15850   return range_type;
15851 }
15852
15853 static struct type *
15854 read_unspecified_type (struct die_info *die, struct dwarf2_cu *cu)
15855 {
15856   struct type *type;
15857
15858   /* For now, we only support the C meaning of an unspecified type: void.  */
15859
15860   type = init_type (cu->objfile, TYPE_CODE_VOID, 0, NULL);
15861   TYPE_NAME (type) = dwarf2_name (die, cu);
15862
15863   return set_die_type (die, type, cu);
15864 }
15865
15866 /* Read a single die and all its descendents.  Set the die's sibling
15867    field to NULL; set other fields in the die correctly, and set all
15868    of the descendents' fields correctly.  Set *NEW_INFO_PTR to the
15869    location of the info_ptr after reading all of those dies.  PARENT
15870    is the parent of the die in question.  */
15871
15872 static struct die_info *
15873 read_die_and_children (const struct die_reader_specs *reader,
15874                        const gdb_byte *info_ptr,
15875                        const gdb_byte **new_info_ptr,
15876                        struct die_info *parent)
15877 {
15878   struct die_info *die;
15879   const gdb_byte *cur_ptr;
15880   int has_children;
15881
15882   cur_ptr = read_full_die_1 (reader, &die, info_ptr, &has_children, 0);
15883   if (die == NULL)
15884     {
15885       *new_info_ptr = cur_ptr;
15886       return NULL;
15887     }
15888   store_in_ref_table (die, reader->cu);
15889
15890   if (has_children)
15891     die->child = read_die_and_siblings_1 (reader, cur_ptr, new_info_ptr, die);
15892   else
15893     {
15894       die->child = NULL;
15895       *new_info_ptr = cur_ptr;
15896     }
15897
15898   die->sibling = NULL;
15899   die->parent = parent;
15900   return die;
15901 }
15902
15903 /* Read a die, all of its descendents, and all of its siblings; set
15904    all of the fields of all of the dies correctly.  Arguments are as
15905    in read_die_and_children.  */
15906
15907 static struct die_info *
15908 read_die_and_siblings_1 (const struct die_reader_specs *reader,
15909                          const gdb_byte *info_ptr,
15910                          const gdb_byte **new_info_ptr,
15911                          struct die_info *parent)
15912 {
15913   struct die_info *first_die, *last_sibling;
15914   const gdb_byte *cur_ptr;
15915
15916   cur_ptr = info_ptr;
15917   first_die = last_sibling = NULL;
15918
15919   while (1)
15920     {
15921       struct die_info *die
15922         = read_die_and_children (reader, cur_ptr, &cur_ptr, parent);
15923
15924       if (die == NULL)
15925         {
15926           *new_info_ptr = cur_ptr;
15927           return first_die;
15928         }
15929
15930       if (!first_die)
15931         first_die = die;
15932       else
15933         last_sibling->sibling = die;
15934
15935       last_sibling = die;
15936     }
15937 }
15938
15939 /* Read a die, all of its descendents, and all of its siblings; set
15940    all of the fields of all of the dies correctly.  Arguments are as
15941    in read_die_and_children.
15942    This the main entry point for reading a DIE and all its children.  */
15943
15944 static struct die_info *
15945 read_die_and_siblings (const struct die_reader_specs *reader,
15946                        const gdb_byte *info_ptr,
15947                        const gdb_byte **new_info_ptr,
15948                        struct die_info *parent)
15949 {
15950   struct die_info *die = read_die_and_siblings_1 (reader, info_ptr,
15951                                                   new_info_ptr, parent);
15952
15953   if (dwarf_die_debug)
15954     {
15955       fprintf_unfiltered (gdb_stdlog,
15956                           "Read die from %s@0x%x of %s:\n",
15957                           get_section_name (reader->die_section),
15958                           (unsigned) (info_ptr - reader->die_section->buffer),
15959                           bfd_get_filename (reader->abfd));
15960       dump_die (die, dwarf_die_debug);
15961     }
15962
15963   return die;
15964 }
15965
15966 /* Read a die and all its attributes, leave space for NUM_EXTRA_ATTRS
15967    attributes.
15968    The caller is responsible for filling in the extra attributes
15969    and updating (*DIEP)->num_attrs.
15970    Set DIEP to point to a newly allocated die with its information,
15971    except for its child, sibling, and parent fields.
15972    Set HAS_CHILDREN to tell whether the die has children or not.  */
15973
15974 static const gdb_byte *
15975 read_full_die_1 (const struct die_reader_specs *reader,
15976                  struct die_info **diep, const gdb_byte *info_ptr,
15977                  int *has_children, int num_extra_attrs)
15978 {
15979   unsigned int abbrev_number, bytes_read, i;
15980   struct abbrev_info *abbrev;
15981   struct die_info *die;
15982   struct dwarf2_cu *cu = reader->cu;
15983   bfd *abfd = reader->abfd;
15984
15985   sect_offset sect_off = (sect_offset) (info_ptr - reader->buffer);
15986   abbrev_number = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
15987   info_ptr += bytes_read;
15988   if (!abbrev_number)
15989     {
15990       *diep = NULL;
15991       *has_children = 0;
15992       return info_ptr;
15993     }
15994
15995   abbrev = abbrev_table_lookup_abbrev (cu->abbrev_table, abbrev_number);
15996   if (!abbrev)
15997     error (_("Dwarf Error: could not find abbrev number %d [in module %s]"),
15998            abbrev_number,
15999            bfd_get_filename (abfd));
16000
16001   die = dwarf_alloc_die (cu, abbrev->num_attrs + num_extra_attrs);
16002   die->sect_off = sect_off;
16003   die->tag = abbrev->tag;
16004   die->abbrev = abbrev_number;
16005
16006   /* Make the result usable.
16007      The caller needs to update num_attrs after adding the extra
16008      attributes.  */
16009   die->num_attrs = abbrev->num_attrs;
16010
16011   for (i = 0; i < abbrev->num_attrs; ++i)
16012     info_ptr = read_attribute (reader, &die->attrs[i], &abbrev->attrs[i],
16013                                info_ptr);
16014
16015   *diep = die;
16016   *has_children = abbrev->has_children;
16017   return info_ptr;
16018 }
16019
16020 /* Read a die and all its attributes.
16021    Set DIEP to point to a newly allocated die with its information,
16022    except for its child, sibling, and parent fields.
16023    Set HAS_CHILDREN to tell whether the die has children or not.  */
16024
16025 static const gdb_byte *
16026 read_full_die (const struct die_reader_specs *reader,
16027                struct die_info **diep, const gdb_byte *info_ptr,
16028                int *has_children)
16029 {
16030   const gdb_byte *result;
16031
16032   result = read_full_die_1 (reader, diep, info_ptr, has_children, 0);
16033
16034   if (dwarf_die_debug)
16035     {
16036       fprintf_unfiltered (gdb_stdlog,
16037                           "Read die from %s@0x%x of %s:\n",
16038                           get_section_name (reader->die_section),
16039                           (unsigned) (info_ptr - reader->die_section->buffer),
16040                           bfd_get_filename (reader->abfd));
16041       dump_die (*diep, dwarf_die_debug);
16042     }
16043
16044   return result;
16045 }
16046 \f
16047 /* Abbreviation tables.
16048
16049    In DWARF version 2, the description of the debugging information is
16050    stored in a separate .debug_abbrev section.  Before we read any
16051    dies from a section we read in all abbreviations and install them
16052    in a hash table.  */
16053
16054 /* Allocate space for a struct abbrev_info object in ABBREV_TABLE.  */
16055
16056 static struct abbrev_info *
16057 abbrev_table_alloc_abbrev (struct abbrev_table *abbrev_table)
16058 {
16059   struct abbrev_info *abbrev;
16060
16061   abbrev = XOBNEW (&abbrev_table->abbrev_obstack, struct abbrev_info);
16062   memset (abbrev, 0, sizeof (struct abbrev_info));
16063
16064   return abbrev;
16065 }
16066
16067 /* Add an abbreviation to the table.  */
16068
16069 static void
16070 abbrev_table_add_abbrev (struct abbrev_table *abbrev_table,
16071                          unsigned int abbrev_number,
16072                          struct abbrev_info *abbrev)
16073 {
16074   unsigned int hash_number;
16075
16076   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16077   abbrev->next = abbrev_table->abbrevs[hash_number];
16078   abbrev_table->abbrevs[hash_number] = abbrev;
16079 }
16080
16081 /* Look up an abbrev in the table.
16082    Returns NULL if the abbrev is not found.  */
16083
16084 static struct abbrev_info *
16085 abbrev_table_lookup_abbrev (const struct abbrev_table *abbrev_table,
16086                             unsigned int abbrev_number)
16087 {
16088   unsigned int hash_number;
16089   struct abbrev_info *abbrev;
16090
16091   hash_number = abbrev_number % ABBREV_HASH_SIZE;
16092   abbrev = abbrev_table->abbrevs[hash_number];
16093
16094   while (abbrev)
16095     {
16096       if (abbrev->number == abbrev_number)
16097         return abbrev;
16098       abbrev = abbrev->next;
16099     }
16100   return NULL;
16101 }
16102
16103 /* Read in an abbrev table.  */
16104
16105 static struct abbrev_table *
16106 abbrev_table_read_table (struct dwarf2_section_info *section,
16107                          sect_offset sect_off)
16108 {
16109   struct objfile *objfile = dwarf2_per_objfile->objfile;
16110   bfd *abfd = get_section_bfd_owner (section);
16111   struct abbrev_table *abbrev_table;
16112   const gdb_byte *abbrev_ptr;
16113   struct abbrev_info *cur_abbrev;
16114   unsigned int abbrev_number, bytes_read, abbrev_name;
16115   unsigned int abbrev_form;
16116   struct attr_abbrev *cur_attrs;
16117   unsigned int allocated_attrs;
16118
16119   abbrev_table = XNEW (struct abbrev_table);
16120   abbrev_table->sect_off = sect_off;
16121   obstack_init (&abbrev_table->abbrev_obstack);
16122   abbrev_table->abbrevs =
16123     XOBNEWVEC (&abbrev_table->abbrev_obstack, struct abbrev_info *,
16124                ABBREV_HASH_SIZE);
16125   memset (abbrev_table->abbrevs, 0,
16126           ABBREV_HASH_SIZE * sizeof (struct abbrev_info *));
16127
16128   dwarf2_read_section (objfile, section);
16129   abbrev_ptr = section->buffer + to_underlying (sect_off);
16130   abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16131   abbrev_ptr += bytes_read;
16132
16133   allocated_attrs = ATTR_ALLOC_CHUNK;
16134   cur_attrs = XNEWVEC (struct attr_abbrev, allocated_attrs);
16135
16136   /* Loop until we reach an abbrev number of 0.  */
16137   while (abbrev_number)
16138     {
16139       cur_abbrev = abbrev_table_alloc_abbrev (abbrev_table);
16140
16141       /* read in abbrev header */
16142       cur_abbrev->number = abbrev_number;
16143       cur_abbrev->tag
16144         = (enum dwarf_tag) read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16145       abbrev_ptr += bytes_read;
16146       cur_abbrev->has_children = read_1_byte (abfd, abbrev_ptr);
16147       abbrev_ptr += 1;
16148
16149       /* now read in declarations */
16150       for (;;)
16151         {
16152           LONGEST implicit_const;
16153
16154           abbrev_name = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16155           abbrev_ptr += bytes_read;
16156           abbrev_form = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16157           abbrev_ptr += bytes_read;
16158           if (abbrev_form == DW_FORM_implicit_const)
16159             {
16160               implicit_const = read_signed_leb128 (abfd, abbrev_ptr,
16161                                                    &bytes_read);
16162               abbrev_ptr += bytes_read;
16163             }
16164           else
16165             {
16166               /* Initialize it due to a false compiler warning.  */
16167               implicit_const = -1;
16168             }
16169
16170           if (abbrev_name == 0)
16171             break;
16172
16173           if (cur_abbrev->num_attrs == allocated_attrs)
16174             {
16175               allocated_attrs += ATTR_ALLOC_CHUNK;
16176               cur_attrs
16177                 = XRESIZEVEC (struct attr_abbrev, cur_attrs, allocated_attrs);
16178             }
16179
16180           cur_attrs[cur_abbrev->num_attrs].name
16181             = (enum dwarf_attribute) abbrev_name;
16182           cur_attrs[cur_abbrev->num_attrs].form
16183             = (enum dwarf_form) abbrev_form;
16184           cur_attrs[cur_abbrev->num_attrs].implicit_const = implicit_const;
16185           ++cur_abbrev->num_attrs;
16186         }
16187
16188       cur_abbrev->attrs =
16189         XOBNEWVEC (&abbrev_table->abbrev_obstack, struct attr_abbrev,
16190                    cur_abbrev->num_attrs);
16191       memcpy (cur_abbrev->attrs, cur_attrs,
16192               cur_abbrev->num_attrs * sizeof (struct attr_abbrev));
16193
16194       abbrev_table_add_abbrev (abbrev_table, abbrev_number, cur_abbrev);
16195
16196       /* Get next abbreviation.
16197          Under Irix6 the abbreviations for a compilation unit are not
16198          always properly terminated with an abbrev number of 0.
16199          Exit loop if we encounter an abbreviation which we have
16200          already read (which means we are about to read the abbreviations
16201          for the next compile unit) or if the end of the abbreviation
16202          table is reached.  */
16203       if ((unsigned int) (abbrev_ptr - section->buffer) >= section->size)
16204         break;
16205       abbrev_number = read_unsigned_leb128 (abfd, abbrev_ptr, &bytes_read);
16206       abbrev_ptr += bytes_read;
16207       if (abbrev_table_lookup_abbrev (abbrev_table, abbrev_number) != NULL)
16208         break;
16209     }
16210
16211   xfree (cur_attrs);
16212   return abbrev_table;
16213 }
16214
16215 /* Free the resources held by ABBREV_TABLE.  */
16216
16217 static void
16218 abbrev_table_free (struct abbrev_table *abbrev_table)
16219 {
16220   obstack_free (&abbrev_table->abbrev_obstack, NULL);
16221   xfree (abbrev_table);
16222 }
16223
16224 /* Same as abbrev_table_free but as a cleanup.
16225    We pass in a pointer to the pointer to the table so that we can
16226    set the pointer to NULL when we're done.  It also simplifies
16227    build_type_psymtabs_1.  */
16228
16229 static void
16230 abbrev_table_free_cleanup (void *table_ptr)
16231 {
16232   struct abbrev_table **abbrev_table_ptr = (struct abbrev_table **) table_ptr;
16233
16234   if (*abbrev_table_ptr != NULL)
16235     abbrev_table_free (*abbrev_table_ptr);
16236   *abbrev_table_ptr = NULL;
16237 }
16238
16239 /* Read the abbrev table for CU from ABBREV_SECTION.  */
16240
16241 static void
16242 dwarf2_read_abbrevs (struct dwarf2_cu *cu,
16243                      struct dwarf2_section_info *abbrev_section)
16244 {
16245   cu->abbrev_table =
16246     abbrev_table_read_table (abbrev_section, cu->header.abbrev_sect_off);
16247 }
16248
16249 /* Release the memory used by the abbrev table for a compilation unit.  */
16250
16251 static void
16252 dwarf2_free_abbrev_table (void *ptr_to_cu)
16253 {
16254   struct dwarf2_cu *cu = (struct dwarf2_cu *) ptr_to_cu;
16255
16256   if (cu->abbrev_table != NULL)
16257     abbrev_table_free (cu->abbrev_table);
16258   /* Set this to NULL so that we SEGV if we try to read it later,
16259      and also because free_comp_unit verifies this is NULL.  */
16260   cu->abbrev_table = NULL;
16261 }
16262 \f
16263 /* Returns nonzero if TAG represents a type that we might generate a partial
16264    symbol for.  */
16265
16266 static int
16267 is_type_tag_for_partial (int tag)
16268 {
16269   switch (tag)
16270     {
16271 #if 0
16272     /* Some types that would be reasonable to generate partial symbols for,
16273        that we don't at present.  */
16274     case DW_TAG_array_type:
16275     case DW_TAG_file_type:
16276     case DW_TAG_ptr_to_member_type:
16277     case DW_TAG_set_type:
16278     case DW_TAG_string_type:
16279     case DW_TAG_subroutine_type:
16280 #endif
16281     case DW_TAG_base_type:
16282     case DW_TAG_class_type:
16283     case DW_TAG_interface_type:
16284     case DW_TAG_enumeration_type:
16285     case DW_TAG_structure_type:
16286     case DW_TAG_subrange_type:
16287     case DW_TAG_typedef:
16288     case DW_TAG_union_type:
16289       return 1;
16290     default:
16291       return 0;
16292     }
16293 }
16294
16295 /* Load all DIEs that are interesting for partial symbols into memory.  */
16296
16297 static struct partial_die_info *
16298 load_partial_dies (const struct die_reader_specs *reader,
16299                    const gdb_byte *info_ptr, int building_psymtab)
16300 {
16301   struct dwarf2_cu *cu = reader->cu;
16302   struct objfile *objfile = cu->objfile;
16303   struct partial_die_info *part_die;
16304   struct partial_die_info *parent_die, *last_die, *first_die = NULL;
16305   struct abbrev_info *abbrev;
16306   unsigned int bytes_read;
16307   unsigned int load_all = 0;
16308   int nesting_level = 1;
16309
16310   parent_die = NULL;
16311   last_die = NULL;
16312
16313   gdb_assert (cu->per_cu != NULL);
16314   if (cu->per_cu->load_all_dies)
16315     load_all = 1;
16316
16317   cu->partial_dies
16318     = htab_create_alloc_ex (cu->header.length / 12,
16319                             partial_die_hash,
16320                             partial_die_eq,
16321                             NULL,
16322                             &cu->comp_unit_obstack,
16323                             hashtab_obstack_allocate,
16324                             dummy_obstack_deallocate);
16325
16326   part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16327
16328   while (1)
16329     {
16330       abbrev = peek_die_abbrev (info_ptr, &bytes_read, cu);
16331
16332       /* A NULL abbrev means the end of a series of children.  */
16333       if (abbrev == NULL)
16334         {
16335           if (--nesting_level == 0)
16336             {
16337               /* PART_DIE was probably the last thing allocated on the
16338                  comp_unit_obstack, so we could call obstack_free
16339                  here.  We don't do that because the waste is small,
16340                  and will be cleaned up when we're done with this
16341                  compilation unit.  This way, we're also more robust
16342                  against other users of the comp_unit_obstack.  */
16343               return first_die;
16344             }
16345           info_ptr += bytes_read;
16346           last_die = parent_die;
16347           parent_die = parent_die->die_parent;
16348           continue;
16349         }
16350
16351       /* Check for template arguments.  We never save these; if
16352          they're seen, we just mark the parent, and go on our way.  */
16353       if (parent_die != NULL
16354           && cu->language == language_cplus
16355           && (abbrev->tag == DW_TAG_template_type_param
16356               || abbrev->tag == DW_TAG_template_value_param))
16357         {
16358           parent_die->has_template_arguments = 1;
16359
16360           if (!load_all)
16361             {
16362               /* We don't need a partial DIE for the template argument.  */
16363               info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16364               continue;
16365             }
16366         }
16367
16368       /* We only recurse into c++ subprograms looking for template arguments.
16369          Skip their other children.  */
16370       if (!load_all
16371           && cu->language == language_cplus
16372           && parent_die != NULL
16373           && parent_die->tag == DW_TAG_subprogram)
16374         {
16375           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16376           continue;
16377         }
16378
16379       /* Check whether this DIE is interesting enough to save.  Normally
16380          we would not be interested in members here, but there may be
16381          later variables referencing them via DW_AT_specification (for
16382          static members).  */
16383       if (!load_all
16384           && !is_type_tag_for_partial (abbrev->tag)
16385           && abbrev->tag != DW_TAG_constant
16386           && abbrev->tag != DW_TAG_enumerator
16387           && abbrev->tag != DW_TAG_subprogram
16388           && abbrev->tag != DW_TAG_lexical_block
16389           && abbrev->tag != DW_TAG_variable
16390           && abbrev->tag != DW_TAG_namespace
16391           && abbrev->tag != DW_TAG_module
16392           && abbrev->tag != DW_TAG_member
16393           && abbrev->tag != DW_TAG_imported_unit
16394           && abbrev->tag != DW_TAG_imported_declaration)
16395         {
16396           /* Otherwise we skip to the next sibling, if any.  */
16397           info_ptr = skip_one_die (reader, info_ptr + bytes_read, abbrev);
16398           continue;
16399         }
16400
16401       info_ptr = read_partial_die (reader, part_die, abbrev, bytes_read,
16402                                    info_ptr);
16403
16404       /* This two-pass algorithm for processing partial symbols has a
16405          high cost in cache pressure.  Thus, handle some simple cases
16406          here which cover the majority of C partial symbols.  DIEs
16407          which neither have specification tags in them, nor could have
16408          specification tags elsewhere pointing at them, can simply be
16409          processed and discarded.
16410
16411          This segment is also optional; scan_partial_symbols and
16412          add_partial_symbol will handle these DIEs if we chain
16413          them in normally.  When compilers which do not emit large
16414          quantities of duplicate debug information are more common,
16415          this code can probably be removed.  */
16416
16417       /* Any complete simple types at the top level (pretty much all
16418          of them, for a language without namespaces), can be processed
16419          directly.  */
16420       if (parent_die == NULL
16421           && part_die->has_specification == 0
16422           && part_die->is_declaration == 0
16423           && ((part_die->tag == DW_TAG_typedef && !part_die->has_children)
16424               || part_die->tag == DW_TAG_base_type
16425               || part_die->tag == DW_TAG_subrange_type))
16426         {
16427           if (building_psymtab && part_die->name != NULL)
16428             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16429                                  VAR_DOMAIN, LOC_TYPEDEF,
16430                                  &objfile->static_psymbols,
16431                                  0, cu->language, objfile);
16432           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16433           continue;
16434         }
16435
16436       /* The exception for DW_TAG_typedef with has_children above is
16437          a workaround of GCC PR debug/47510.  In the case of this complaint
16438          type_name_no_tag_or_error will error on such types later.
16439
16440          GDB skipped children of DW_TAG_typedef by the shortcut above and then
16441          it could not find the child DIEs referenced later, this is checked
16442          above.  In correct DWARF DW_TAG_typedef should have no children.  */
16443
16444       if (part_die->tag == DW_TAG_typedef && part_die->has_children)
16445         complaint (&symfile_complaints,
16446                    _("DW_TAG_typedef has childen - GCC PR debug/47510 bug "
16447                      "- DIE at 0x%x [in module %s]"),
16448                    to_underlying (part_die->sect_off), objfile_name (objfile));
16449
16450       /* If we're at the second level, and we're an enumerator, and
16451          our parent has no specification (meaning possibly lives in a
16452          namespace elsewhere), then we can add the partial symbol now
16453          instead of queueing it.  */
16454       if (part_die->tag == DW_TAG_enumerator
16455           && parent_die != NULL
16456           && parent_die->die_parent == NULL
16457           && parent_die->tag == DW_TAG_enumeration_type
16458           && parent_die->has_specification == 0)
16459         {
16460           if (part_die->name == NULL)
16461             complaint (&symfile_complaints,
16462                        _("malformed enumerator DIE ignored"));
16463           else if (building_psymtab)
16464             add_psymbol_to_list (part_die->name, strlen (part_die->name), 0,
16465                                  VAR_DOMAIN, LOC_CONST,
16466                                  cu->language == language_cplus
16467                                  ? &objfile->global_psymbols
16468                                  : &objfile->static_psymbols,
16469                                  0, cu->language, objfile);
16470
16471           info_ptr = locate_pdi_sibling (reader, part_die, info_ptr);
16472           continue;
16473         }
16474
16475       /* We'll save this DIE so link it in.  */
16476       part_die->die_parent = parent_die;
16477       part_die->die_sibling = NULL;
16478       part_die->die_child = NULL;
16479
16480       if (last_die && last_die == parent_die)
16481         last_die->die_child = part_die;
16482       else if (last_die)
16483         last_die->die_sibling = part_die;
16484
16485       last_die = part_die;
16486
16487       if (first_die == NULL)
16488         first_die = part_die;
16489
16490       /* Maybe add the DIE to the hash table.  Not all DIEs that we
16491          find interesting need to be in the hash table, because we
16492          also have the parent/sibling/child chains; only those that we
16493          might refer to by offset later during partial symbol reading.
16494
16495          For now this means things that might have be the target of a
16496          DW_AT_specification, DW_AT_abstract_origin, or
16497          DW_AT_extension.  DW_AT_extension will refer only to
16498          namespaces; DW_AT_abstract_origin refers to functions (and
16499          many things under the function DIE, but we do not recurse
16500          into function DIEs during partial symbol reading) and
16501          possibly variables as well; DW_AT_specification refers to
16502          declarations.  Declarations ought to have the DW_AT_declaration
16503          flag.  It happens that GCC forgets to put it in sometimes, but
16504          only for functions, not for types.
16505
16506          Adding more things than necessary to the hash table is harmless
16507          except for the performance cost.  Adding too few will result in
16508          wasted time in find_partial_die, when we reread the compilation
16509          unit with load_all_dies set.  */
16510
16511       if (load_all
16512           || abbrev->tag == DW_TAG_constant
16513           || abbrev->tag == DW_TAG_subprogram
16514           || abbrev->tag == DW_TAG_variable
16515           || abbrev->tag == DW_TAG_namespace
16516           || part_die->is_declaration)
16517         {
16518           void **slot;
16519
16520           slot = htab_find_slot_with_hash (cu->partial_dies, part_die,
16521                                            to_underlying (part_die->sect_off),
16522                                            INSERT);
16523           *slot = part_die;
16524         }
16525
16526       part_die = XOBNEW (&cu->comp_unit_obstack, struct partial_die_info);
16527
16528       /* For some DIEs we want to follow their children (if any).  For C
16529          we have no reason to follow the children of structures; for other
16530          languages we have to, so that we can get at method physnames
16531          to infer fully qualified class names, for DW_AT_specification,
16532          and for C++ template arguments.  For C++, we also look one level
16533          inside functions to find template arguments (if the name of the
16534          function does not already contain the template arguments).
16535
16536          For Ada, we need to scan the children of subprograms and lexical
16537          blocks as well because Ada allows the definition of nested
16538          entities that could be interesting for the debugger, such as
16539          nested subprograms for instance.  */
16540       if (last_die->has_children
16541           && (load_all
16542               || last_die->tag == DW_TAG_namespace
16543               || last_die->tag == DW_TAG_module
16544               || last_die->tag == DW_TAG_enumeration_type
16545               || (cu->language == language_cplus
16546                   && last_die->tag == DW_TAG_subprogram
16547                   && (last_die->name == NULL
16548                       || strchr (last_die->name, '<') == NULL))
16549               || (cu->language != language_c
16550                   && (last_die->tag == DW_TAG_class_type
16551                       || last_die->tag == DW_TAG_interface_type
16552                       || last_die->tag == DW_TAG_structure_type
16553                       || last_die->tag == DW_TAG_union_type))
16554               || (cu->language == language_ada
16555                   && (last_die->tag == DW_TAG_subprogram
16556                       || last_die->tag == DW_TAG_lexical_block))))
16557         {
16558           nesting_level++;
16559           parent_die = last_die;
16560           continue;
16561         }
16562
16563       /* Otherwise we skip to the next sibling, if any.  */
16564       info_ptr = locate_pdi_sibling (reader, last_die, info_ptr);
16565
16566       /* Back to the top, do it again.  */
16567     }
16568 }
16569
16570 /* Read a minimal amount of information into the minimal die structure.  */
16571
16572 static const gdb_byte *
16573 read_partial_die (const struct die_reader_specs *reader,
16574                   struct partial_die_info *part_die,
16575                   struct abbrev_info *abbrev, unsigned int abbrev_len,
16576                   const gdb_byte *info_ptr)
16577 {
16578   struct dwarf2_cu *cu = reader->cu;
16579   struct objfile *objfile = cu->objfile;
16580   const gdb_byte *buffer = reader->buffer;
16581   unsigned int i;
16582   struct attribute attr;
16583   int has_low_pc_attr = 0;
16584   int has_high_pc_attr = 0;
16585   int high_pc_relative = 0;
16586
16587   memset (part_die, 0, sizeof (struct partial_die_info));
16588
16589   part_die->sect_off = (sect_offset) (info_ptr - buffer);
16590
16591   info_ptr += abbrev_len;
16592
16593   if (abbrev == NULL)
16594     return info_ptr;
16595
16596   part_die->tag = abbrev->tag;
16597   part_die->has_children = abbrev->has_children;
16598
16599   for (i = 0; i < abbrev->num_attrs; ++i)
16600     {
16601       info_ptr = read_attribute (reader, &attr, &abbrev->attrs[i], info_ptr);
16602
16603       /* Store the data if it is of an attribute we want to keep in a
16604          partial symbol table.  */
16605       switch (attr.name)
16606         {
16607         case DW_AT_name:
16608           switch (part_die->tag)
16609             {
16610             case DW_TAG_compile_unit:
16611             case DW_TAG_partial_unit:
16612             case DW_TAG_type_unit:
16613               /* Compilation units have a DW_AT_name that is a filename, not
16614                  a source language identifier.  */
16615             case DW_TAG_enumeration_type:
16616             case DW_TAG_enumerator:
16617               /* These tags always have simple identifiers already; no need
16618                  to canonicalize them.  */
16619               part_die->name = DW_STRING (&attr);
16620               break;
16621             default:
16622               part_die->name
16623                 = dwarf2_canonicalize_name (DW_STRING (&attr), cu,
16624                                             &objfile->per_bfd->storage_obstack);
16625               break;
16626             }
16627           break;
16628         case DW_AT_linkage_name:
16629         case DW_AT_MIPS_linkage_name:
16630           /* Note that both forms of linkage name might appear.  We
16631              assume they will be the same, and we only store the last
16632              one we see.  */
16633           if (cu->language == language_ada)
16634             part_die->name = DW_STRING (&attr);
16635           part_die->linkage_name = DW_STRING (&attr);
16636           break;
16637         case DW_AT_low_pc:
16638           has_low_pc_attr = 1;
16639           part_die->lowpc = attr_value_as_address (&attr);
16640           break;
16641         case DW_AT_high_pc:
16642           has_high_pc_attr = 1;
16643           part_die->highpc = attr_value_as_address (&attr);
16644           if (cu->header.version >= 4 && attr_form_is_constant (&attr))
16645                 high_pc_relative = 1;
16646           break;
16647         case DW_AT_location:
16648           /* Support the .debug_loc offsets.  */
16649           if (attr_form_is_block (&attr))
16650             {
16651                part_die->d.locdesc = DW_BLOCK (&attr);
16652             }
16653           else if (attr_form_is_section_offset (&attr))
16654             {
16655               dwarf2_complex_location_expr_complaint ();
16656             }
16657           else
16658             {
16659               dwarf2_invalid_attrib_class_complaint ("DW_AT_location",
16660                                                      "partial symbol information");
16661             }
16662           break;
16663         case DW_AT_external:
16664           part_die->is_external = DW_UNSND (&attr);
16665           break;
16666         case DW_AT_declaration:
16667           part_die->is_declaration = DW_UNSND (&attr);
16668           break;
16669         case DW_AT_type:
16670           part_die->has_type = 1;
16671           break;
16672         case DW_AT_abstract_origin:
16673         case DW_AT_specification:
16674         case DW_AT_extension:
16675           part_die->has_specification = 1;
16676           part_die->spec_offset = dwarf2_get_ref_die_offset (&attr);
16677           part_die->spec_is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16678                                    || cu->per_cu->is_dwz);
16679           break;
16680         case DW_AT_sibling:
16681           /* Ignore absolute siblings, they might point outside of
16682              the current compile unit.  */
16683           if (attr.form == DW_FORM_ref_addr)
16684             complaint (&symfile_complaints,
16685                        _("ignoring absolute DW_AT_sibling"));
16686           else
16687             {
16688               sect_offset off = dwarf2_get_ref_die_offset (&attr);
16689               const gdb_byte *sibling_ptr = buffer + to_underlying (off);
16690
16691               if (sibling_ptr < info_ptr)
16692                 complaint (&symfile_complaints,
16693                            _("DW_AT_sibling points backwards"));
16694               else if (sibling_ptr > reader->buffer_end)
16695                 dwarf2_section_buffer_overflow_complaint (reader->die_section);
16696               else
16697                 part_die->sibling = sibling_ptr;
16698             }
16699           break;
16700         case DW_AT_byte_size:
16701           part_die->has_byte_size = 1;
16702           break;
16703         case DW_AT_const_value:
16704           part_die->has_const_value = 1;
16705           break;
16706         case DW_AT_calling_convention:
16707           /* DWARF doesn't provide a way to identify a program's source-level
16708              entry point.  DW_AT_calling_convention attributes are only meant
16709              to describe functions' calling conventions.
16710
16711              However, because it's a necessary piece of information in
16712              Fortran, and before DWARF 4 DW_CC_program was the only
16713              piece of debugging information whose definition refers to
16714              a 'main program' at all, several compilers marked Fortran
16715              main programs with DW_CC_program --- even when those
16716              functions use the standard calling conventions.
16717
16718              Although DWARF now specifies a way to provide this
16719              information, we support this practice for backward
16720              compatibility.  */
16721           if (DW_UNSND (&attr) == DW_CC_program
16722               && cu->language == language_fortran)
16723             part_die->main_subprogram = 1;
16724           break;
16725         case DW_AT_inline:
16726           if (DW_UNSND (&attr) == DW_INL_inlined
16727               || DW_UNSND (&attr) == DW_INL_declared_inlined)
16728             part_die->may_be_inlined = 1;
16729           break;
16730
16731         case DW_AT_import:
16732           if (part_die->tag == DW_TAG_imported_unit)
16733             {
16734               part_die->d.sect_off = dwarf2_get_ref_die_offset (&attr);
16735               part_die->is_dwz = (attr.form == DW_FORM_GNU_ref_alt
16736                                   || cu->per_cu->is_dwz);
16737             }
16738           break;
16739
16740         case DW_AT_main_subprogram:
16741           part_die->main_subprogram = DW_UNSND (&attr);
16742           break;
16743
16744         default:
16745           break;
16746         }
16747     }
16748
16749   if (high_pc_relative)
16750     part_die->highpc += part_die->lowpc;
16751
16752   if (has_low_pc_attr && has_high_pc_attr)
16753     {
16754       /* When using the GNU linker, .gnu.linkonce. sections are used to
16755          eliminate duplicate copies of functions and vtables and such.
16756          The linker will arbitrarily choose one and discard the others.
16757          The AT_*_pc values for such functions refer to local labels in
16758          these sections.  If the section from that file was discarded, the
16759          labels are not in the output, so the relocs get a value of 0.
16760          If this is a discarded function, mark the pc bounds as invalid,
16761          so that GDB will ignore it.  */
16762       if (part_die->lowpc == 0 && !dwarf2_per_objfile->has_section_at_zero)
16763         {
16764           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16765
16766           complaint (&symfile_complaints,
16767                      _("DW_AT_low_pc %s is zero "
16768                        "for DIE at 0x%x [in module %s]"),
16769                      paddress (gdbarch, part_die->lowpc),
16770                      to_underlying (part_die->sect_off), objfile_name (objfile));
16771         }
16772       /* dwarf2_get_pc_bounds has also the strict low < high requirement.  */
16773       else if (part_die->lowpc >= part_die->highpc)
16774         {
16775           struct gdbarch *gdbarch = get_objfile_arch (objfile);
16776
16777           complaint (&symfile_complaints,
16778                      _("DW_AT_low_pc %s is not < DW_AT_high_pc %s "
16779                        "for DIE at 0x%x [in module %s]"),
16780                      paddress (gdbarch, part_die->lowpc),
16781                      paddress (gdbarch, part_die->highpc),
16782                      to_underlying (part_die->sect_off),
16783                      objfile_name (objfile));
16784         }
16785       else
16786         part_die->has_pc_info = 1;
16787     }
16788
16789   return info_ptr;
16790 }
16791
16792 /* Find a cached partial DIE at OFFSET in CU.  */
16793
16794 static struct partial_die_info *
16795 find_partial_die_in_comp_unit (sect_offset sect_off, struct dwarf2_cu *cu)
16796 {
16797   struct partial_die_info *lookup_die = NULL;
16798   struct partial_die_info part_die;
16799
16800   part_die.sect_off = sect_off;
16801   lookup_die = ((struct partial_die_info *)
16802                 htab_find_with_hash (cu->partial_dies, &part_die,
16803                                      to_underlying (sect_off)));
16804
16805   return lookup_die;
16806 }
16807
16808 /* Find a partial DIE at OFFSET, which may or may not be in CU,
16809    except in the case of .debug_types DIEs which do not reference
16810    outside their CU (they do however referencing other types via
16811    DW_FORM_ref_sig8).  */
16812
16813 static struct partial_die_info *
16814 find_partial_die (sect_offset sect_off, int offset_in_dwz, struct dwarf2_cu *cu)
16815 {
16816   struct objfile *objfile = cu->objfile;
16817   struct dwarf2_per_cu_data *per_cu = NULL;
16818   struct partial_die_info *pd = NULL;
16819
16820   if (offset_in_dwz == cu->per_cu->is_dwz
16821       && offset_in_cu_p (&cu->header, sect_off))
16822     {
16823       pd = find_partial_die_in_comp_unit (sect_off, cu);
16824       if (pd != NULL)
16825         return pd;
16826       /* We missed recording what we needed.
16827          Load all dies and try again.  */
16828       per_cu = cu->per_cu;
16829     }
16830   else
16831     {
16832       /* TUs don't reference other CUs/TUs (except via type signatures).  */
16833       if (cu->per_cu->is_debug_types)
16834         {
16835           error (_("Dwarf Error: Type Unit at offset 0x%x contains"
16836                    " external reference to offset 0x%x [in module %s].\n"),
16837                  to_underlying (cu->header.sect_off), to_underlying (sect_off),
16838                  bfd_get_filename (objfile->obfd));
16839         }
16840       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
16841                                                  objfile);
16842
16843       if (per_cu->cu == NULL || per_cu->cu->partial_dies == NULL)
16844         load_partial_comp_unit (per_cu);
16845
16846       per_cu->cu->last_used = 0;
16847       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16848     }
16849
16850   /* If we didn't find it, and not all dies have been loaded,
16851      load them all and try again.  */
16852
16853   if (pd == NULL && per_cu->load_all_dies == 0)
16854     {
16855       per_cu->load_all_dies = 1;
16856
16857       /* This is nasty.  When we reread the DIEs, somewhere up the call chain
16858          THIS_CU->cu may already be in use.  So we can't just free it and
16859          replace its DIEs with the ones we read in.  Instead, we leave those
16860          DIEs alone (which can still be in use, e.g. in scan_partial_symbols),
16861          and clobber THIS_CU->cu->partial_dies with the hash table for the new
16862          set.  */
16863       load_partial_comp_unit (per_cu);
16864
16865       pd = find_partial_die_in_comp_unit (sect_off, per_cu->cu);
16866     }
16867
16868   if (pd == NULL)
16869     internal_error (__FILE__, __LINE__,
16870                     _("could not find partial DIE 0x%x "
16871                       "in cache [from module %s]\n"),
16872                     to_underlying (sect_off), bfd_get_filename (objfile->obfd));
16873   return pd;
16874 }
16875
16876 /* See if we can figure out if the class lives in a namespace.  We do
16877    this by looking for a member function; its demangled name will
16878    contain namespace info, if there is any.  */
16879
16880 static void
16881 guess_partial_die_structure_name (struct partial_die_info *struct_pdi,
16882                                   struct dwarf2_cu *cu)
16883 {
16884   /* NOTE: carlton/2003-10-07: Getting the info this way changes
16885      what template types look like, because the demangler
16886      frequently doesn't give the same name as the debug info.  We
16887      could fix this by only using the demangled name to get the
16888      prefix (but see comment in read_structure_type).  */
16889
16890   struct partial_die_info *real_pdi;
16891   struct partial_die_info *child_pdi;
16892
16893   /* If this DIE (this DIE's specification, if any) has a parent, then
16894      we should not do this.  We'll prepend the parent's fully qualified
16895      name when we create the partial symbol.  */
16896
16897   real_pdi = struct_pdi;
16898   while (real_pdi->has_specification)
16899     real_pdi = find_partial_die (real_pdi->spec_offset,
16900                                  real_pdi->spec_is_dwz, cu);
16901
16902   if (real_pdi->die_parent != NULL)
16903     return;
16904
16905   for (child_pdi = struct_pdi->die_child;
16906        child_pdi != NULL;
16907        child_pdi = child_pdi->die_sibling)
16908     {
16909       if (child_pdi->tag == DW_TAG_subprogram
16910           && child_pdi->linkage_name != NULL)
16911         {
16912           char *actual_class_name
16913             = language_class_name_from_physname (cu->language_defn,
16914                                                  child_pdi->linkage_name);
16915           if (actual_class_name != NULL)
16916             {
16917               struct_pdi->name
16918                 = ((const char *)
16919                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
16920                                   actual_class_name,
16921                                   strlen (actual_class_name)));
16922               xfree (actual_class_name);
16923             }
16924           break;
16925         }
16926     }
16927 }
16928
16929 /* Adjust PART_DIE before generating a symbol for it.  This function
16930    may set the is_external flag or change the DIE's name.  */
16931
16932 static void
16933 fixup_partial_die (struct partial_die_info *part_die,
16934                    struct dwarf2_cu *cu)
16935 {
16936   /* Once we've fixed up a die, there's no point in doing so again.
16937      This also avoids a memory leak if we were to call
16938      guess_partial_die_structure_name multiple times.  */
16939   if (part_die->fixup_called)
16940     return;
16941
16942   /* If we found a reference attribute and the DIE has no name, try
16943      to find a name in the referred to DIE.  */
16944
16945   if (part_die->name == NULL && part_die->has_specification)
16946     {
16947       struct partial_die_info *spec_die;
16948
16949       spec_die = find_partial_die (part_die->spec_offset,
16950                                    part_die->spec_is_dwz, cu);
16951
16952       fixup_partial_die (spec_die, cu);
16953
16954       if (spec_die->name)
16955         {
16956           part_die->name = spec_die->name;
16957
16958           /* Copy DW_AT_external attribute if it is set.  */
16959           if (spec_die->is_external)
16960             part_die->is_external = spec_die->is_external;
16961         }
16962     }
16963
16964   /* Set default names for some unnamed DIEs.  */
16965
16966   if (part_die->name == NULL && part_die->tag == DW_TAG_namespace)
16967     part_die->name = CP_ANONYMOUS_NAMESPACE_STR;
16968
16969   /* If there is no parent die to provide a namespace, and there are
16970      children, see if we can determine the namespace from their linkage
16971      name.  */
16972   if (cu->language == language_cplus
16973       && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
16974       && part_die->die_parent == NULL
16975       && part_die->has_children
16976       && (part_die->tag == DW_TAG_class_type
16977           || part_die->tag == DW_TAG_structure_type
16978           || part_die->tag == DW_TAG_union_type))
16979     guess_partial_die_structure_name (part_die, cu);
16980
16981   /* GCC might emit a nameless struct or union that has a linkage
16982      name.  See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
16983   if (part_die->name == NULL
16984       && (part_die->tag == DW_TAG_class_type
16985           || part_die->tag == DW_TAG_interface_type
16986           || part_die->tag == DW_TAG_structure_type
16987           || part_die->tag == DW_TAG_union_type)
16988       && part_die->linkage_name != NULL)
16989     {
16990       char *demangled;
16991
16992       demangled = gdb_demangle (part_die->linkage_name, DMGL_TYPES);
16993       if (demangled)
16994         {
16995           const char *base;
16996
16997           /* Strip any leading namespaces/classes, keep only the base name.
16998              DW_AT_name for named DIEs does not contain the prefixes.  */
16999           base = strrchr (demangled, ':');
17000           if (base && base > demangled && base[-1] == ':')
17001             base++;
17002           else
17003             base = demangled;
17004
17005           part_die->name
17006             = ((const char *)
17007                obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
17008                               base, strlen (base)));
17009           xfree (demangled);
17010         }
17011     }
17012
17013   part_die->fixup_called = 1;
17014 }
17015
17016 /* Read an attribute value described by an attribute form.  */
17017
17018 static const gdb_byte *
17019 read_attribute_value (const struct die_reader_specs *reader,
17020                       struct attribute *attr, unsigned form,
17021                       LONGEST implicit_const, const gdb_byte *info_ptr)
17022 {
17023   struct dwarf2_cu *cu = reader->cu;
17024   struct objfile *objfile = cu->objfile;
17025   struct gdbarch *gdbarch = get_objfile_arch (objfile);
17026   bfd *abfd = reader->abfd;
17027   struct comp_unit_head *cu_header = &cu->header;
17028   unsigned int bytes_read;
17029   struct dwarf_block *blk;
17030
17031   attr->form = (enum dwarf_form) form;
17032   switch (form)
17033     {
17034     case DW_FORM_ref_addr:
17035       if (cu->header.version == 2)
17036         DW_UNSND (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17037       else
17038         DW_UNSND (attr) = read_offset (abfd, info_ptr,
17039                                        &cu->header, &bytes_read);
17040       info_ptr += bytes_read;
17041       break;
17042     case DW_FORM_GNU_ref_alt:
17043       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17044       info_ptr += bytes_read;
17045       break;
17046     case DW_FORM_addr:
17047       DW_ADDR (attr) = read_address (abfd, info_ptr, cu, &bytes_read);
17048       DW_ADDR (attr) = gdbarch_adjust_dwarf2_addr (gdbarch, DW_ADDR (attr));
17049       info_ptr += bytes_read;
17050       break;
17051     case DW_FORM_block2:
17052       blk = dwarf_alloc_block (cu);
17053       blk->size = read_2_bytes (abfd, info_ptr);
17054       info_ptr += 2;
17055       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17056       info_ptr += blk->size;
17057       DW_BLOCK (attr) = blk;
17058       break;
17059     case DW_FORM_block4:
17060       blk = dwarf_alloc_block (cu);
17061       blk->size = read_4_bytes (abfd, info_ptr);
17062       info_ptr += 4;
17063       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17064       info_ptr += blk->size;
17065       DW_BLOCK (attr) = blk;
17066       break;
17067     case DW_FORM_data2:
17068       DW_UNSND (attr) = read_2_bytes (abfd, info_ptr);
17069       info_ptr += 2;
17070       break;
17071     case DW_FORM_data4:
17072       DW_UNSND (attr) = read_4_bytes (abfd, info_ptr);
17073       info_ptr += 4;
17074       break;
17075     case DW_FORM_data8:
17076       DW_UNSND (attr) = read_8_bytes (abfd, info_ptr);
17077       info_ptr += 8;
17078       break;
17079     case DW_FORM_data16:
17080       blk = dwarf_alloc_block (cu);
17081       blk->size = 16;
17082       blk->data = read_n_bytes (abfd, info_ptr, 16);
17083       info_ptr += 16;
17084       DW_BLOCK (attr) = blk;
17085       break;
17086     case DW_FORM_sec_offset:
17087       DW_UNSND (attr) = read_offset (abfd, info_ptr, &cu->header, &bytes_read);
17088       info_ptr += bytes_read;
17089       break;
17090     case DW_FORM_string:
17091       DW_STRING (attr) = read_direct_string (abfd, info_ptr, &bytes_read);
17092       DW_STRING_IS_CANONICAL (attr) = 0;
17093       info_ptr += bytes_read;
17094       break;
17095     case DW_FORM_strp:
17096       if (!cu->per_cu->is_dwz)
17097         {
17098           DW_STRING (attr) = read_indirect_string (abfd, info_ptr, cu_header,
17099                                                    &bytes_read);
17100           DW_STRING_IS_CANONICAL (attr) = 0;
17101           info_ptr += bytes_read;
17102           break;
17103         }
17104       /* FALLTHROUGH */
17105     case DW_FORM_line_strp:
17106       if (!cu->per_cu->is_dwz)
17107         {
17108           DW_STRING (attr) = read_indirect_line_string (abfd, info_ptr,
17109                                                         cu_header, &bytes_read);
17110           DW_STRING_IS_CANONICAL (attr) = 0;
17111           info_ptr += bytes_read;
17112           break;
17113         }
17114       /* FALLTHROUGH */
17115     case DW_FORM_GNU_strp_alt:
17116       {
17117         struct dwz_file *dwz = dwarf2_get_dwz_file ();
17118         LONGEST str_offset = read_offset (abfd, info_ptr, cu_header,
17119                                           &bytes_read);
17120
17121         DW_STRING (attr) = read_indirect_string_from_dwz (dwz, str_offset);
17122         DW_STRING_IS_CANONICAL (attr) = 0;
17123         info_ptr += bytes_read;
17124       }
17125       break;
17126     case DW_FORM_exprloc:
17127     case DW_FORM_block:
17128       blk = dwarf_alloc_block (cu);
17129       blk->size = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17130       info_ptr += bytes_read;
17131       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17132       info_ptr += blk->size;
17133       DW_BLOCK (attr) = blk;
17134       break;
17135     case DW_FORM_block1:
17136       blk = dwarf_alloc_block (cu);
17137       blk->size = read_1_byte (abfd, info_ptr);
17138       info_ptr += 1;
17139       blk->data = read_n_bytes (abfd, info_ptr, blk->size);
17140       info_ptr += blk->size;
17141       DW_BLOCK (attr) = blk;
17142       break;
17143     case DW_FORM_data1:
17144       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17145       info_ptr += 1;
17146       break;
17147     case DW_FORM_flag:
17148       DW_UNSND (attr) = read_1_byte (abfd, info_ptr);
17149       info_ptr += 1;
17150       break;
17151     case DW_FORM_flag_present:
17152       DW_UNSND (attr) = 1;
17153       break;
17154     case DW_FORM_sdata:
17155       DW_SND (attr) = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17156       info_ptr += bytes_read;
17157       break;
17158     case DW_FORM_udata:
17159       DW_UNSND (attr) = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17160       info_ptr += bytes_read;
17161       break;
17162     case DW_FORM_ref1:
17163       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17164                          + read_1_byte (abfd, info_ptr));
17165       info_ptr += 1;
17166       break;
17167     case DW_FORM_ref2:
17168       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17169                          + read_2_bytes (abfd, info_ptr));
17170       info_ptr += 2;
17171       break;
17172     case DW_FORM_ref4:
17173       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17174                          + read_4_bytes (abfd, info_ptr));
17175       info_ptr += 4;
17176       break;
17177     case DW_FORM_ref8:
17178       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17179                          + read_8_bytes (abfd, info_ptr));
17180       info_ptr += 8;
17181       break;
17182     case DW_FORM_ref_sig8:
17183       DW_SIGNATURE (attr) = read_8_bytes (abfd, info_ptr);
17184       info_ptr += 8;
17185       break;
17186     case DW_FORM_ref_udata:
17187       DW_UNSND (attr) = (to_underlying (cu->header.sect_off)
17188                          + read_unsigned_leb128 (abfd, info_ptr, &bytes_read));
17189       info_ptr += bytes_read;
17190       break;
17191     case DW_FORM_indirect:
17192       form = read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17193       info_ptr += bytes_read;
17194       if (form == DW_FORM_implicit_const)
17195         {
17196           implicit_const = read_signed_leb128 (abfd, info_ptr, &bytes_read);
17197           info_ptr += bytes_read;
17198         }
17199       info_ptr = read_attribute_value (reader, attr, form, implicit_const,
17200                                        info_ptr);
17201       break;
17202     case DW_FORM_implicit_const:
17203       DW_SND (attr) = implicit_const;
17204       break;
17205     case DW_FORM_GNU_addr_index:
17206       if (reader->dwo_file == NULL)
17207         {
17208           /* For now flag a hard error.
17209              Later we can turn this into a complaint.  */
17210           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17211                  dwarf_form_name (form),
17212                  bfd_get_filename (abfd));
17213         }
17214       DW_ADDR (attr) = read_addr_index_from_leb128 (cu, info_ptr, &bytes_read);
17215       info_ptr += bytes_read;
17216       break;
17217     case DW_FORM_GNU_str_index:
17218       if (reader->dwo_file == NULL)
17219         {
17220           /* For now flag a hard error.
17221              Later we can turn this into a complaint if warranted.  */
17222           error (_("Dwarf Error: %s found in non-DWO CU [in module %s]"),
17223                  dwarf_form_name (form),
17224                  bfd_get_filename (abfd));
17225         }
17226       {
17227         ULONGEST str_index =
17228           read_unsigned_leb128 (abfd, info_ptr, &bytes_read);
17229
17230         DW_STRING (attr) = read_str_index (reader, str_index);
17231         DW_STRING_IS_CANONICAL (attr) = 0;
17232         info_ptr += bytes_read;
17233       }
17234       break;
17235     default:
17236       error (_("Dwarf Error: Cannot handle %s in DWARF reader [in module %s]"),
17237              dwarf_form_name (form),
17238              bfd_get_filename (abfd));
17239     }
17240
17241   /* Super hack.  */
17242   if (cu->per_cu->is_dwz && attr_form_is_ref (attr))
17243     attr->form = DW_FORM_GNU_ref_alt;
17244
17245   /* We have seen instances where the compiler tried to emit a byte
17246      size attribute of -1 which ended up being encoded as an unsigned
17247      0xffffffff.  Although 0xffffffff is technically a valid size value,
17248      an object of this size seems pretty unlikely so we can relatively
17249      safely treat these cases as if the size attribute was invalid and
17250      treat them as zero by default.  */
17251   if (attr->name == DW_AT_byte_size
17252       && form == DW_FORM_data4
17253       && DW_UNSND (attr) >= 0xffffffff)
17254     {
17255       complaint
17256         (&symfile_complaints,
17257          _("Suspicious DW_AT_byte_size value treated as zero instead of %s"),
17258          hex_string (DW_UNSND (attr)));
17259       DW_UNSND (attr) = 0;
17260     }
17261
17262   return info_ptr;
17263 }
17264
17265 /* Read an attribute described by an abbreviated attribute.  */
17266
17267 static const gdb_byte *
17268 read_attribute (const struct die_reader_specs *reader,
17269                 struct attribute *attr, struct attr_abbrev *abbrev,
17270                 const gdb_byte *info_ptr)
17271 {
17272   attr->name = abbrev->name;
17273   return read_attribute_value (reader, attr, abbrev->form,
17274                                abbrev->implicit_const, info_ptr);
17275 }
17276
17277 /* Read dwarf information from a buffer.  */
17278
17279 static unsigned int
17280 read_1_byte (bfd *abfd, const gdb_byte *buf)
17281 {
17282   return bfd_get_8 (abfd, buf);
17283 }
17284
17285 static int
17286 read_1_signed_byte (bfd *abfd, const gdb_byte *buf)
17287 {
17288   return bfd_get_signed_8 (abfd, buf);
17289 }
17290
17291 static unsigned int
17292 read_2_bytes (bfd *abfd, const gdb_byte *buf)
17293 {
17294   return bfd_get_16 (abfd, buf);
17295 }
17296
17297 static int
17298 read_2_signed_bytes (bfd *abfd, const gdb_byte *buf)
17299 {
17300   return bfd_get_signed_16 (abfd, buf);
17301 }
17302
17303 static unsigned int
17304 read_4_bytes (bfd *abfd, const gdb_byte *buf)
17305 {
17306   return bfd_get_32 (abfd, buf);
17307 }
17308
17309 static int
17310 read_4_signed_bytes (bfd *abfd, const gdb_byte *buf)
17311 {
17312   return bfd_get_signed_32 (abfd, buf);
17313 }
17314
17315 static ULONGEST
17316 read_8_bytes (bfd *abfd, const gdb_byte *buf)
17317 {
17318   return bfd_get_64 (abfd, buf);
17319 }
17320
17321 static CORE_ADDR
17322 read_address (bfd *abfd, const gdb_byte *buf, struct dwarf2_cu *cu,
17323               unsigned int *bytes_read)
17324 {
17325   struct comp_unit_head *cu_header = &cu->header;
17326   CORE_ADDR retval = 0;
17327
17328   if (cu_header->signed_addr_p)
17329     {
17330       switch (cu_header->addr_size)
17331         {
17332         case 2:
17333           retval = bfd_get_signed_16 (abfd, buf);
17334           break;
17335         case 4:
17336           retval = bfd_get_signed_32 (abfd, buf);
17337           break;
17338         case 8:
17339           retval = bfd_get_signed_64 (abfd, buf);
17340           break;
17341         default:
17342           internal_error (__FILE__, __LINE__,
17343                           _("read_address: bad switch, signed [in module %s]"),
17344                           bfd_get_filename (abfd));
17345         }
17346     }
17347   else
17348     {
17349       switch (cu_header->addr_size)
17350         {
17351         case 2:
17352           retval = bfd_get_16 (abfd, buf);
17353           break;
17354         case 4:
17355           retval = bfd_get_32 (abfd, buf);
17356           break;
17357         case 8:
17358           retval = bfd_get_64 (abfd, buf);
17359           break;
17360         default:
17361           internal_error (__FILE__, __LINE__,
17362                           _("read_address: bad switch, "
17363                             "unsigned [in module %s]"),
17364                           bfd_get_filename (abfd));
17365         }
17366     }
17367
17368   *bytes_read = cu_header->addr_size;
17369   return retval;
17370 }
17371
17372 /* Read the initial length from a section.  The (draft) DWARF 3
17373    specification allows the initial length to take up either 4 bytes
17374    or 12 bytes.  If the first 4 bytes are 0xffffffff, then the next 8
17375    bytes describe the length and all offsets will be 8 bytes in length
17376    instead of 4.
17377
17378    An older, non-standard 64-bit format is also handled by this
17379    function.  The older format in question stores the initial length
17380    as an 8-byte quantity without an escape value.  Lengths greater
17381    than 2^32 aren't very common which means that the initial 4 bytes
17382    is almost always zero.  Since a length value of zero doesn't make
17383    sense for the 32-bit format, this initial zero can be considered to
17384    be an escape value which indicates the presence of the older 64-bit
17385    format.  As written, the code can't detect (old format) lengths
17386    greater than 4GB.  If it becomes necessary to handle lengths
17387    somewhat larger than 4GB, we could allow other small values (such
17388    as the non-sensical values of 1, 2, and 3) to also be used as
17389    escape values indicating the presence of the old format.
17390
17391    The value returned via bytes_read should be used to increment the
17392    relevant pointer after calling read_initial_length().
17393
17394    [ Note:  read_initial_length() and read_offset() are based on the
17395      document entitled "DWARF Debugging Information Format", revision
17396      3, draft 8, dated November 19, 2001.  This document was obtained
17397      from:
17398
17399         http://reality.sgiweb.org/davea/dwarf3-draft8-011125.pdf
17400
17401      This document is only a draft and is subject to change.  (So beware.)
17402
17403      Details regarding the older, non-standard 64-bit format were
17404      determined empirically by examining 64-bit ELF files produced by
17405      the SGI toolchain on an IRIX 6.5 machine.
17406
17407      - Kevin, July 16, 2002
17408    ] */
17409
17410 static LONGEST
17411 read_initial_length (bfd *abfd, const gdb_byte *buf, unsigned int *bytes_read)
17412 {
17413   LONGEST length = bfd_get_32 (abfd, buf);
17414
17415   if (length == 0xffffffff)
17416     {
17417       length = bfd_get_64 (abfd, buf + 4);
17418       *bytes_read = 12;
17419     }
17420   else if (length == 0)
17421     {
17422       /* Handle the (non-standard) 64-bit DWARF2 format used by IRIX.  */
17423       length = bfd_get_64 (abfd, buf);
17424       *bytes_read = 8;
17425     }
17426   else
17427     {
17428       *bytes_read = 4;
17429     }
17430
17431   return length;
17432 }
17433
17434 /* Cover function for read_initial_length.
17435    Returns the length of the object at BUF, and stores the size of the
17436    initial length in *BYTES_READ and stores the size that offsets will be in
17437    *OFFSET_SIZE.
17438    If the initial length size is not equivalent to that specified in
17439    CU_HEADER then issue a complaint.
17440    This is useful when reading non-comp-unit headers.  */
17441
17442 static LONGEST
17443 read_checked_initial_length_and_offset (bfd *abfd, const gdb_byte *buf,
17444                                         const struct comp_unit_head *cu_header,
17445                                         unsigned int *bytes_read,
17446                                         unsigned int *offset_size)
17447 {
17448   LONGEST length = read_initial_length (abfd, buf, bytes_read);
17449
17450   gdb_assert (cu_header->initial_length_size == 4
17451               || cu_header->initial_length_size == 8
17452               || cu_header->initial_length_size == 12);
17453
17454   if (cu_header->initial_length_size != *bytes_read)
17455     complaint (&symfile_complaints,
17456                _("intermixed 32-bit and 64-bit DWARF sections"));
17457
17458   *offset_size = (*bytes_read == 4) ? 4 : 8;
17459   return length;
17460 }
17461
17462 /* Read an offset from the data stream.  The size of the offset is
17463    given by cu_header->offset_size.  */
17464
17465 static LONGEST
17466 read_offset (bfd *abfd, const gdb_byte *buf,
17467              const struct comp_unit_head *cu_header,
17468              unsigned int *bytes_read)
17469 {
17470   LONGEST offset = read_offset_1 (abfd, buf, cu_header->offset_size);
17471
17472   *bytes_read = cu_header->offset_size;
17473   return offset;
17474 }
17475
17476 /* Read an offset from the data stream.  */
17477
17478 static LONGEST
17479 read_offset_1 (bfd *abfd, const gdb_byte *buf, unsigned int offset_size)
17480 {
17481   LONGEST retval = 0;
17482
17483   switch (offset_size)
17484     {
17485     case 4:
17486       retval = bfd_get_32 (abfd, buf);
17487       break;
17488     case 8:
17489       retval = bfd_get_64 (abfd, buf);
17490       break;
17491     default:
17492       internal_error (__FILE__, __LINE__,
17493                       _("read_offset_1: bad switch [in module %s]"),
17494                       bfd_get_filename (abfd));
17495     }
17496
17497   return retval;
17498 }
17499
17500 static const gdb_byte *
17501 read_n_bytes (bfd *abfd, const gdb_byte *buf, unsigned int size)
17502 {
17503   /* If the size of a host char is 8 bits, we can return a pointer
17504      to the buffer, otherwise we have to copy the data to a buffer
17505      allocated on the temporary obstack.  */
17506   gdb_assert (HOST_CHAR_BIT == 8);
17507   return buf;
17508 }
17509
17510 static const char *
17511 read_direct_string (bfd *abfd, const gdb_byte *buf,
17512                     unsigned int *bytes_read_ptr)
17513 {
17514   /* If the size of a host char is 8 bits, we can return a pointer
17515      to the string, otherwise we have to copy the string to a buffer
17516      allocated on the temporary obstack.  */
17517   gdb_assert (HOST_CHAR_BIT == 8);
17518   if (*buf == '\0')
17519     {
17520       *bytes_read_ptr = 1;
17521       return NULL;
17522     }
17523   *bytes_read_ptr = strlen ((const char *) buf) + 1;
17524   return (const char *) buf;
17525 }
17526
17527 /* Return pointer to string at section SECT offset STR_OFFSET with error
17528    reporting strings FORM_NAME and SECT_NAME.  */
17529
17530 static const char *
17531 read_indirect_string_at_offset_from (bfd *abfd, LONGEST str_offset,
17532                                      struct dwarf2_section_info *sect,
17533                                      const char *form_name,
17534                                      const char *sect_name)
17535 {
17536   dwarf2_read_section (dwarf2_per_objfile->objfile, sect);
17537   if (sect->buffer == NULL)
17538     error (_("%s used without %s section [in module %s]"),
17539            form_name, sect_name, bfd_get_filename (abfd));
17540   if (str_offset >= sect->size)
17541     error (_("%s pointing outside of %s section [in module %s]"),
17542            form_name, sect_name, bfd_get_filename (abfd));
17543   gdb_assert (HOST_CHAR_BIT == 8);
17544   if (sect->buffer[str_offset] == '\0')
17545     return NULL;
17546   return (const char *) (sect->buffer + str_offset);
17547 }
17548
17549 /* Return pointer to string at .debug_str offset STR_OFFSET.  */
17550
17551 static const char *
17552 read_indirect_string_at_offset (bfd *abfd, LONGEST str_offset)
17553 {
17554   return read_indirect_string_at_offset_from (abfd, str_offset,
17555                                               &dwarf2_per_objfile->str,
17556                                               "DW_FORM_strp", ".debug_str");
17557 }
17558
17559 /* Return pointer to string at .debug_line_str offset STR_OFFSET.  */
17560
17561 static const char *
17562 read_indirect_line_string_at_offset (bfd *abfd, LONGEST str_offset)
17563 {
17564   return read_indirect_string_at_offset_from (abfd, str_offset,
17565                                               &dwarf2_per_objfile->line_str,
17566                                               "DW_FORM_line_strp",
17567                                               ".debug_line_str");
17568 }
17569
17570 /* Read a string at offset STR_OFFSET in the .debug_str section from
17571    the .dwz file DWZ.  Throw an error if the offset is too large.  If
17572    the string consists of a single NUL byte, return NULL; otherwise
17573    return a pointer to the string.  */
17574
17575 static const char *
17576 read_indirect_string_from_dwz (struct dwz_file *dwz, LONGEST str_offset)
17577 {
17578   dwarf2_read_section (dwarf2_per_objfile->objfile, &dwz->str);
17579
17580   if (dwz->str.buffer == NULL)
17581     error (_("DW_FORM_GNU_strp_alt used without .debug_str "
17582              "section [in module %s]"),
17583            bfd_get_filename (dwz->dwz_bfd));
17584   if (str_offset >= dwz->str.size)
17585     error (_("DW_FORM_GNU_strp_alt pointing outside of "
17586              ".debug_str section [in module %s]"),
17587            bfd_get_filename (dwz->dwz_bfd));
17588   gdb_assert (HOST_CHAR_BIT == 8);
17589   if (dwz->str.buffer[str_offset] == '\0')
17590     return NULL;
17591   return (const char *) (dwz->str.buffer + str_offset);
17592 }
17593
17594 /* Return pointer to string at .debug_str offset as read from BUF.
17595    BUF is assumed to be in a compilation unit described by CU_HEADER.
17596    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17597
17598 static const char *
17599 read_indirect_string (bfd *abfd, const gdb_byte *buf,
17600                       const struct comp_unit_head *cu_header,
17601                       unsigned int *bytes_read_ptr)
17602 {
17603   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17604
17605   return read_indirect_string_at_offset (abfd, str_offset);
17606 }
17607
17608 /* Return pointer to string at .debug_line_str offset as read from BUF.
17609    BUF is assumed to be in a compilation unit described by CU_HEADER.
17610    Return *BYTES_READ_PTR count of bytes read from BUF.  */
17611
17612 static const char *
17613 read_indirect_line_string (bfd *abfd, const gdb_byte *buf,
17614                            const struct comp_unit_head *cu_header,
17615                            unsigned int *bytes_read_ptr)
17616 {
17617   LONGEST str_offset = read_offset (abfd, buf, cu_header, bytes_read_ptr);
17618
17619   return read_indirect_line_string_at_offset (abfd, str_offset);
17620 }
17621
17622 ULONGEST
17623 read_unsigned_leb128 (bfd *abfd, const gdb_byte *buf,
17624                           unsigned int *bytes_read_ptr)
17625 {
17626   ULONGEST result;
17627   unsigned int num_read;
17628   int shift;
17629   unsigned char byte;
17630
17631   result = 0;
17632   shift = 0;
17633   num_read = 0;
17634   while (1)
17635     {
17636       byte = bfd_get_8 (abfd, buf);
17637       buf++;
17638       num_read++;
17639       result |= ((ULONGEST) (byte & 127) << shift);
17640       if ((byte & 128) == 0)
17641         {
17642           break;
17643         }
17644       shift += 7;
17645     }
17646   *bytes_read_ptr = num_read;
17647   return result;
17648 }
17649
17650 static LONGEST
17651 read_signed_leb128 (bfd *abfd, const gdb_byte *buf,
17652                     unsigned int *bytes_read_ptr)
17653 {
17654   LONGEST result;
17655   int shift, num_read;
17656   unsigned char byte;
17657
17658   result = 0;
17659   shift = 0;
17660   num_read = 0;
17661   while (1)
17662     {
17663       byte = bfd_get_8 (abfd, buf);
17664       buf++;
17665       num_read++;
17666       result |= ((LONGEST) (byte & 127) << shift);
17667       shift += 7;
17668       if ((byte & 128) == 0)
17669         {
17670           break;
17671         }
17672     }
17673   if ((shift < 8 * sizeof (result)) && (byte & 0x40))
17674     result |= -(((LONGEST) 1) << shift);
17675   *bytes_read_ptr = num_read;
17676   return result;
17677 }
17678
17679 /* Given index ADDR_INDEX in .debug_addr, fetch the value.
17680    ADDR_BASE is the DW_AT_GNU_addr_base attribute or zero.
17681    ADDR_SIZE is the size of addresses from the CU header.  */
17682
17683 static CORE_ADDR
17684 read_addr_index_1 (unsigned int addr_index, ULONGEST addr_base, int addr_size)
17685 {
17686   struct objfile *objfile = dwarf2_per_objfile->objfile;
17687   bfd *abfd = objfile->obfd;
17688   const gdb_byte *info_ptr;
17689
17690   dwarf2_read_section (objfile, &dwarf2_per_objfile->addr);
17691   if (dwarf2_per_objfile->addr.buffer == NULL)
17692     error (_("DW_FORM_addr_index used without .debug_addr section [in module %s]"),
17693            objfile_name (objfile));
17694   if (addr_base + addr_index * addr_size >= dwarf2_per_objfile->addr.size)
17695     error (_("DW_FORM_addr_index pointing outside of "
17696              ".debug_addr section [in module %s]"),
17697            objfile_name (objfile));
17698   info_ptr = (dwarf2_per_objfile->addr.buffer
17699               + addr_base + addr_index * addr_size);
17700   if (addr_size == 4)
17701     return bfd_get_32 (abfd, info_ptr);
17702   else
17703     return bfd_get_64 (abfd, info_ptr);
17704 }
17705
17706 /* Given index ADDR_INDEX in .debug_addr, fetch the value.  */
17707
17708 static CORE_ADDR
17709 read_addr_index (struct dwarf2_cu *cu, unsigned int addr_index)
17710 {
17711   return read_addr_index_1 (addr_index, cu->addr_base, cu->header.addr_size);
17712 }
17713
17714 /* Given a pointer to an leb128 value, fetch the value from .debug_addr.  */
17715
17716 static CORE_ADDR
17717 read_addr_index_from_leb128 (struct dwarf2_cu *cu, const gdb_byte *info_ptr,
17718                              unsigned int *bytes_read)
17719 {
17720   bfd *abfd = cu->objfile->obfd;
17721   unsigned int addr_index = read_unsigned_leb128 (abfd, info_ptr, bytes_read);
17722
17723   return read_addr_index (cu, addr_index);
17724 }
17725
17726 /* Data structure to pass results from dwarf2_read_addr_index_reader
17727    back to dwarf2_read_addr_index.  */
17728
17729 struct dwarf2_read_addr_index_data
17730 {
17731   ULONGEST addr_base;
17732   int addr_size;
17733 };
17734
17735 /* die_reader_func for dwarf2_read_addr_index.  */
17736
17737 static void
17738 dwarf2_read_addr_index_reader (const struct die_reader_specs *reader,
17739                                const gdb_byte *info_ptr,
17740                                struct die_info *comp_unit_die,
17741                                int has_children,
17742                                void *data)
17743 {
17744   struct dwarf2_cu *cu = reader->cu;
17745   struct dwarf2_read_addr_index_data *aidata =
17746     (struct dwarf2_read_addr_index_data *) data;
17747
17748   aidata->addr_base = cu->addr_base;
17749   aidata->addr_size = cu->header.addr_size;
17750 }
17751
17752 /* Given an index in .debug_addr, fetch the value.
17753    NOTE: This can be called during dwarf expression evaluation,
17754    long after the debug information has been read, and thus per_cu->cu
17755    may no longer exist.  */
17756
17757 CORE_ADDR
17758 dwarf2_read_addr_index (struct dwarf2_per_cu_data *per_cu,
17759                         unsigned int addr_index)
17760 {
17761   struct objfile *objfile = per_cu->objfile;
17762   struct dwarf2_cu *cu = per_cu->cu;
17763   ULONGEST addr_base;
17764   int addr_size;
17765
17766   /* This is intended to be called from outside this file.  */
17767   dw2_setup (objfile);
17768
17769   /* We need addr_base and addr_size.
17770      If we don't have PER_CU->cu, we have to get it.
17771      Nasty, but the alternative is storing the needed info in PER_CU,
17772      which at this point doesn't seem justified: it's not clear how frequently
17773      it would get used and it would increase the size of every PER_CU.
17774      Entry points like dwarf2_per_cu_addr_size do a similar thing
17775      so we're not in uncharted territory here.
17776      Alas we need to be a bit more complicated as addr_base is contained
17777      in the DIE.
17778
17779      We don't need to read the entire CU(/TU).
17780      We just need the header and top level die.
17781
17782      IWBN to use the aging mechanism to let us lazily later discard the CU.
17783      For now we skip this optimization.  */
17784
17785   if (cu != NULL)
17786     {
17787       addr_base = cu->addr_base;
17788       addr_size = cu->header.addr_size;
17789     }
17790   else
17791     {
17792       struct dwarf2_read_addr_index_data aidata;
17793
17794       /* Note: We can't use init_cutu_and_read_dies_simple here,
17795          we need addr_base.  */
17796       init_cutu_and_read_dies (per_cu, NULL, 0, 0,
17797                                dwarf2_read_addr_index_reader, &aidata);
17798       addr_base = aidata.addr_base;
17799       addr_size = aidata.addr_size;
17800     }
17801
17802   return read_addr_index_1 (addr_index, addr_base, addr_size);
17803 }
17804
17805 /* Given a DW_FORM_GNU_str_index, fetch the string.
17806    This is only used by the Fission support.  */
17807
17808 static const char *
17809 read_str_index (const struct die_reader_specs *reader, ULONGEST str_index)
17810 {
17811   struct objfile *objfile = dwarf2_per_objfile->objfile;
17812   const char *objf_name = objfile_name (objfile);
17813   bfd *abfd = objfile->obfd;
17814   struct dwarf2_cu *cu = reader->cu;
17815   struct dwarf2_section_info *str_section = &reader->dwo_file->sections.str;
17816   struct dwarf2_section_info *str_offsets_section =
17817     &reader->dwo_file->sections.str_offsets;
17818   const gdb_byte *info_ptr;
17819   ULONGEST str_offset;
17820   static const char form_name[] = "DW_FORM_GNU_str_index";
17821
17822   dwarf2_read_section (objfile, str_section);
17823   dwarf2_read_section (objfile, str_offsets_section);
17824   if (str_section->buffer == NULL)
17825     error (_("%s used without .debug_str.dwo section"
17826              " in CU at offset 0x%x [in module %s]"),
17827            form_name, to_underlying (cu->header.sect_off), objf_name);
17828   if (str_offsets_section->buffer == NULL)
17829     error (_("%s used without .debug_str_offsets.dwo section"
17830              " in CU at offset 0x%x [in module %s]"),
17831            form_name, to_underlying (cu->header.sect_off), objf_name);
17832   if (str_index * cu->header.offset_size >= str_offsets_section->size)
17833     error (_("%s pointing outside of .debug_str_offsets.dwo"
17834              " section in CU at offset 0x%x [in module %s]"),
17835            form_name, to_underlying (cu->header.sect_off), objf_name);
17836   info_ptr = (str_offsets_section->buffer
17837               + str_index * cu->header.offset_size);
17838   if (cu->header.offset_size == 4)
17839     str_offset = bfd_get_32 (abfd, info_ptr);
17840   else
17841     str_offset = bfd_get_64 (abfd, info_ptr);
17842   if (str_offset >= str_section->size)
17843     error (_("Offset from %s pointing outside of"
17844              " .debug_str.dwo section in CU at offset 0x%x [in module %s]"),
17845            form_name, to_underlying (cu->header.sect_off), objf_name);
17846   return (const char *) (str_section->buffer + str_offset);
17847 }
17848
17849 /* Return the length of an LEB128 number in BUF.  */
17850
17851 static int
17852 leb128_size (const gdb_byte *buf)
17853 {
17854   const gdb_byte *begin = buf;
17855   gdb_byte byte;
17856
17857   while (1)
17858     {
17859       byte = *buf++;
17860       if ((byte & 128) == 0)
17861         return buf - begin;
17862     }
17863 }
17864
17865 static void
17866 set_cu_language (unsigned int lang, struct dwarf2_cu *cu)
17867 {
17868   switch (lang)
17869     {
17870     case DW_LANG_C89:
17871     case DW_LANG_C99:
17872     case DW_LANG_C11:
17873     case DW_LANG_C:
17874     case DW_LANG_UPC:
17875       cu->language = language_c;
17876       break;
17877     case DW_LANG_Java:
17878     case DW_LANG_C_plus_plus:
17879     case DW_LANG_C_plus_plus_11:
17880     case DW_LANG_C_plus_plus_14:
17881       cu->language = language_cplus;
17882       break;
17883     case DW_LANG_D:
17884       cu->language = language_d;
17885       break;
17886     case DW_LANG_Fortran77:
17887     case DW_LANG_Fortran90:
17888     case DW_LANG_Fortran95:
17889     case DW_LANG_Fortran03:
17890     case DW_LANG_Fortran08:
17891       cu->language = language_fortran;
17892       break;
17893     case DW_LANG_Go:
17894       cu->language = language_go;
17895       break;
17896     case DW_LANG_Mips_Assembler:
17897       cu->language = language_asm;
17898       break;
17899     case DW_LANG_Ada83:
17900     case DW_LANG_Ada95:
17901       cu->language = language_ada;
17902       break;
17903     case DW_LANG_Modula2:
17904       cu->language = language_m2;
17905       break;
17906     case DW_LANG_Pascal83:
17907       cu->language = language_pascal;
17908       break;
17909     case DW_LANG_ObjC:
17910       cu->language = language_objc;
17911       break;
17912     case DW_LANG_Rust:
17913     case DW_LANG_Rust_old:
17914       cu->language = language_rust;
17915       break;
17916     case DW_LANG_Cobol74:
17917     case DW_LANG_Cobol85:
17918     default:
17919       cu->language = language_minimal;
17920       break;
17921     }
17922   cu->language_defn = language_def (cu->language);
17923 }
17924
17925 /* Return the named attribute or NULL if not there.  */
17926
17927 static struct attribute *
17928 dwarf2_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17929 {
17930   for (;;)
17931     {
17932       unsigned int i;
17933       struct attribute *spec = NULL;
17934
17935       for (i = 0; i < die->num_attrs; ++i)
17936         {
17937           if (die->attrs[i].name == name)
17938             return &die->attrs[i];
17939           if (die->attrs[i].name == DW_AT_specification
17940               || die->attrs[i].name == DW_AT_abstract_origin)
17941             spec = &die->attrs[i];
17942         }
17943
17944       if (!spec)
17945         break;
17946
17947       die = follow_die_ref (die, spec, &cu);
17948     }
17949
17950   return NULL;
17951 }
17952
17953 /* Return the named attribute or NULL if not there,
17954    but do not follow DW_AT_specification, etc.
17955    This is for use in contexts where we're reading .debug_types dies.
17956    Following DW_AT_specification, DW_AT_abstract_origin will take us
17957    back up the chain, and we want to go down.  */
17958
17959 static struct attribute *
17960 dwarf2_attr_no_follow (struct die_info *die, unsigned int name)
17961 {
17962   unsigned int i;
17963
17964   for (i = 0; i < die->num_attrs; ++i)
17965     if (die->attrs[i].name == name)
17966       return &die->attrs[i];
17967
17968   return NULL;
17969 }
17970
17971 /* Return the string associated with a string-typed attribute, or NULL if it
17972    is either not found or is of an incorrect type.  */
17973
17974 static const char *
17975 dwarf2_string_attr (struct die_info *die, unsigned int name, struct dwarf2_cu *cu)
17976 {
17977   struct attribute *attr;
17978   const char *str = NULL;
17979
17980   attr = dwarf2_attr (die, name, cu);
17981
17982   if (attr != NULL)
17983     {
17984       if (attr->form == DW_FORM_strp || attr->form == DW_FORM_line_strp
17985           || attr->form == DW_FORM_string
17986           || attr->form == DW_FORM_GNU_str_index
17987           || attr->form == DW_FORM_GNU_strp_alt)
17988         str = DW_STRING (attr);
17989       else
17990         complaint (&symfile_complaints,
17991                    _("string type expected for attribute %s for "
17992                      "DIE at 0x%x in module %s"),
17993                    dwarf_attr_name (name), to_underlying (die->sect_off),
17994                    objfile_name (cu->objfile));
17995     }
17996
17997   return str;
17998 }
17999
18000 /* Return non-zero iff the attribute NAME is defined for the given DIE,
18001    and holds a non-zero value.  This function should only be used for
18002    DW_FORM_flag or DW_FORM_flag_present attributes.  */
18003
18004 static int
18005 dwarf2_flag_true_p (struct die_info *die, unsigned name, struct dwarf2_cu *cu)
18006 {
18007   struct attribute *attr = dwarf2_attr (die, name, cu);
18008
18009   return (attr && DW_UNSND (attr));
18010 }
18011
18012 static int
18013 die_is_declaration (struct die_info *die, struct dwarf2_cu *cu)
18014 {
18015   /* A DIE is a declaration if it has a DW_AT_declaration attribute
18016      which value is non-zero.  However, we have to be careful with
18017      DIEs having a DW_AT_specification attribute, because dwarf2_attr()
18018      (via dwarf2_flag_true_p) follows this attribute.  So we may
18019      end up accidently finding a declaration attribute that belongs
18020      to a different DIE referenced by the specification attribute,
18021      even though the given DIE does not have a declaration attribute.  */
18022   return (dwarf2_flag_true_p (die, DW_AT_declaration, cu)
18023           && dwarf2_attr (die, DW_AT_specification, cu) == NULL);
18024 }
18025
18026 /* Return the die giving the specification for DIE, if there is
18027    one.  *SPEC_CU is the CU containing DIE on input, and the CU
18028    containing the return value on output.  If there is no
18029    specification, but there is an abstract origin, that is
18030    returned.  */
18031
18032 static struct die_info *
18033 die_specification (struct die_info *die, struct dwarf2_cu **spec_cu)
18034 {
18035   struct attribute *spec_attr = dwarf2_attr (die, DW_AT_specification,
18036                                              *spec_cu);
18037
18038   if (spec_attr == NULL)
18039     spec_attr = dwarf2_attr (die, DW_AT_abstract_origin, *spec_cu);
18040
18041   if (spec_attr == NULL)
18042     return NULL;
18043   else
18044     return follow_die_ref (die, spec_attr, spec_cu);
18045 }
18046
18047 /* Stub for free_line_header to match void * callback types.  */
18048
18049 static void
18050 free_line_header_voidp (void *arg)
18051 {
18052   struct line_header *lh = (struct line_header *) arg;
18053
18054   delete lh;
18055 }
18056
18057 void
18058 line_header::add_include_dir (const char *include_dir)
18059 {
18060   if (dwarf_line_debug >= 2)
18061     fprintf_unfiltered (gdb_stdlog, "Adding dir %zu: %s\n",
18062                         include_dirs.size () + 1, include_dir);
18063
18064   include_dirs.push_back (include_dir);
18065 }
18066
18067 void
18068 line_header::add_file_name (const char *name,
18069                             dir_index d_index,
18070                             unsigned int mod_time,
18071                             unsigned int length)
18072 {
18073   if (dwarf_line_debug >= 2)
18074     fprintf_unfiltered (gdb_stdlog, "Adding file %u: %s\n",
18075                         (unsigned) file_names.size () + 1, name);
18076
18077   file_names.emplace_back (name, d_index, mod_time, length);
18078 }
18079
18080 /* A convenience function to find the proper .debug_line section for a CU.  */
18081
18082 static struct dwarf2_section_info *
18083 get_debug_line_section (struct dwarf2_cu *cu)
18084 {
18085   struct dwarf2_section_info *section;
18086
18087   /* For TUs in DWO files, the DW_AT_stmt_list attribute lives in the
18088      DWO file.  */
18089   if (cu->dwo_unit && cu->per_cu->is_debug_types)
18090     section = &cu->dwo_unit->dwo_file->sections.line;
18091   else if (cu->per_cu->is_dwz)
18092     {
18093       struct dwz_file *dwz = dwarf2_get_dwz_file ();
18094
18095       section = &dwz->line;
18096     }
18097   else
18098     section = &dwarf2_per_objfile->line;
18099
18100   return section;
18101 }
18102
18103 /* Read directory or file name entry format, starting with byte of
18104    format count entries, ULEB128 pairs of entry formats, ULEB128 of
18105    entries count and the entries themselves in the described entry
18106    format.  */
18107
18108 static void
18109 read_formatted_entries (bfd *abfd, const gdb_byte **bufp,
18110                         struct line_header *lh,
18111                         const struct comp_unit_head *cu_header,
18112                         void (*callback) (struct line_header *lh,
18113                                           const char *name,
18114                                           dir_index d_index,
18115                                           unsigned int mod_time,
18116                                           unsigned int length))
18117 {
18118   gdb_byte format_count, formati;
18119   ULONGEST data_count, datai;
18120   const gdb_byte *buf = *bufp;
18121   const gdb_byte *format_header_data;
18122   int i;
18123   unsigned int bytes_read;
18124
18125   format_count = read_1_byte (abfd, buf);
18126   buf += 1;
18127   format_header_data = buf;
18128   for (formati = 0; formati < format_count; formati++)
18129     {
18130       read_unsigned_leb128 (abfd, buf, &bytes_read);
18131       buf += bytes_read;
18132       read_unsigned_leb128 (abfd, buf, &bytes_read);
18133       buf += bytes_read;
18134     }
18135
18136   data_count = read_unsigned_leb128 (abfd, buf, &bytes_read);
18137   buf += bytes_read;
18138   for (datai = 0; datai < data_count; datai++)
18139     {
18140       const gdb_byte *format = format_header_data;
18141       struct file_entry fe;
18142
18143       for (formati = 0; formati < format_count; formati++)
18144         {
18145           ULONGEST content_type = read_unsigned_leb128 (abfd, format, &bytes_read);
18146           format += bytes_read;
18147
18148           ULONGEST form  = read_unsigned_leb128 (abfd, format, &bytes_read);
18149           format += bytes_read;
18150
18151           gdb::optional<const char *> string;
18152           gdb::optional<unsigned int> uint;
18153
18154           switch (form)
18155             {
18156             case DW_FORM_string:
18157               string.emplace (read_direct_string (abfd, buf, &bytes_read));
18158               buf += bytes_read;
18159               break;
18160
18161             case DW_FORM_line_strp:
18162               string.emplace (read_indirect_line_string (abfd, buf,
18163                                                          cu_header,
18164                                                          &bytes_read));
18165               buf += bytes_read;
18166               break;
18167
18168             case DW_FORM_data1:
18169               uint.emplace (read_1_byte (abfd, buf));
18170               buf += 1;
18171               break;
18172
18173             case DW_FORM_data2:
18174               uint.emplace (read_2_bytes (abfd, buf));
18175               buf += 2;
18176               break;
18177
18178             case DW_FORM_data4:
18179               uint.emplace (read_4_bytes (abfd, buf));
18180               buf += 4;
18181               break;
18182
18183             case DW_FORM_data8:
18184               uint.emplace (read_8_bytes (abfd, buf));
18185               buf += 8;
18186               break;
18187
18188             case DW_FORM_udata:
18189               uint.emplace (read_unsigned_leb128 (abfd, buf, &bytes_read));
18190               buf += bytes_read;
18191               break;
18192
18193             case DW_FORM_block:
18194               /* It is valid only for DW_LNCT_timestamp which is ignored by
18195                  current GDB.  */
18196               break;
18197             }
18198
18199           switch (content_type)
18200             {
18201             case DW_LNCT_path:
18202               if (string.has_value ())
18203                 fe.name = *string;
18204               break;
18205             case DW_LNCT_directory_index:
18206               if (uint.has_value ())
18207                 fe.d_index = (dir_index) *uint;
18208               break;
18209             case DW_LNCT_timestamp:
18210               if (uint.has_value ())
18211                 fe.mod_time = *uint;
18212               break;
18213             case DW_LNCT_size:
18214               if (uint.has_value ())
18215                 fe.length = *uint;
18216               break;
18217             case DW_LNCT_MD5:
18218               break;
18219             default:
18220               complaint (&symfile_complaints,
18221                          _("Unknown format content type %s"),
18222                          pulongest (content_type));
18223             }
18224         }
18225
18226       callback (lh, fe.name, fe.d_index, fe.mod_time, fe.length);
18227     }
18228
18229   *bufp = buf;
18230 }
18231
18232 /* Read the statement program header starting at OFFSET in
18233    .debug_line, or .debug_line.dwo.  Return a pointer
18234    to a struct line_header, allocated using xmalloc.
18235    Returns NULL if there is a problem reading the header, e.g., if it
18236    has a version we don't understand.
18237
18238    NOTE: the strings in the include directory and file name tables of
18239    the returned object point into the dwarf line section buffer,
18240    and must not be freed.  */
18241
18242 static line_header_up
18243 dwarf_decode_line_header (sect_offset sect_off, struct dwarf2_cu *cu)
18244 {
18245   const gdb_byte *line_ptr;
18246   unsigned int bytes_read, offset_size;
18247   int i;
18248   const char *cur_dir, *cur_file;
18249   struct dwarf2_section_info *section;
18250   bfd *abfd;
18251
18252   section = get_debug_line_section (cu);
18253   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
18254   if (section->buffer == NULL)
18255     {
18256       if (cu->dwo_unit && cu->per_cu->is_debug_types)
18257         complaint (&symfile_complaints, _("missing .debug_line.dwo section"));
18258       else
18259         complaint (&symfile_complaints, _("missing .debug_line section"));
18260       return 0;
18261     }
18262
18263   /* We can't do this until we know the section is non-empty.
18264      Only then do we know we have such a section.  */
18265   abfd = get_section_bfd_owner (section);
18266
18267   /* Make sure that at least there's room for the total_length field.
18268      That could be 12 bytes long, but we're just going to fudge that.  */
18269   if (to_underlying (sect_off) + 4 >= section->size)
18270     {
18271       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18272       return 0;
18273     }
18274
18275   line_header_up lh (new line_header ());
18276
18277   lh->sect_off = sect_off;
18278   lh->offset_in_dwz = cu->per_cu->is_dwz;
18279
18280   line_ptr = section->buffer + to_underlying (sect_off);
18281
18282   /* Read in the header.  */
18283   lh->total_length =
18284     read_checked_initial_length_and_offset (abfd, line_ptr, &cu->header,
18285                                             &bytes_read, &offset_size);
18286   line_ptr += bytes_read;
18287   if (line_ptr + lh->total_length > (section->buffer + section->size))
18288     {
18289       dwarf2_statement_list_fits_in_line_number_section_complaint ();
18290       return 0;
18291     }
18292   lh->statement_program_end = line_ptr + lh->total_length;
18293   lh->version = read_2_bytes (abfd, line_ptr);
18294   line_ptr += 2;
18295   if (lh->version > 5)
18296     {
18297       /* This is a version we don't understand.  The format could have
18298          changed in ways we don't handle properly so just punt.  */
18299       complaint (&symfile_complaints,
18300                  _("unsupported version in .debug_line section"));
18301       return NULL;
18302     }
18303   if (lh->version >= 5)
18304     {
18305       gdb_byte segment_selector_size;
18306
18307       /* Skip address size.  */
18308       read_1_byte (abfd, line_ptr);
18309       line_ptr += 1;
18310
18311       segment_selector_size = read_1_byte (abfd, line_ptr);
18312       line_ptr += 1;
18313       if (segment_selector_size != 0)
18314         {
18315           complaint (&symfile_complaints,
18316                      _("unsupported segment selector size %u "
18317                        "in .debug_line section"),
18318                      segment_selector_size);
18319           return NULL;
18320         }
18321     }
18322   lh->header_length = read_offset_1 (abfd, line_ptr, offset_size);
18323   line_ptr += offset_size;
18324   lh->minimum_instruction_length = read_1_byte (abfd, line_ptr);
18325   line_ptr += 1;
18326   if (lh->version >= 4)
18327     {
18328       lh->maximum_ops_per_instruction = read_1_byte (abfd, line_ptr);
18329       line_ptr += 1;
18330     }
18331   else
18332     lh->maximum_ops_per_instruction = 1;
18333
18334   if (lh->maximum_ops_per_instruction == 0)
18335     {
18336       lh->maximum_ops_per_instruction = 1;
18337       complaint (&symfile_complaints,
18338                  _("invalid maximum_ops_per_instruction "
18339                    "in `.debug_line' section"));
18340     }
18341
18342   lh->default_is_stmt = read_1_byte (abfd, line_ptr);
18343   line_ptr += 1;
18344   lh->line_base = read_1_signed_byte (abfd, line_ptr);
18345   line_ptr += 1;
18346   lh->line_range = read_1_byte (abfd, line_ptr);
18347   line_ptr += 1;
18348   lh->opcode_base = read_1_byte (abfd, line_ptr);
18349   line_ptr += 1;
18350   lh->standard_opcode_lengths.reset (new unsigned char[lh->opcode_base]);
18351
18352   lh->standard_opcode_lengths[0] = 1;  /* This should never be used anyway.  */
18353   for (i = 1; i < lh->opcode_base; ++i)
18354     {
18355       lh->standard_opcode_lengths[i] = read_1_byte (abfd, line_ptr);
18356       line_ptr += 1;
18357     }
18358
18359   if (lh->version >= 5)
18360     {
18361       /* Read directory table.  */
18362       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18363                               [] (struct line_header *lh, const char *name,
18364                                   dir_index d_index, unsigned int mod_time,
18365                                   unsigned int length)
18366         {
18367           lh->add_include_dir (name);
18368         });
18369
18370       /* Read file name table.  */
18371       read_formatted_entries (abfd, &line_ptr, lh.get (), &cu->header,
18372                               [] (struct line_header *lh, const char *name,
18373                                   dir_index d_index, unsigned int mod_time,
18374                                   unsigned int length)
18375         {
18376           lh->add_file_name (name, d_index, mod_time, length);
18377         });
18378     }
18379   else
18380     {
18381       /* Read directory table.  */
18382       while ((cur_dir = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18383         {
18384           line_ptr += bytes_read;
18385           lh->add_include_dir (cur_dir);
18386         }
18387       line_ptr += bytes_read;
18388
18389       /* Read file name table.  */
18390       while ((cur_file = read_direct_string (abfd, line_ptr, &bytes_read)) != NULL)
18391         {
18392           unsigned int mod_time, length;
18393           dir_index d_index;
18394
18395           line_ptr += bytes_read;
18396           d_index = (dir_index) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18397           line_ptr += bytes_read;
18398           mod_time = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18399           line_ptr += bytes_read;
18400           length = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18401           line_ptr += bytes_read;
18402
18403           lh->add_file_name (cur_file, d_index, mod_time, length);
18404         }
18405       line_ptr += bytes_read;
18406     }
18407   lh->statement_program_start = line_ptr;
18408
18409   if (line_ptr > (section->buffer + section->size))
18410     complaint (&symfile_complaints,
18411                _("line number info header doesn't "
18412                  "fit in `.debug_line' section"));
18413
18414   return lh;
18415 }
18416
18417 /* Subroutine of dwarf_decode_lines to simplify it.
18418    Return the file name of the psymtab for included file FILE_INDEX
18419    in line header LH of PST.
18420    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
18421    If space for the result is malloc'd, it will be freed by a cleanup.
18422    Returns NULL if FILE_INDEX should be ignored, i.e., it is pst->filename.
18423
18424    The function creates dangling cleanup registration.  */
18425
18426 static const char *
18427 psymtab_include_file_name (const struct line_header *lh, int file_index,
18428                            const struct partial_symtab *pst,
18429                            const char *comp_dir)
18430 {
18431   const file_entry &fe = lh->file_names[file_index];
18432   const char *include_name = fe.name;
18433   const char *include_name_to_compare = include_name;
18434   const char *pst_filename;
18435   char *copied_name = NULL;
18436   int file_is_pst;
18437
18438   const char *dir_name = fe.include_dir (lh);
18439
18440   if (!IS_ABSOLUTE_PATH (include_name)
18441       && (dir_name != NULL || comp_dir != NULL))
18442     {
18443       /* Avoid creating a duplicate psymtab for PST.
18444          We do this by comparing INCLUDE_NAME and PST_FILENAME.
18445          Before we do the comparison, however, we need to account
18446          for DIR_NAME and COMP_DIR.
18447          First prepend dir_name (if non-NULL).  If we still don't
18448          have an absolute path prepend comp_dir (if non-NULL).
18449          However, the directory we record in the include-file's
18450          psymtab does not contain COMP_DIR (to match the
18451          corresponding symtab(s)).
18452
18453          Example:
18454
18455          bash$ cd /tmp
18456          bash$ gcc -g ./hello.c
18457          include_name = "hello.c"
18458          dir_name = "."
18459          DW_AT_comp_dir = comp_dir = "/tmp"
18460          DW_AT_name = "./hello.c"
18461
18462       */
18463
18464       if (dir_name != NULL)
18465         {
18466           char *tem = concat (dir_name, SLASH_STRING,
18467                               include_name, (char *)NULL);
18468
18469           make_cleanup (xfree, tem);
18470           include_name = tem;
18471           include_name_to_compare = include_name;
18472         }
18473       if (!IS_ABSOLUTE_PATH (include_name) && comp_dir != NULL)
18474         {
18475           char *tem = concat (comp_dir, SLASH_STRING,
18476                               include_name, (char *)NULL);
18477
18478           make_cleanup (xfree, tem);
18479           include_name_to_compare = tem;
18480         }
18481     }
18482
18483   pst_filename = pst->filename;
18484   if (!IS_ABSOLUTE_PATH (pst_filename) && pst->dirname != NULL)
18485     {
18486       copied_name = concat (pst->dirname, SLASH_STRING,
18487                             pst_filename, (char *)NULL);
18488       pst_filename = copied_name;
18489     }
18490
18491   file_is_pst = FILENAME_CMP (include_name_to_compare, pst_filename) == 0;
18492
18493   if (copied_name != NULL)
18494     xfree (copied_name);
18495
18496   if (file_is_pst)
18497     return NULL;
18498   return include_name;
18499 }
18500
18501 /* State machine to track the state of the line number program.  */
18502
18503 class lnp_state_machine
18504 {
18505 public:
18506   /* Initialize a machine state for the start of a line number
18507      program.  */
18508   lnp_state_machine (gdbarch *arch, line_header *lh, bool record_lines_p);
18509
18510   file_entry *current_file ()
18511   {
18512     /* lh->file_names is 0-based, but the file name numbers in the
18513        statement program are 1-based.  */
18514     return m_line_header->file_name_at (m_file);
18515   }
18516
18517   /* Record the line in the state machine.  END_SEQUENCE is true if
18518      we're processing the end of a sequence.  */
18519   void record_line (bool end_sequence);
18520
18521   /* Check address and if invalid nop-out the rest of the lines in this
18522      sequence.  */
18523   void check_line_address (struct dwarf2_cu *cu,
18524                            const gdb_byte *line_ptr,
18525                            CORE_ADDR lowpc, CORE_ADDR address);
18526
18527   void handle_set_discriminator (unsigned int discriminator)
18528   {
18529     m_discriminator = discriminator;
18530     m_line_has_non_zero_discriminator |= discriminator != 0;
18531   }
18532
18533   /* Handle DW_LNE_set_address.  */
18534   void handle_set_address (CORE_ADDR baseaddr, CORE_ADDR address)
18535   {
18536     m_op_index = 0;
18537     address += baseaddr;
18538     m_address = gdbarch_adjust_dwarf2_line (m_gdbarch, address, false);
18539   }
18540
18541   /* Handle DW_LNS_advance_pc.  */
18542   void handle_advance_pc (CORE_ADDR adjust);
18543
18544   /* Handle a special opcode.  */
18545   void handle_special_opcode (unsigned char op_code);
18546
18547   /* Handle DW_LNS_advance_line.  */
18548   void handle_advance_line (int line_delta)
18549   {
18550     advance_line (line_delta);
18551   }
18552
18553   /* Handle DW_LNS_set_file.  */
18554   void handle_set_file (file_name_index file);
18555
18556   /* Handle DW_LNS_negate_stmt.  */
18557   void handle_negate_stmt ()
18558   {
18559     m_is_stmt = !m_is_stmt;
18560   }
18561
18562   /* Handle DW_LNS_const_add_pc.  */
18563   void handle_const_add_pc ();
18564
18565   /* Handle DW_LNS_fixed_advance_pc.  */
18566   void handle_fixed_advance_pc (CORE_ADDR addr_adj)
18567   {
18568     m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18569     m_op_index = 0;
18570   }
18571
18572   /* Handle DW_LNS_copy.  */
18573   void handle_copy ()
18574   {
18575     record_line (false);
18576     m_discriminator = 0;
18577   }
18578
18579   /* Handle DW_LNE_end_sequence.  */
18580   void handle_end_sequence ()
18581   {
18582     m_record_line_callback = ::record_line;
18583   }
18584
18585 private:
18586   /* Advance the line by LINE_DELTA.  */
18587   void advance_line (int line_delta)
18588   {
18589     m_line += line_delta;
18590
18591     if (line_delta != 0)
18592       m_line_has_non_zero_discriminator = m_discriminator != 0;
18593   }
18594
18595   gdbarch *m_gdbarch;
18596
18597   /* True if we're recording lines.
18598      Otherwise we're building partial symtabs and are just interested in
18599      finding include files mentioned by the line number program.  */
18600   bool m_record_lines_p;
18601
18602   /* The line number header.  */
18603   line_header *m_line_header;
18604
18605   /* These are part of the standard DWARF line number state machine,
18606      and initialized according to the DWARF spec.  */
18607
18608   unsigned char m_op_index = 0;
18609   /* The line table index (1-based) of the current file.  */
18610   file_name_index m_file = (file_name_index) 1;
18611   unsigned int m_line = 1;
18612
18613   /* These are initialized in the constructor.  */
18614
18615   CORE_ADDR m_address;
18616   bool m_is_stmt;
18617   unsigned int m_discriminator;
18618
18619   /* Additional bits of state we need to track.  */
18620
18621   /* The last file that we called dwarf2_start_subfile for.
18622      This is only used for TLLs.  */
18623   unsigned int m_last_file = 0;
18624   /* The last file a line number was recorded for.  */
18625   struct subfile *m_last_subfile = NULL;
18626
18627   /* The function to call to record a line.  */
18628   record_line_ftype *m_record_line_callback = NULL;
18629
18630   /* The last line number that was recorded, used to coalesce
18631      consecutive entries for the same line.  This can happen, for
18632      example, when discriminators are present.  PR 17276.  */
18633   unsigned int m_last_line = 0;
18634   bool m_line_has_non_zero_discriminator = false;
18635 };
18636
18637 void
18638 lnp_state_machine::handle_advance_pc (CORE_ADDR adjust)
18639 {
18640   CORE_ADDR addr_adj = (((m_op_index + adjust)
18641                          / m_line_header->maximum_ops_per_instruction)
18642                         * m_line_header->minimum_instruction_length);
18643   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18644   m_op_index = ((m_op_index + adjust)
18645                 % m_line_header->maximum_ops_per_instruction);
18646 }
18647
18648 void
18649 lnp_state_machine::handle_special_opcode (unsigned char op_code)
18650 {
18651   unsigned char adj_opcode = op_code - m_line_header->opcode_base;
18652   CORE_ADDR addr_adj = (((m_op_index
18653                           + (adj_opcode / m_line_header->line_range))
18654                          / m_line_header->maximum_ops_per_instruction)
18655                         * m_line_header->minimum_instruction_length);
18656   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18657   m_op_index = ((m_op_index + (adj_opcode / m_line_header->line_range))
18658                 % m_line_header->maximum_ops_per_instruction);
18659
18660   int line_delta = (m_line_header->line_base
18661                     + (adj_opcode % m_line_header->line_range));
18662   advance_line (line_delta);
18663   record_line (false);
18664   m_discriminator = 0;
18665 }
18666
18667 void
18668 lnp_state_machine::handle_set_file (file_name_index file)
18669 {
18670   m_file = file;
18671
18672   const file_entry *fe = current_file ();
18673   if (fe == NULL)
18674     dwarf2_debug_line_missing_file_complaint ();
18675   else if (m_record_lines_p)
18676     {
18677       const char *dir = fe->include_dir (m_line_header);
18678
18679       m_last_subfile = current_subfile;
18680       m_line_has_non_zero_discriminator = m_discriminator != 0;
18681       dwarf2_start_subfile (fe->name, dir);
18682     }
18683 }
18684
18685 void
18686 lnp_state_machine::handle_const_add_pc ()
18687 {
18688   CORE_ADDR adjust
18689     = (255 - m_line_header->opcode_base) / m_line_header->line_range;
18690
18691   CORE_ADDR addr_adj
18692     = (((m_op_index + adjust)
18693         / m_line_header->maximum_ops_per_instruction)
18694        * m_line_header->minimum_instruction_length);
18695
18696   m_address += gdbarch_adjust_dwarf2_line (m_gdbarch, addr_adj, true);
18697   m_op_index = ((m_op_index + adjust)
18698                 % m_line_header->maximum_ops_per_instruction);
18699 }
18700
18701 /* Ignore this record_line request.  */
18702
18703 static void
18704 noop_record_line (struct subfile *subfile, int line, CORE_ADDR pc)
18705 {
18706   return;
18707 }
18708
18709 /* Return non-zero if we should add LINE to the line number table.
18710    LINE is the line to add, LAST_LINE is the last line that was added,
18711    LAST_SUBFILE is the subfile for LAST_LINE.
18712    LINE_HAS_NON_ZERO_DISCRIMINATOR is non-zero if LINE has ever
18713    had a non-zero discriminator.
18714
18715    We have to be careful in the presence of discriminators.
18716    E.g., for this line:
18717
18718      for (i = 0; i < 100000; i++);
18719
18720    clang can emit four line number entries for that one line,
18721    each with a different discriminator.
18722    See gdb.dwarf2/dw2-single-line-discriminators.exp for an example.
18723
18724    However, we want gdb to coalesce all four entries into one.
18725    Otherwise the user could stepi into the middle of the line and
18726    gdb would get confused about whether the pc really was in the
18727    middle of the line.
18728
18729    Things are further complicated by the fact that two consecutive
18730    line number entries for the same line is a heuristic used by gcc
18731    to denote the end of the prologue.  So we can't just discard duplicate
18732    entries, we have to be selective about it.  The heuristic we use is
18733    that we only collapse consecutive entries for the same line if at least
18734    one of those entries has a non-zero discriminator.  PR 17276.
18735
18736    Note: Addresses in the line number state machine can never go backwards
18737    within one sequence, thus this coalescing is ok.  */
18738
18739 static int
18740 dwarf_record_line_p (unsigned int line, unsigned int last_line,
18741                      int line_has_non_zero_discriminator,
18742                      struct subfile *last_subfile)
18743 {
18744   if (current_subfile != last_subfile)
18745     return 1;
18746   if (line != last_line)
18747     return 1;
18748   /* Same line for the same file that we've seen already.
18749      As a last check, for pr 17276, only record the line if the line
18750      has never had a non-zero discriminator.  */
18751   if (!line_has_non_zero_discriminator)
18752     return 1;
18753   return 0;
18754 }
18755
18756 /* Use P_RECORD_LINE to record line number LINE beginning at address ADDRESS
18757    in the line table of subfile SUBFILE.  */
18758
18759 static void
18760 dwarf_record_line_1 (struct gdbarch *gdbarch, struct subfile *subfile,
18761                      unsigned int line, CORE_ADDR address,
18762                      record_line_ftype p_record_line)
18763 {
18764   CORE_ADDR addr = gdbarch_addr_bits_remove (gdbarch, address);
18765
18766   if (dwarf_line_debug)
18767     {
18768       fprintf_unfiltered (gdb_stdlog,
18769                           "Recording line %u, file %s, address %s\n",
18770                           line, lbasename (subfile->name),
18771                           paddress (gdbarch, address));
18772     }
18773
18774   (*p_record_line) (subfile, line, addr);
18775 }
18776
18777 /* Subroutine of dwarf_decode_lines_1 to simplify it.
18778    Mark the end of a set of line number records.
18779    The arguments are the same as for dwarf_record_line_1.
18780    If SUBFILE is NULL the request is ignored.  */
18781
18782 static void
18783 dwarf_finish_line (struct gdbarch *gdbarch, struct subfile *subfile,
18784                    CORE_ADDR address, record_line_ftype p_record_line)
18785 {
18786   if (subfile == NULL)
18787     return;
18788
18789   if (dwarf_line_debug)
18790     {
18791       fprintf_unfiltered (gdb_stdlog,
18792                           "Finishing current line, file %s, address %s\n",
18793                           lbasename (subfile->name),
18794                           paddress (gdbarch, address));
18795     }
18796
18797   dwarf_record_line_1 (gdbarch, subfile, 0, address, p_record_line);
18798 }
18799
18800 void
18801 lnp_state_machine::record_line (bool end_sequence)
18802 {
18803   if (dwarf_line_debug)
18804     {
18805       fprintf_unfiltered (gdb_stdlog,
18806                           "Processing actual line %u: file %u,"
18807                           " address %s, is_stmt %u, discrim %u\n",
18808                           m_line, to_underlying (m_file),
18809                           paddress (m_gdbarch, m_address),
18810                           m_is_stmt, m_discriminator);
18811     }
18812
18813   file_entry *fe = current_file ();
18814
18815   if (fe == NULL)
18816     dwarf2_debug_line_missing_file_complaint ();
18817   /* For now we ignore lines not starting on an instruction boundary.
18818      But not when processing end_sequence for compatibility with the
18819      previous version of the code.  */
18820   else if (m_op_index == 0 || end_sequence)
18821     {
18822       fe->included_p = 1;
18823       if (m_record_lines_p && m_is_stmt)
18824         {
18825           if (m_last_subfile != current_subfile || end_sequence)
18826             {
18827               dwarf_finish_line (m_gdbarch, m_last_subfile,
18828                                  m_address, m_record_line_callback);
18829             }
18830
18831           if (!end_sequence)
18832             {
18833               if (dwarf_record_line_p (m_line, m_last_line,
18834                                        m_line_has_non_zero_discriminator,
18835                                        m_last_subfile))
18836                 {
18837                   dwarf_record_line_1 (m_gdbarch, current_subfile,
18838                                        m_line, m_address,
18839                                        m_record_line_callback);
18840                 }
18841               m_last_subfile = current_subfile;
18842               m_last_line = m_line;
18843             }
18844         }
18845     }
18846 }
18847
18848 lnp_state_machine::lnp_state_machine (gdbarch *arch, line_header *lh,
18849                                       bool record_lines_p)
18850 {
18851   m_gdbarch = arch;
18852   m_record_lines_p = record_lines_p;
18853   m_line_header = lh;
18854
18855   m_record_line_callback = ::record_line;
18856
18857   /* Call `gdbarch_adjust_dwarf2_line' on the initial 0 address as if there
18858      was a line entry for it so that the backend has a chance to adjust it
18859      and also record it in case it needs it.  This is currently used by MIPS
18860      code, cf. `mips_adjust_dwarf2_line'.  */
18861   m_address = gdbarch_adjust_dwarf2_line (arch, 0, 0);
18862   m_is_stmt = lh->default_is_stmt;
18863   m_discriminator = 0;
18864 }
18865
18866 void
18867 lnp_state_machine::check_line_address (struct dwarf2_cu *cu,
18868                                        const gdb_byte *line_ptr,
18869                                        CORE_ADDR lowpc, CORE_ADDR address)
18870 {
18871   /* If address < lowpc then it's not a usable value, it's outside the
18872      pc range of the CU.  However, we restrict the test to only address
18873      values of zero to preserve GDB's previous behaviour which is to
18874      handle the specific case of a function being GC'd by the linker.  */
18875
18876   if (address == 0 && address < lowpc)
18877     {
18878       /* This line table is for a function which has been
18879          GCd by the linker.  Ignore it.  PR gdb/12528 */
18880
18881       struct objfile *objfile = cu->objfile;
18882       long line_offset = line_ptr - get_debug_line_section (cu)->buffer;
18883
18884       complaint (&symfile_complaints,
18885                  _(".debug_line address at offset 0x%lx is 0 [in module %s]"),
18886                  line_offset, objfile_name (objfile));
18887       m_record_line_callback = noop_record_line;
18888       /* Note: record_line_callback is left as noop_record_line until
18889          we see DW_LNE_end_sequence.  */
18890     }
18891 }
18892
18893 /* Subroutine of dwarf_decode_lines to simplify it.
18894    Process the line number information in LH.
18895    If DECODE_FOR_PST_P is non-zero, all we do is process the line number
18896    program in order to set included_p for every referenced header.  */
18897
18898 static void
18899 dwarf_decode_lines_1 (struct line_header *lh, struct dwarf2_cu *cu,
18900                       const int decode_for_pst_p, CORE_ADDR lowpc)
18901 {
18902   const gdb_byte *line_ptr, *extended_end;
18903   const gdb_byte *line_end;
18904   unsigned int bytes_read, extended_len;
18905   unsigned char op_code, extended_op;
18906   CORE_ADDR baseaddr;
18907   struct objfile *objfile = cu->objfile;
18908   bfd *abfd = objfile->obfd;
18909   struct gdbarch *gdbarch = get_objfile_arch (objfile);
18910   /* True if we're recording line info (as opposed to building partial
18911      symtabs and just interested in finding include files mentioned by
18912      the line number program).  */
18913   bool record_lines_p = !decode_for_pst_p;
18914
18915   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
18916
18917   line_ptr = lh->statement_program_start;
18918   line_end = lh->statement_program_end;
18919
18920   /* Read the statement sequences until there's nothing left.  */
18921   while (line_ptr < line_end)
18922     {
18923       /* The DWARF line number program state machine.  Reset the state
18924          machine at the start of each sequence.  */
18925       lnp_state_machine state_machine (gdbarch, lh, record_lines_p);
18926       bool end_sequence = false;
18927
18928       if (record_lines_p)
18929         {
18930           /* Start a subfile for the current file of the state
18931              machine.  */
18932           const file_entry *fe = state_machine.current_file ();
18933
18934           if (fe != NULL)
18935             dwarf2_start_subfile (fe->name, fe->include_dir (lh));
18936         }
18937
18938       /* Decode the table.  */
18939       while (line_ptr < line_end && !end_sequence)
18940         {
18941           op_code = read_1_byte (abfd, line_ptr);
18942           line_ptr += 1;
18943
18944           if (op_code >= lh->opcode_base)
18945             {
18946               /* Special opcode.  */
18947               state_machine.handle_special_opcode (op_code);
18948             }
18949           else switch (op_code)
18950             {
18951             case DW_LNS_extended_op:
18952               extended_len = read_unsigned_leb128 (abfd, line_ptr,
18953                                                    &bytes_read);
18954               line_ptr += bytes_read;
18955               extended_end = line_ptr + extended_len;
18956               extended_op = read_1_byte (abfd, line_ptr);
18957               line_ptr += 1;
18958               switch (extended_op)
18959                 {
18960                 case DW_LNE_end_sequence:
18961                   state_machine.handle_end_sequence ();
18962                   end_sequence = true;
18963                   break;
18964                 case DW_LNE_set_address:
18965                   {
18966                     CORE_ADDR address
18967                       = read_address (abfd, line_ptr, cu, &bytes_read);
18968                     line_ptr += bytes_read;
18969
18970                     state_machine.check_line_address (cu, line_ptr,
18971                                                       lowpc, address);
18972                     state_machine.handle_set_address (baseaddr, address);
18973                   }
18974                   break;
18975                 case DW_LNE_define_file:
18976                   {
18977                     const char *cur_file;
18978                     unsigned int mod_time, length;
18979                     dir_index dindex;
18980
18981                     cur_file = read_direct_string (abfd, line_ptr,
18982                                                    &bytes_read);
18983                     line_ptr += bytes_read;
18984                     dindex = (dir_index)
18985                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18986                     line_ptr += bytes_read;
18987                     mod_time =
18988                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18989                     line_ptr += bytes_read;
18990                     length =
18991                       read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
18992                     line_ptr += bytes_read;
18993                     lh->add_file_name (cur_file, dindex, mod_time, length);
18994                   }
18995                   break;
18996                 case DW_LNE_set_discriminator:
18997                   {
18998                     /* The discriminator is not interesting to the
18999                        debugger; just ignore it.  We still need to
19000                        check its value though:
19001                        if there are consecutive entries for the same
19002                        (non-prologue) line we want to coalesce them.
19003                        PR 17276.  */
19004                     unsigned int discr
19005                       = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19006                     line_ptr += bytes_read;
19007
19008                     state_machine.handle_set_discriminator (discr);
19009                   }
19010                   break;
19011                 default:
19012                   complaint (&symfile_complaints,
19013                              _("mangled .debug_line section"));
19014                   return;
19015                 }
19016               /* Make sure that we parsed the extended op correctly.  If e.g.
19017                  we expected a different address size than the producer used,
19018                  we may have read the wrong number of bytes.  */
19019               if (line_ptr != extended_end)
19020                 {
19021                   complaint (&symfile_complaints,
19022                              _("mangled .debug_line section"));
19023                   return;
19024                 }
19025               break;
19026             case DW_LNS_copy:
19027               state_machine.handle_copy ();
19028               break;
19029             case DW_LNS_advance_pc:
19030               {
19031                 CORE_ADDR adjust
19032                   = read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19033                 line_ptr += bytes_read;
19034
19035                 state_machine.handle_advance_pc (adjust);
19036               }
19037               break;
19038             case DW_LNS_advance_line:
19039               {
19040                 int line_delta
19041                   = read_signed_leb128 (abfd, line_ptr, &bytes_read);
19042                 line_ptr += bytes_read;
19043
19044                 state_machine.handle_advance_line (line_delta);
19045               }
19046               break;
19047             case DW_LNS_set_file:
19048               {
19049                 file_name_index file
19050                   = (file_name_index) read_unsigned_leb128 (abfd, line_ptr,
19051                                                             &bytes_read);
19052                 line_ptr += bytes_read;
19053
19054                 state_machine.handle_set_file (file);
19055               }
19056               break;
19057             case DW_LNS_set_column:
19058               (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19059               line_ptr += bytes_read;
19060               break;
19061             case DW_LNS_negate_stmt:
19062               state_machine.handle_negate_stmt ();
19063               break;
19064             case DW_LNS_set_basic_block:
19065               break;
19066             /* Add to the address register of the state machine the
19067                address increment value corresponding to special opcode
19068                255.  I.e., this value is scaled by the minimum
19069                instruction length since special opcode 255 would have
19070                scaled the increment.  */
19071             case DW_LNS_const_add_pc:
19072               state_machine.handle_const_add_pc ();
19073               break;
19074             case DW_LNS_fixed_advance_pc:
19075               {
19076                 CORE_ADDR addr_adj = read_2_bytes (abfd, line_ptr);
19077                 line_ptr += 2;
19078
19079                 state_machine.handle_fixed_advance_pc (addr_adj);
19080               }
19081               break;
19082             default:
19083               {
19084                 /* Unknown standard opcode, ignore it.  */
19085                 int i;
19086
19087                 for (i = 0; i < lh->standard_opcode_lengths[op_code]; i++)
19088                   {
19089                     (void) read_unsigned_leb128 (abfd, line_ptr, &bytes_read);
19090                     line_ptr += bytes_read;
19091                   }
19092               }
19093             }
19094         }
19095
19096       if (!end_sequence)
19097         dwarf2_debug_line_missing_end_sequence_complaint ();
19098
19099       /* We got a DW_LNE_end_sequence (or we ran off the end of the buffer,
19100          in which case we still finish recording the last line).  */
19101       state_machine.record_line (true);
19102     }
19103 }
19104
19105 /* Decode the Line Number Program (LNP) for the given line_header
19106    structure and CU.  The actual information extracted and the type
19107    of structures created from the LNP depends on the value of PST.
19108
19109    1. If PST is NULL, then this procedure uses the data from the program
19110       to create all necessary symbol tables, and their linetables.
19111
19112    2. If PST is not NULL, this procedure reads the program to determine
19113       the list of files included by the unit represented by PST, and
19114       builds all the associated partial symbol tables.
19115
19116    COMP_DIR is the compilation directory (DW_AT_comp_dir) or NULL if unknown.
19117    It is used for relative paths in the line table.
19118    NOTE: When processing partial symtabs (pst != NULL),
19119    comp_dir == pst->dirname.
19120
19121    NOTE: It is important that psymtabs have the same file name (via strcmp)
19122    as the corresponding symtab.  Since COMP_DIR is not used in the name of the
19123    symtab we don't use it in the name of the psymtabs we create.
19124    E.g. expand_line_sal requires this when finding psymtabs to expand.
19125    A good testcase for this is mb-inline.exp.
19126
19127    LOWPC is the lowest address in CU (or 0 if not known).
19128
19129    Boolean DECODE_MAPPING specifies we need to fully decode .debug_line
19130    for its PC<->lines mapping information.  Otherwise only the filename
19131    table is read in.  */
19132
19133 static void
19134 dwarf_decode_lines (struct line_header *lh, const char *comp_dir,
19135                     struct dwarf2_cu *cu, struct partial_symtab *pst,
19136                     CORE_ADDR lowpc, int decode_mapping)
19137 {
19138   struct objfile *objfile = cu->objfile;
19139   const int decode_for_pst_p = (pst != NULL);
19140
19141   if (decode_mapping)
19142     dwarf_decode_lines_1 (lh, cu, decode_for_pst_p, lowpc);
19143
19144   if (decode_for_pst_p)
19145     {
19146       int file_index;
19147
19148       /* Now that we're done scanning the Line Header Program, we can
19149          create the psymtab of each included file.  */
19150       for (file_index = 0; file_index < lh->file_names.size (); file_index++)
19151         if (lh->file_names[file_index].included_p == 1)
19152           {
19153             const char *include_name =
19154               psymtab_include_file_name (lh, file_index, pst, comp_dir);
19155             if (include_name != NULL)
19156               dwarf2_create_include_psymtab (include_name, pst, objfile);
19157           }
19158     }
19159   else
19160     {
19161       /* Make sure a symtab is created for every file, even files
19162          which contain only variables (i.e. no code with associated
19163          line numbers).  */
19164       struct compunit_symtab *cust = buildsym_compunit_symtab ();
19165       int i;
19166
19167       for (i = 0; i < lh->file_names.size (); i++)
19168         {
19169           file_entry &fe = lh->file_names[i];
19170
19171           dwarf2_start_subfile (fe.name, fe.include_dir (lh));
19172
19173           if (current_subfile->symtab == NULL)
19174             {
19175               current_subfile->symtab
19176                 = allocate_symtab (cust, current_subfile->name);
19177             }
19178           fe.symtab = current_subfile->symtab;
19179         }
19180     }
19181 }
19182
19183 /* Start a subfile for DWARF.  FILENAME is the name of the file and
19184    DIRNAME the name of the source directory which contains FILENAME
19185    or NULL if not known.
19186    This routine tries to keep line numbers from identical absolute and
19187    relative file names in a common subfile.
19188
19189    Using the `list' example from the GDB testsuite, which resides in
19190    /srcdir and compiling it with Irix6.2 cc in /compdir using a filename
19191    of /srcdir/list0.c yields the following debugging information for list0.c:
19192
19193    DW_AT_name:          /srcdir/list0.c
19194    DW_AT_comp_dir:      /compdir
19195    files.files[0].name: list0.h
19196    files.files[0].dir:  /srcdir
19197    files.files[1].name: list0.c
19198    files.files[1].dir:  /srcdir
19199
19200    The line number information for list0.c has to end up in a single
19201    subfile, so that `break /srcdir/list0.c:1' works as expected.
19202    start_subfile will ensure that this happens provided that we pass the
19203    concatenation of files.files[1].dir and files.files[1].name as the
19204    subfile's name.  */
19205
19206 static void
19207 dwarf2_start_subfile (const char *filename, const char *dirname)
19208 {
19209   char *copy = NULL;
19210
19211   /* In order not to lose the line information directory,
19212      we concatenate it to the filename when it makes sense.
19213      Note that the Dwarf3 standard says (speaking of filenames in line
19214      information): ``The directory index is ignored for file names
19215      that represent full path names''.  Thus ignoring dirname in the
19216      `else' branch below isn't an issue.  */
19217
19218   if (!IS_ABSOLUTE_PATH (filename) && dirname != NULL)
19219     {
19220       copy = concat (dirname, SLASH_STRING, filename, (char *)NULL);
19221       filename = copy;
19222     }
19223
19224   start_subfile (filename);
19225
19226   if (copy != NULL)
19227     xfree (copy);
19228 }
19229
19230 /* Start a symtab for DWARF.
19231    NAME, COMP_DIR, LOW_PC are passed to start_symtab.  */
19232
19233 static struct compunit_symtab *
19234 dwarf2_start_symtab (struct dwarf2_cu *cu,
19235                      const char *name, const char *comp_dir, CORE_ADDR low_pc)
19236 {
19237   struct compunit_symtab *cust
19238     = start_symtab (cu->objfile, name, comp_dir, low_pc, cu->language);
19239
19240   record_debugformat ("DWARF 2");
19241   record_producer (cu->producer);
19242
19243   /* We assume that we're processing GCC output.  */
19244   processing_gcc_compilation = 2;
19245
19246   cu->processing_has_namespace_info = 0;
19247
19248   return cust;
19249 }
19250
19251 static void
19252 var_decode_location (struct attribute *attr, struct symbol *sym,
19253                      struct dwarf2_cu *cu)
19254 {
19255   struct objfile *objfile = cu->objfile;
19256   struct comp_unit_head *cu_header = &cu->header;
19257
19258   /* NOTE drow/2003-01-30: There used to be a comment and some special
19259      code here to turn a symbol with DW_AT_external and a
19260      SYMBOL_VALUE_ADDRESS of 0 into a LOC_UNRESOLVED symbol.  This was
19261      necessary for platforms (maybe Alpha, certainly PowerPC GNU/Linux
19262      with some versions of binutils) where shared libraries could have
19263      relocations against symbols in their debug information - the
19264      minimal symbol would have the right address, but the debug info
19265      would not.  It's no longer necessary, because we will explicitly
19266      apply relocations when we read in the debug information now.  */
19267
19268   /* A DW_AT_location attribute with no contents indicates that a
19269      variable has been optimized away.  */
19270   if (attr_form_is_block (attr) && DW_BLOCK (attr)->size == 0)
19271     {
19272       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19273       return;
19274     }
19275
19276   /* Handle one degenerate form of location expression specially, to
19277      preserve GDB's previous behavior when section offsets are
19278      specified.  If this is just a DW_OP_addr or DW_OP_GNU_addr_index
19279      then mark this symbol as LOC_STATIC.  */
19280
19281   if (attr_form_is_block (attr)
19282       && ((DW_BLOCK (attr)->data[0] == DW_OP_addr
19283            && DW_BLOCK (attr)->size == 1 + cu_header->addr_size)
19284           || (DW_BLOCK (attr)->data[0] == DW_OP_GNU_addr_index
19285               && (DW_BLOCK (attr)->size
19286                   == 1 + leb128_size (&DW_BLOCK (attr)->data[1])))))
19287     {
19288       unsigned int dummy;
19289
19290       if (DW_BLOCK (attr)->data[0] == DW_OP_addr)
19291         SYMBOL_VALUE_ADDRESS (sym) =
19292           read_address (objfile->obfd, DW_BLOCK (attr)->data + 1, cu, &dummy);
19293       else
19294         SYMBOL_VALUE_ADDRESS (sym) =
19295           read_addr_index_from_leb128 (cu, DW_BLOCK (attr)->data + 1, &dummy);
19296       SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
19297       fixup_symbol_section (sym, objfile);
19298       SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
19299                                               SYMBOL_SECTION (sym));
19300       return;
19301     }
19302
19303   /* NOTE drow/2002-01-30: It might be worthwhile to have a static
19304      expression evaluator, and use LOC_COMPUTED only when necessary
19305      (i.e. when the value of a register or memory location is
19306      referenced, or a thread-local block, etc.).  Then again, it might
19307      not be worthwhile.  I'm assuming that it isn't unless performance
19308      or memory numbers show me otherwise.  */
19309
19310   dwarf2_symbol_mark_computed (attr, sym, cu, 0);
19311
19312   if (SYMBOL_COMPUTED_OPS (sym)->location_has_loclist)
19313     cu->has_loclist = 1;
19314 }
19315
19316 /* Given a pointer to a DWARF information entry, figure out if we need
19317    to make a symbol table entry for it, and if so, create a new entry
19318    and return a pointer to it.
19319    If TYPE is NULL, determine symbol type from the die, otherwise
19320    used the passed type.
19321    If SPACE is not NULL, use it to hold the new symbol.  If it is
19322    NULL, allocate a new symbol on the objfile's obstack.  */
19323
19324 static struct symbol *
19325 new_symbol_full (struct die_info *die, struct type *type, struct dwarf2_cu *cu,
19326                  struct symbol *space)
19327 {
19328   struct objfile *objfile = cu->objfile;
19329   struct gdbarch *gdbarch = get_objfile_arch (objfile);
19330   struct symbol *sym = NULL;
19331   const char *name;
19332   struct attribute *attr = NULL;
19333   struct attribute *attr2 = NULL;
19334   CORE_ADDR baseaddr;
19335   struct pending **list_to_add = NULL;
19336
19337   int inlined_func = (die->tag == DW_TAG_inlined_subroutine);
19338
19339   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
19340
19341   name = dwarf2_name (die, cu);
19342   if (name)
19343     {
19344       const char *linkagename;
19345       int suppress_add = 0;
19346
19347       if (space)
19348         sym = space;
19349       else
19350         sym = allocate_symbol (objfile);
19351       OBJSTAT (objfile, n_syms++);
19352
19353       /* Cache this symbol's name and the name's demangled form (if any).  */
19354       SYMBOL_SET_LANGUAGE (sym, cu->language, &objfile->objfile_obstack);
19355       linkagename = dwarf2_physname (name, die, cu);
19356       SYMBOL_SET_NAMES (sym, linkagename, strlen (linkagename), 0, objfile);
19357
19358       /* Fortran does not have mangling standard and the mangling does differ
19359          between gfortran, iFort etc.  */
19360       if (cu->language == language_fortran
19361           && symbol_get_demangled_name (&(sym->ginfo)) == NULL)
19362         symbol_set_demangled_name (&(sym->ginfo),
19363                                    dwarf2_full_name (name, die, cu),
19364                                    NULL);
19365
19366       /* Default assumptions.
19367          Use the passed type or decode it from the die.  */
19368       SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19369       SYMBOL_ACLASS_INDEX (sym) = LOC_OPTIMIZED_OUT;
19370       if (type != NULL)
19371         SYMBOL_TYPE (sym) = type;
19372       else
19373         SYMBOL_TYPE (sym) = die_type (die, cu);
19374       attr = dwarf2_attr (die,
19375                           inlined_func ? DW_AT_call_line : DW_AT_decl_line,
19376                           cu);
19377       if (attr)
19378         {
19379           SYMBOL_LINE (sym) = DW_UNSND (attr);
19380         }
19381
19382       attr = dwarf2_attr (die,
19383                           inlined_func ? DW_AT_call_file : DW_AT_decl_file,
19384                           cu);
19385       if (attr)
19386         {
19387           file_name_index file_index = (file_name_index) DW_UNSND (attr);
19388           struct file_entry *fe;
19389
19390           if (cu->line_header != NULL)
19391             fe = cu->line_header->file_name_at (file_index);
19392           else
19393             fe = NULL;
19394
19395           if (fe == NULL)
19396             complaint (&symfile_complaints,
19397                        _("file index out of range"));
19398           else
19399             symbol_set_symtab (sym, fe->symtab);
19400         }
19401
19402       switch (die->tag)
19403         {
19404         case DW_TAG_label:
19405           attr = dwarf2_attr (die, DW_AT_low_pc, cu);
19406           if (attr)
19407             {
19408               CORE_ADDR addr;
19409
19410               addr = attr_value_as_address (attr);
19411               addr = gdbarch_adjust_dwarf2_addr (gdbarch, addr + baseaddr);
19412               SYMBOL_VALUE_ADDRESS (sym) = addr;
19413             }
19414           SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_core_addr;
19415           SYMBOL_DOMAIN (sym) = LABEL_DOMAIN;
19416           SYMBOL_ACLASS_INDEX (sym) = LOC_LABEL;
19417           add_symbol_to_list (sym, cu->list_in_scope);
19418           break;
19419         case DW_TAG_subprogram:
19420           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19421              finish_block.  */
19422           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19423           attr2 = dwarf2_attr (die, DW_AT_external, cu);
19424           if ((attr2 && (DW_UNSND (attr2) != 0))
19425               || cu->language == language_ada)
19426             {
19427               /* Subprograms marked external are stored as a global symbol.
19428                  Ada subprograms, whether marked external or not, are always
19429                  stored as a global symbol, because we want to be able to
19430                  access them globally.  For instance, we want to be able
19431                  to break on a nested subprogram without having to
19432                  specify the context.  */
19433               list_to_add = &global_symbols;
19434             }
19435           else
19436             {
19437               list_to_add = cu->list_in_scope;
19438             }
19439           break;
19440         case DW_TAG_inlined_subroutine:
19441           /* SYMBOL_BLOCK_VALUE (sym) will be filled in later by
19442              finish_block.  */
19443           SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
19444           SYMBOL_INLINED (sym) = 1;
19445           list_to_add = cu->list_in_scope;
19446           break;
19447         case DW_TAG_template_value_param:
19448           suppress_add = 1;
19449           /* Fall through.  */
19450         case DW_TAG_constant:
19451         case DW_TAG_variable:
19452         case DW_TAG_member:
19453           /* Compilation with minimal debug info may result in
19454              variables with missing type entries.  Change the
19455              misleading `void' type to something sensible.  */
19456           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_VOID)
19457             SYMBOL_TYPE (sym) = objfile_type (objfile)->builtin_int;
19458
19459           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19460           /* In the case of DW_TAG_member, we should only be called for
19461              static const members.  */
19462           if (die->tag == DW_TAG_member)
19463             {
19464               /* dwarf2_add_field uses die_is_declaration,
19465                  so we do the same.  */
19466               gdb_assert (die_is_declaration (die, cu));
19467               gdb_assert (attr);
19468             }
19469           if (attr)
19470             {
19471               dwarf2_const_value (attr, sym, cu);
19472               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19473               if (!suppress_add)
19474                 {
19475                   if (attr2 && (DW_UNSND (attr2) != 0))
19476                     list_to_add = &global_symbols;
19477                   else
19478                     list_to_add = cu->list_in_scope;
19479                 }
19480               break;
19481             }
19482           attr = dwarf2_attr (die, DW_AT_location, cu);
19483           if (attr)
19484             {
19485               var_decode_location (attr, sym, cu);
19486               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19487
19488               /* Fortran explicitly imports any global symbols to the local
19489                  scope by DW_TAG_common_block.  */
19490               if (cu->language == language_fortran && die->parent
19491                   && die->parent->tag == DW_TAG_common_block)
19492                 attr2 = NULL;
19493
19494               if (SYMBOL_CLASS (sym) == LOC_STATIC
19495                   && SYMBOL_VALUE_ADDRESS (sym) == 0
19496                   && !dwarf2_per_objfile->has_section_at_zero)
19497                 {
19498                   /* When a static variable is eliminated by the linker,
19499                      the corresponding debug information is not stripped
19500                      out, but the variable address is set to null;
19501                      do not add such variables into symbol table.  */
19502                 }
19503               else if (attr2 && (DW_UNSND (attr2) != 0))
19504                 {
19505                   /* Workaround gfortran PR debug/40040 - it uses
19506                      DW_AT_location for variables in -fPIC libraries which may
19507                      get overriden by other libraries/executable and get
19508                      a different address.  Resolve it by the minimal symbol
19509                      which may come from inferior's executable using copy
19510                      relocation.  Make this workaround only for gfortran as for
19511                      other compilers GDB cannot guess the minimal symbol
19512                      Fortran mangling kind.  */
19513                   if (cu->language == language_fortran && die->parent
19514                       && die->parent->tag == DW_TAG_module
19515                       && cu->producer
19516                       && startswith (cu->producer, "GNU Fortran"))
19517                     SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19518
19519                   /* A variable with DW_AT_external is never static,
19520                      but it may be block-scoped.  */
19521                   list_to_add = (cu->list_in_scope == &file_symbols
19522                                  ? &global_symbols : cu->list_in_scope);
19523                 }
19524               else
19525                 list_to_add = cu->list_in_scope;
19526             }
19527           else
19528             {
19529               /* We do not know the address of this symbol.
19530                  If it is an external symbol and we have type information
19531                  for it, enter the symbol as a LOC_UNRESOLVED symbol.
19532                  The address of the variable will then be determined from
19533                  the minimal symbol table whenever the variable is
19534                  referenced.  */
19535               attr2 = dwarf2_attr (die, DW_AT_external, cu);
19536
19537               /* Fortran explicitly imports any global symbols to the local
19538                  scope by DW_TAG_common_block.  */
19539               if (cu->language == language_fortran && die->parent
19540                   && die->parent->tag == DW_TAG_common_block)
19541                 {
19542                   /* SYMBOL_CLASS doesn't matter here because
19543                      read_common_block is going to reset it.  */
19544                   if (!suppress_add)
19545                     list_to_add = cu->list_in_scope;
19546                 }
19547               else if (attr2 && (DW_UNSND (attr2) != 0)
19548                        && dwarf2_attr (die, DW_AT_type, cu) != NULL)
19549                 {
19550                   /* A variable with DW_AT_external is never static, but it
19551                      may be block-scoped.  */
19552                   list_to_add = (cu->list_in_scope == &file_symbols
19553                                  ? &global_symbols : cu->list_in_scope);
19554
19555                   SYMBOL_ACLASS_INDEX (sym) = LOC_UNRESOLVED;
19556                 }
19557               else if (!die_is_declaration (die, cu))
19558                 {
19559                   /* Use the default LOC_OPTIMIZED_OUT class.  */
19560                   gdb_assert (SYMBOL_CLASS (sym) == LOC_OPTIMIZED_OUT);
19561                   if (!suppress_add)
19562                     list_to_add = cu->list_in_scope;
19563                 }
19564             }
19565           break;
19566         case DW_TAG_formal_parameter:
19567           /* If we are inside a function, mark this as an argument.  If
19568              not, we might be looking at an argument to an inlined function
19569              when we do not have enough information to show inlined frames;
19570              pretend it's a local variable in that case so that the user can
19571              still see it.  */
19572           if (context_stack_depth > 0
19573               && context_stack[context_stack_depth - 1].name != NULL)
19574             SYMBOL_IS_ARGUMENT (sym) = 1;
19575           attr = dwarf2_attr (die, DW_AT_location, cu);
19576           if (attr)
19577             {
19578               var_decode_location (attr, sym, cu);
19579             }
19580           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19581           if (attr)
19582             {
19583               dwarf2_const_value (attr, sym, cu);
19584             }
19585
19586           list_to_add = cu->list_in_scope;
19587           break;
19588         case DW_TAG_unspecified_parameters:
19589           /* From varargs functions; gdb doesn't seem to have any
19590              interest in this information, so just ignore it for now.
19591              (FIXME?) */
19592           break;
19593         case DW_TAG_template_type_param:
19594           suppress_add = 1;
19595           /* Fall through.  */
19596         case DW_TAG_class_type:
19597         case DW_TAG_interface_type:
19598         case DW_TAG_structure_type:
19599         case DW_TAG_union_type:
19600         case DW_TAG_set_type:
19601         case DW_TAG_enumeration_type:
19602           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19603           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
19604
19605           {
19606             /* NOTE: carlton/2003-11-10: C++ class symbols shouldn't
19607                really ever be static objects: otherwise, if you try
19608                to, say, break of a class's method and you're in a file
19609                which doesn't mention that class, it won't work unless
19610                the check for all static symbols in lookup_symbol_aux
19611                saves you.  See the OtherFileClass tests in
19612                gdb.c++/namespace.exp.  */
19613
19614             if (!suppress_add)
19615               {
19616                 list_to_add = (cu->list_in_scope == &file_symbols
19617                                && cu->language == language_cplus
19618                                ? &global_symbols : cu->list_in_scope);
19619
19620                 /* The semantics of C++ state that "struct foo {
19621                    ... }" also defines a typedef for "foo".  */
19622                 if (cu->language == language_cplus
19623                     || cu->language == language_ada
19624                     || cu->language == language_d
19625                     || cu->language == language_rust)
19626                   {
19627                     /* The symbol's name is already allocated along
19628                        with this objfile, so we don't need to
19629                        duplicate it for the type.  */
19630                     if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
19631                       TYPE_NAME (SYMBOL_TYPE (sym)) = SYMBOL_SEARCH_NAME (sym);
19632                   }
19633               }
19634           }
19635           break;
19636         case DW_TAG_typedef:
19637           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19638           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19639           list_to_add = cu->list_in_scope;
19640           break;
19641         case DW_TAG_base_type:
19642         case DW_TAG_subrange_type:
19643           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19644           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
19645           list_to_add = cu->list_in_scope;
19646           break;
19647         case DW_TAG_enumerator:
19648           attr = dwarf2_attr (die, DW_AT_const_value, cu);
19649           if (attr)
19650             {
19651               dwarf2_const_value (attr, sym, cu);
19652             }
19653           {
19654             /* NOTE: carlton/2003-11-10: See comment above in the
19655                DW_TAG_class_type, etc. block.  */
19656
19657             list_to_add = (cu->list_in_scope == &file_symbols
19658                            && cu->language == language_cplus
19659                            ? &global_symbols : cu->list_in_scope);
19660           }
19661           break;
19662         case DW_TAG_imported_declaration:
19663         case DW_TAG_namespace:
19664           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19665           list_to_add = &global_symbols;
19666           break;
19667         case DW_TAG_module:
19668           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
19669           SYMBOL_DOMAIN (sym) = MODULE_DOMAIN;
19670           list_to_add = &global_symbols;
19671           break;
19672         case DW_TAG_common_block:
19673           SYMBOL_ACLASS_INDEX (sym) = LOC_COMMON_BLOCK;
19674           SYMBOL_DOMAIN (sym) = COMMON_BLOCK_DOMAIN;
19675           add_symbol_to_list (sym, cu->list_in_scope);
19676           break;
19677         default:
19678           /* Not a tag we recognize.  Hopefully we aren't processing
19679              trash data, but since we must specifically ignore things
19680              we don't recognize, there is nothing else we should do at
19681              this point.  */
19682           complaint (&symfile_complaints, _("unsupported tag: '%s'"),
19683                      dwarf_tag_name (die->tag));
19684           break;
19685         }
19686
19687       if (suppress_add)
19688         {
19689           sym->hash_next = objfile->template_symbols;
19690           objfile->template_symbols = sym;
19691           list_to_add = NULL;
19692         }
19693
19694       if (list_to_add != NULL)
19695         add_symbol_to_list (sym, list_to_add);
19696
19697       /* For the benefit of old versions of GCC, check for anonymous
19698          namespaces based on the demangled name.  */
19699       if (!cu->processing_has_namespace_info
19700           && cu->language == language_cplus)
19701         cp_scan_for_anonymous_namespaces (sym, objfile);
19702     }
19703   return (sym);
19704 }
19705
19706 /* A wrapper for new_symbol_full that always allocates a new symbol.  */
19707
19708 static struct symbol *
19709 new_symbol (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
19710 {
19711   return new_symbol_full (die, type, cu, NULL);
19712 }
19713
19714 /* Given an attr with a DW_FORM_dataN value in host byte order,
19715    zero-extend it as appropriate for the symbol's type.  The DWARF
19716    standard (v4) is not entirely clear about the meaning of using
19717    DW_FORM_dataN for a constant with a signed type, where the type is
19718    wider than the data.  The conclusion of a discussion on the DWARF
19719    list was that this is unspecified.  We choose to always zero-extend
19720    because that is the interpretation long in use by GCC.  */
19721
19722 static gdb_byte *
19723 dwarf2_const_value_data (const struct attribute *attr, struct obstack *obstack,
19724                          struct dwarf2_cu *cu, LONGEST *value, int bits)
19725 {
19726   struct objfile *objfile = cu->objfile;
19727   enum bfd_endian byte_order = bfd_big_endian (objfile->obfd) ?
19728                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE;
19729   LONGEST l = DW_UNSND (attr);
19730
19731   if (bits < sizeof (*value) * 8)
19732     {
19733       l &= ((LONGEST) 1 << bits) - 1;
19734       *value = l;
19735     }
19736   else if (bits == sizeof (*value) * 8)
19737     *value = l;
19738   else
19739     {
19740       gdb_byte *bytes = (gdb_byte *) obstack_alloc (obstack, bits / 8);
19741       store_unsigned_integer (bytes, bits / 8, byte_order, l);
19742       return bytes;
19743     }
19744
19745   return NULL;
19746 }
19747
19748 /* Read a constant value from an attribute.  Either set *VALUE, or if
19749    the value does not fit in *VALUE, set *BYTES - either already
19750    allocated on the objfile obstack, or newly allocated on OBSTACK,
19751    or, set *BATON, if we translated the constant to a location
19752    expression.  */
19753
19754 static void
19755 dwarf2_const_value_attr (const struct attribute *attr, struct type *type,
19756                          const char *name, struct obstack *obstack,
19757                          struct dwarf2_cu *cu,
19758                          LONGEST *value, const gdb_byte **bytes,
19759                          struct dwarf2_locexpr_baton **baton)
19760 {
19761   struct objfile *objfile = cu->objfile;
19762   struct comp_unit_head *cu_header = &cu->header;
19763   struct dwarf_block *blk;
19764   enum bfd_endian byte_order = (bfd_big_endian (objfile->obfd) ?
19765                                 BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
19766
19767   *value = 0;
19768   *bytes = NULL;
19769   *baton = NULL;
19770
19771   switch (attr->form)
19772     {
19773     case DW_FORM_addr:
19774     case DW_FORM_GNU_addr_index:
19775       {
19776         gdb_byte *data;
19777
19778         if (TYPE_LENGTH (type) != cu_header->addr_size)
19779           dwarf2_const_value_length_mismatch_complaint (name,
19780                                                         cu_header->addr_size,
19781                                                         TYPE_LENGTH (type));
19782         /* Symbols of this form are reasonably rare, so we just
19783            piggyback on the existing location code rather than writing
19784            a new implementation of symbol_computed_ops.  */
19785         *baton = XOBNEW (obstack, struct dwarf2_locexpr_baton);
19786         (*baton)->per_cu = cu->per_cu;
19787         gdb_assert ((*baton)->per_cu);
19788
19789         (*baton)->size = 2 + cu_header->addr_size;
19790         data = (gdb_byte *) obstack_alloc (obstack, (*baton)->size);
19791         (*baton)->data = data;
19792
19793         data[0] = DW_OP_addr;
19794         store_unsigned_integer (&data[1], cu_header->addr_size,
19795                                 byte_order, DW_ADDR (attr));
19796         data[cu_header->addr_size + 1] = DW_OP_stack_value;
19797       }
19798       break;
19799     case DW_FORM_string:
19800     case DW_FORM_strp:
19801     case DW_FORM_GNU_str_index:
19802     case DW_FORM_GNU_strp_alt:
19803       /* DW_STRING is already allocated on the objfile obstack, point
19804          directly to it.  */
19805       *bytes = (const gdb_byte *) DW_STRING (attr);
19806       break;
19807     case DW_FORM_block1:
19808     case DW_FORM_block2:
19809     case DW_FORM_block4:
19810     case DW_FORM_block:
19811     case DW_FORM_exprloc:
19812     case DW_FORM_data16:
19813       blk = DW_BLOCK (attr);
19814       if (TYPE_LENGTH (type) != blk->size)
19815         dwarf2_const_value_length_mismatch_complaint (name, blk->size,
19816                                                       TYPE_LENGTH (type));
19817       *bytes = blk->data;
19818       break;
19819
19820       /* The DW_AT_const_value attributes are supposed to carry the
19821          symbol's value "represented as it would be on the target
19822          architecture."  By the time we get here, it's already been
19823          converted to host endianness, so we just need to sign- or
19824          zero-extend it as appropriate.  */
19825     case DW_FORM_data1:
19826       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 8);
19827       break;
19828     case DW_FORM_data2:
19829       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 16);
19830       break;
19831     case DW_FORM_data4:
19832       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 32);
19833       break;
19834     case DW_FORM_data8:
19835       *bytes = dwarf2_const_value_data (attr, obstack, cu, value, 64);
19836       break;
19837
19838     case DW_FORM_sdata:
19839     case DW_FORM_implicit_const:
19840       *value = DW_SND (attr);
19841       break;
19842
19843     case DW_FORM_udata:
19844       *value = DW_UNSND (attr);
19845       break;
19846
19847     default:
19848       complaint (&symfile_complaints,
19849                  _("unsupported const value attribute form: '%s'"),
19850                  dwarf_form_name (attr->form));
19851       *value = 0;
19852       break;
19853     }
19854 }
19855
19856
19857 /* Copy constant value from an attribute to a symbol.  */
19858
19859 static void
19860 dwarf2_const_value (const struct attribute *attr, struct symbol *sym,
19861                     struct dwarf2_cu *cu)
19862 {
19863   struct objfile *objfile = cu->objfile;
19864   LONGEST value;
19865   const gdb_byte *bytes;
19866   struct dwarf2_locexpr_baton *baton;
19867
19868   dwarf2_const_value_attr (attr, SYMBOL_TYPE (sym),
19869                            SYMBOL_PRINT_NAME (sym),
19870                            &objfile->objfile_obstack, cu,
19871                            &value, &bytes, &baton);
19872
19873   if (baton != NULL)
19874     {
19875       SYMBOL_LOCATION_BATON (sym) = baton;
19876       SYMBOL_ACLASS_INDEX (sym) = dwarf2_locexpr_index;
19877     }
19878   else if (bytes != NULL)
19879      {
19880       SYMBOL_VALUE_BYTES (sym) = bytes;
19881       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST_BYTES;
19882     }
19883   else
19884     {
19885       SYMBOL_VALUE (sym) = value;
19886       SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
19887     }
19888 }
19889
19890 /* Return the type of the die in question using its DW_AT_type attribute.  */
19891
19892 static struct type *
19893 die_type (struct die_info *die, struct dwarf2_cu *cu)
19894 {
19895   struct attribute *type_attr;
19896
19897   type_attr = dwarf2_attr (die, DW_AT_type, cu);
19898   if (!type_attr)
19899     {
19900       /* A missing DW_AT_type represents a void type.  */
19901       return objfile_type (cu->objfile)->builtin_void;
19902     }
19903
19904   return lookup_die_type (die, type_attr, cu);
19905 }
19906
19907 /* True iff CU's producer generates GNAT Ada auxiliary information
19908    that allows to find parallel types through that information instead
19909    of having to do expensive parallel lookups by type name.  */
19910
19911 static int
19912 need_gnat_info (struct dwarf2_cu *cu)
19913 {
19914   /* FIXME: brobecker/2010-10-12: As of now, only the AdaCore version
19915      of GNAT produces this auxiliary information, without any indication
19916      that it is produced.  Part of enhancing the FSF version of GNAT
19917      to produce that information will be to put in place an indicator
19918      that we can use in order to determine whether the descriptive type
19919      info is available or not.  One suggestion that has been made is
19920      to use a new attribute, attached to the CU die.  For now, assume
19921      that the descriptive type info is not available.  */
19922   return 0;
19923 }
19924
19925 /* Return the auxiliary type of the die in question using its
19926    DW_AT_GNAT_descriptive_type attribute.  Returns NULL if the
19927    attribute is not present.  */
19928
19929 static struct type *
19930 die_descriptive_type (struct die_info *die, struct dwarf2_cu *cu)
19931 {
19932   struct attribute *type_attr;
19933
19934   type_attr = dwarf2_attr (die, DW_AT_GNAT_descriptive_type, cu);
19935   if (!type_attr)
19936     return NULL;
19937
19938   return lookup_die_type (die, type_attr, cu);
19939 }
19940
19941 /* If DIE has a descriptive_type attribute, then set the TYPE's
19942    descriptive type accordingly.  */
19943
19944 static void
19945 set_descriptive_type (struct type *type, struct die_info *die,
19946                       struct dwarf2_cu *cu)
19947 {
19948   struct type *descriptive_type = die_descriptive_type (die, cu);
19949
19950   if (descriptive_type)
19951     {
19952       ALLOCATE_GNAT_AUX_TYPE (type);
19953       TYPE_DESCRIPTIVE_TYPE (type) = descriptive_type;
19954     }
19955 }
19956
19957 /* Return the containing type of the die in question using its
19958    DW_AT_containing_type attribute.  */
19959
19960 static struct type *
19961 die_containing_type (struct die_info *die, struct dwarf2_cu *cu)
19962 {
19963   struct attribute *type_attr;
19964
19965   type_attr = dwarf2_attr (die, DW_AT_containing_type, cu);
19966   if (!type_attr)
19967     error (_("Dwarf Error: Problem turning containing type into gdb type "
19968              "[in module %s]"), objfile_name (cu->objfile));
19969
19970   return lookup_die_type (die, type_attr, cu);
19971 }
19972
19973 /* Return an error marker type to use for the ill formed type in DIE/CU.  */
19974
19975 static struct type *
19976 build_error_marker_type (struct dwarf2_cu *cu, struct die_info *die)
19977 {
19978   struct objfile *objfile = dwarf2_per_objfile->objfile;
19979   char *message, *saved;
19980
19981   message = xstrprintf (_("<unknown type in %s, CU 0x%x, DIE 0x%x>"),
19982                         objfile_name (objfile),
19983                         to_underlying (cu->header.sect_off),
19984                         to_underlying (die->sect_off));
19985   saved = (char *) obstack_copy0 (&objfile->objfile_obstack,
19986                                   message, strlen (message));
19987   xfree (message);
19988
19989   return init_type (objfile, TYPE_CODE_ERROR, 0, saved);
19990 }
19991
19992 /* Look up the type of DIE in CU using its type attribute ATTR.
19993    ATTR must be one of: DW_AT_type, DW_AT_GNAT_descriptive_type,
19994    DW_AT_containing_type.
19995    If there is no type substitute an error marker.  */
19996
19997 static struct type *
19998 lookup_die_type (struct die_info *die, const struct attribute *attr,
19999                  struct dwarf2_cu *cu)
20000 {
20001   struct objfile *objfile = cu->objfile;
20002   struct type *this_type;
20003
20004   gdb_assert (attr->name == DW_AT_type
20005               || attr->name == DW_AT_GNAT_descriptive_type
20006               || attr->name == DW_AT_containing_type);
20007
20008   /* First see if we have it cached.  */
20009
20010   if (attr->form == DW_FORM_GNU_ref_alt)
20011     {
20012       struct dwarf2_per_cu_data *per_cu;
20013       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20014
20015       per_cu = dwarf2_find_containing_comp_unit (sect_off, 1, cu->objfile);
20016       this_type = get_die_type_at_offset (sect_off, per_cu);
20017     }
20018   else if (attr_form_is_ref (attr))
20019     {
20020       sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
20021
20022       this_type = get_die_type_at_offset (sect_off, cu->per_cu);
20023     }
20024   else if (attr->form == DW_FORM_ref_sig8)
20025     {
20026       ULONGEST signature = DW_SIGNATURE (attr);
20027
20028       return get_signatured_type (die, signature, cu);
20029     }
20030   else
20031     {
20032       complaint (&symfile_complaints,
20033                  _("Dwarf Error: Bad type attribute %s in DIE"
20034                    " at 0x%x [in module %s]"),
20035                  dwarf_attr_name (attr->name), to_underlying (die->sect_off),
20036                  objfile_name (objfile));
20037       return build_error_marker_type (cu, die);
20038     }
20039
20040   /* If not cached we need to read it in.  */
20041
20042   if (this_type == NULL)
20043     {
20044       struct die_info *type_die = NULL;
20045       struct dwarf2_cu *type_cu = cu;
20046
20047       if (attr_form_is_ref (attr))
20048         type_die = follow_die_ref (die, attr, &type_cu);
20049       if (type_die == NULL)
20050         return build_error_marker_type (cu, die);
20051       /* If we find the type now, it's probably because the type came
20052          from an inter-CU reference and the type's CU got expanded before
20053          ours.  */
20054       this_type = read_type_die (type_die, type_cu);
20055     }
20056
20057   /* If we still don't have a type use an error marker.  */
20058
20059   if (this_type == NULL)
20060     return build_error_marker_type (cu, die);
20061
20062   return this_type;
20063 }
20064
20065 /* Return the type in DIE, CU.
20066    Returns NULL for invalid types.
20067
20068    This first does a lookup in die_type_hash,
20069    and only reads the die in if necessary.
20070
20071    NOTE: This can be called when reading in partial or full symbols.  */
20072
20073 static struct type *
20074 read_type_die (struct die_info *die, struct dwarf2_cu *cu)
20075 {
20076   struct type *this_type;
20077
20078   this_type = get_die_type (die, cu);
20079   if (this_type)
20080     return this_type;
20081
20082   return read_type_die_1 (die, cu);
20083 }
20084
20085 /* Read the type in DIE, CU.
20086    Returns NULL for invalid types.  */
20087
20088 static struct type *
20089 read_type_die_1 (struct die_info *die, struct dwarf2_cu *cu)
20090 {
20091   struct type *this_type = NULL;
20092
20093   switch (die->tag)
20094     {
20095     case DW_TAG_class_type:
20096     case DW_TAG_interface_type:
20097     case DW_TAG_structure_type:
20098     case DW_TAG_union_type:
20099       this_type = read_structure_type (die, cu);
20100       break;
20101     case DW_TAG_enumeration_type:
20102       this_type = read_enumeration_type (die, cu);
20103       break;
20104     case DW_TAG_subprogram:
20105     case DW_TAG_subroutine_type:
20106     case DW_TAG_inlined_subroutine:
20107       this_type = read_subroutine_type (die, cu);
20108       break;
20109     case DW_TAG_array_type:
20110       this_type = read_array_type (die, cu);
20111       break;
20112     case DW_TAG_set_type:
20113       this_type = read_set_type (die, cu);
20114       break;
20115     case DW_TAG_pointer_type:
20116       this_type = read_tag_pointer_type (die, cu);
20117       break;
20118     case DW_TAG_ptr_to_member_type:
20119       this_type = read_tag_ptr_to_member_type (die, cu);
20120       break;
20121     case DW_TAG_reference_type:
20122       this_type = read_tag_reference_type (die, cu, TYPE_CODE_REF);
20123       break;
20124     case DW_TAG_rvalue_reference_type:
20125       this_type = read_tag_reference_type (die, cu, TYPE_CODE_RVALUE_REF);
20126       break;
20127     case DW_TAG_const_type:
20128       this_type = read_tag_const_type (die, cu);
20129       break;
20130     case DW_TAG_volatile_type:
20131       this_type = read_tag_volatile_type (die, cu);
20132       break;
20133     case DW_TAG_restrict_type:
20134       this_type = read_tag_restrict_type (die, cu);
20135       break;
20136     case DW_TAG_string_type:
20137       this_type = read_tag_string_type (die, cu);
20138       break;
20139     case DW_TAG_typedef:
20140       this_type = read_typedef (die, cu);
20141       break;
20142     case DW_TAG_subrange_type:
20143       this_type = read_subrange_type (die, cu);
20144       break;
20145     case DW_TAG_base_type:
20146       this_type = read_base_type (die, cu);
20147       break;
20148     case DW_TAG_unspecified_type:
20149       this_type = read_unspecified_type (die, cu);
20150       break;
20151     case DW_TAG_namespace:
20152       this_type = read_namespace_type (die, cu);
20153       break;
20154     case DW_TAG_module:
20155       this_type = read_module_type (die, cu);
20156       break;
20157     case DW_TAG_atomic_type:
20158       this_type = read_tag_atomic_type (die, cu);
20159       break;
20160     default:
20161       complaint (&symfile_complaints,
20162                  _("unexpected tag in read_type_die: '%s'"),
20163                  dwarf_tag_name (die->tag));
20164       break;
20165     }
20166
20167   return this_type;
20168 }
20169
20170 /* See if we can figure out if the class lives in a namespace.  We do
20171    this by looking for a member function; its demangled name will
20172    contain namespace info, if there is any.
20173    Return the computed name or NULL.
20174    Space for the result is allocated on the objfile's obstack.
20175    This is the full-die version of guess_partial_die_structure_name.
20176    In this case we know DIE has no useful parent.  */
20177
20178 static char *
20179 guess_full_die_structure_name (struct die_info *die, struct dwarf2_cu *cu)
20180 {
20181   struct die_info *spec_die;
20182   struct dwarf2_cu *spec_cu;
20183   struct die_info *child;
20184
20185   spec_cu = cu;
20186   spec_die = die_specification (die, &spec_cu);
20187   if (spec_die != NULL)
20188     {
20189       die = spec_die;
20190       cu = spec_cu;
20191     }
20192
20193   for (child = die->child;
20194        child != NULL;
20195        child = child->sibling)
20196     {
20197       if (child->tag == DW_TAG_subprogram)
20198         {
20199           const char *linkage_name = dw2_linkage_name (child, cu);
20200
20201           if (linkage_name != NULL)
20202             {
20203               char *actual_name
20204                 = language_class_name_from_physname (cu->language_defn,
20205                                                      linkage_name);
20206               char *name = NULL;
20207
20208               if (actual_name != NULL)
20209                 {
20210                   const char *die_name = dwarf2_name (die, cu);
20211
20212                   if (die_name != NULL
20213                       && strcmp (die_name, actual_name) != 0)
20214                     {
20215                       /* Strip off the class name from the full name.
20216                          We want the prefix.  */
20217                       int die_name_len = strlen (die_name);
20218                       int actual_name_len = strlen (actual_name);
20219
20220                       /* Test for '::' as a sanity check.  */
20221                       if (actual_name_len > die_name_len + 2
20222                           && actual_name[actual_name_len
20223                                          - die_name_len - 1] == ':')
20224                         name = (char *) obstack_copy0 (
20225                           &cu->objfile->per_bfd->storage_obstack,
20226                           actual_name, actual_name_len - die_name_len - 2);
20227                     }
20228                 }
20229               xfree (actual_name);
20230               return name;
20231             }
20232         }
20233     }
20234
20235   return NULL;
20236 }
20237
20238 /* GCC might emit a nameless typedef that has a linkage name.  Determine the
20239    prefix part in such case.  See
20240    http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20241
20242 static const char *
20243 anonymous_struct_prefix (struct die_info *die, struct dwarf2_cu *cu)
20244 {
20245   struct attribute *attr;
20246   const char *base;
20247
20248   if (die->tag != DW_TAG_class_type && die->tag != DW_TAG_interface_type
20249       && die->tag != DW_TAG_structure_type && die->tag != DW_TAG_union_type)
20250     return NULL;
20251
20252   if (dwarf2_string_attr (die, DW_AT_name, cu) != NULL)
20253     return NULL;
20254
20255   attr = dw2_linkage_name_attr (die, cu);
20256   if (attr == NULL || DW_STRING (attr) == NULL)
20257     return NULL;
20258
20259   /* dwarf2_name had to be already called.  */
20260   gdb_assert (DW_STRING_IS_CANONICAL (attr));
20261
20262   /* Strip the base name, keep any leading namespaces/classes.  */
20263   base = strrchr (DW_STRING (attr), ':');
20264   if (base == NULL || base == DW_STRING (attr) || base[-1] != ':')
20265     return "";
20266
20267   return (char *) obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20268                                  DW_STRING (attr),
20269                                  &base[-1] - DW_STRING (attr));
20270 }
20271
20272 /* Return the name of the namespace/class that DIE is defined within,
20273    or "" if we can't tell.  The caller should not xfree the result.
20274
20275    For example, if we're within the method foo() in the following
20276    code:
20277
20278    namespace N {
20279      class C {
20280        void foo () {
20281        }
20282      };
20283    }
20284
20285    then determine_prefix on foo's die will return "N::C".  */
20286
20287 static const char *
20288 determine_prefix (struct die_info *die, struct dwarf2_cu *cu)
20289 {
20290   struct die_info *parent, *spec_die;
20291   struct dwarf2_cu *spec_cu;
20292   struct type *parent_type;
20293   const char *retval;
20294
20295   if (cu->language != language_cplus
20296       && cu->language != language_fortran && cu->language != language_d
20297       && cu->language != language_rust)
20298     return "";
20299
20300   retval = anonymous_struct_prefix (die, cu);
20301   if (retval)
20302     return retval;
20303
20304   /* We have to be careful in the presence of DW_AT_specification.
20305      For example, with GCC 3.4, given the code
20306
20307      namespace N {
20308        void foo() {
20309          // Definition of N::foo.
20310        }
20311      }
20312
20313      then we'll have a tree of DIEs like this:
20314
20315      1: DW_TAG_compile_unit
20316        2: DW_TAG_namespace        // N
20317          3: DW_TAG_subprogram     // declaration of N::foo
20318        4: DW_TAG_subprogram       // definition of N::foo
20319             DW_AT_specification   // refers to die #3
20320
20321      Thus, when processing die #4, we have to pretend that we're in
20322      the context of its DW_AT_specification, namely the contex of die
20323      #3.  */
20324   spec_cu = cu;
20325   spec_die = die_specification (die, &spec_cu);
20326   if (spec_die == NULL)
20327     parent = die->parent;
20328   else
20329     {
20330       parent = spec_die->parent;
20331       cu = spec_cu;
20332     }
20333
20334   if (parent == NULL)
20335     return "";
20336   else if (parent->building_fullname)
20337     {
20338       const char *name;
20339       const char *parent_name;
20340
20341       /* It has been seen on RealView 2.2 built binaries,
20342          DW_TAG_template_type_param types actually _defined_ as
20343          children of the parent class:
20344
20345          enum E {};
20346          template class <class Enum> Class{};
20347          Class<enum E> class_e;
20348
20349          1: DW_TAG_class_type (Class)
20350            2: DW_TAG_enumeration_type (E)
20351              3: DW_TAG_enumerator (enum1:0)
20352              3: DW_TAG_enumerator (enum2:1)
20353              ...
20354            2: DW_TAG_template_type_param
20355               DW_AT_type  DW_FORM_ref_udata (E)
20356
20357          Besides being broken debug info, it can put GDB into an
20358          infinite loop.  Consider:
20359
20360          When we're building the full name for Class<E>, we'll start
20361          at Class, and go look over its template type parameters,
20362          finding E.  We'll then try to build the full name of E, and
20363          reach here.  We're now trying to build the full name of E,
20364          and look over the parent DIE for containing scope.  In the
20365          broken case, if we followed the parent DIE of E, we'd again
20366          find Class, and once again go look at its template type
20367          arguments, etc., etc.  Simply don't consider such parent die
20368          as source-level parent of this die (it can't be, the language
20369          doesn't allow it), and break the loop here.  */
20370       name = dwarf2_name (die, cu);
20371       parent_name = dwarf2_name (parent, cu);
20372       complaint (&symfile_complaints,
20373                  _("template param type '%s' defined within parent '%s'"),
20374                  name ? name : "<unknown>",
20375                  parent_name ? parent_name : "<unknown>");
20376       return "";
20377     }
20378   else
20379     switch (parent->tag)
20380       {
20381       case DW_TAG_namespace:
20382         parent_type = read_type_die (parent, cu);
20383         /* GCC 4.0 and 4.1 had a bug (PR c++/28460) where they generated bogus
20384            DW_TAG_namespace DIEs with a name of "::" for the global namespace.
20385            Work around this problem here.  */
20386         if (cu->language == language_cplus
20387             && strcmp (TYPE_TAG_NAME (parent_type), "::") == 0)
20388           return "";
20389         /* We give a name to even anonymous namespaces.  */
20390         return TYPE_TAG_NAME (parent_type);
20391       case DW_TAG_class_type:
20392       case DW_TAG_interface_type:
20393       case DW_TAG_structure_type:
20394       case DW_TAG_union_type:
20395       case DW_TAG_module:
20396         parent_type = read_type_die (parent, cu);
20397         if (TYPE_TAG_NAME (parent_type) != NULL)
20398           return TYPE_TAG_NAME (parent_type);
20399         else
20400           /* An anonymous structure is only allowed non-static data
20401              members; no typedefs, no member functions, et cetera.
20402              So it does not need a prefix.  */
20403           return "";
20404       case DW_TAG_compile_unit:
20405       case DW_TAG_partial_unit:
20406         /* gcc-4.5 -gdwarf-4 can drop the enclosing namespace.  Cope.  */
20407         if (cu->language == language_cplus
20408             && !VEC_empty (dwarf2_section_info_def, dwarf2_per_objfile->types)
20409             && die->child != NULL
20410             && (die->tag == DW_TAG_class_type
20411                 || die->tag == DW_TAG_structure_type
20412                 || die->tag == DW_TAG_union_type))
20413           {
20414             char *name = guess_full_die_structure_name (die, cu);
20415             if (name != NULL)
20416               return name;
20417           }
20418         return "";
20419       case DW_TAG_enumeration_type:
20420         parent_type = read_type_die (parent, cu);
20421         if (TYPE_DECLARED_CLASS (parent_type))
20422           {
20423             if (TYPE_TAG_NAME (parent_type) != NULL)
20424               return TYPE_TAG_NAME (parent_type);
20425             return "";
20426           }
20427         /* Fall through.  */
20428       default:
20429         return determine_prefix (parent, cu);
20430       }
20431 }
20432
20433 /* Return a newly-allocated string formed by concatenating PREFIX and SUFFIX
20434    with appropriate separator.  If PREFIX or SUFFIX is NULL or empty, then
20435    simply copy the SUFFIX or PREFIX, respectively.  If OBS is non-null, perform
20436    an obconcat, otherwise allocate storage for the result.  The CU argument is
20437    used to determine the language and hence, the appropriate separator.  */
20438
20439 #define MAX_SEP_LEN 7  /* strlen ("__") + strlen ("_MOD_")  */
20440
20441 static char *
20442 typename_concat (struct obstack *obs, const char *prefix, const char *suffix,
20443                  int physname, struct dwarf2_cu *cu)
20444 {
20445   const char *lead = "";
20446   const char *sep;
20447
20448   if (suffix == NULL || suffix[0] == '\0'
20449       || prefix == NULL || prefix[0] == '\0')
20450     sep = "";
20451   else if (cu->language == language_d)
20452     {
20453       /* For D, the 'main' function could be defined in any module, but it
20454          should never be prefixed.  */
20455       if (strcmp (suffix, "D main") == 0)
20456         {
20457           prefix = "";
20458           sep = "";
20459         }
20460       else
20461         sep = ".";
20462     }
20463   else if (cu->language == language_fortran && physname)
20464     {
20465       /* This is gfortran specific mangling.  Normally DW_AT_linkage_name or
20466          DW_AT_MIPS_linkage_name is preferred and used instead.  */
20467
20468       lead = "__";
20469       sep = "_MOD_";
20470     }
20471   else
20472     sep = "::";
20473
20474   if (prefix == NULL)
20475     prefix = "";
20476   if (suffix == NULL)
20477     suffix = "";
20478
20479   if (obs == NULL)
20480     {
20481       char *retval
20482         = ((char *)
20483            xmalloc (strlen (prefix) + MAX_SEP_LEN + strlen (suffix) + 1));
20484
20485       strcpy (retval, lead);
20486       strcat (retval, prefix);
20487       strcat (retval, sep);
20488       strcat (retval, suffix);
20489       return retval;
20490     }
20491   else
20492     {
20493       /* We have an obstack.  */
20494       return obconcat (obs, lead, prefix, sep, suffix, (char *) NULL);
20495     }
20496 }
20497
20498 /* Return sibling of die, NULL if no sibling.  */
20499
20500 static struct die_info *
20501 sibling_die (struct die_info *die)
20502 {
20503   return die->sibling;
20504 }
20505
20506 /* Get name of a die, return NULL if not found.  */
20507
20508 static const char *
20509 dwarf2_canonicalize_name (const char *name, struct dwarf2_cu *cu,
20510                           struct obstack *obstack)
20511 {
20512   if (name && cu->language == language_cplus)
20513     {
20514       std::string canon_name = cp_canonicalize_string (name);
20515
20516       if (!canon_name.empty ())
20517         {
20518           if (canon_name != name)
20519             name = (const char *) obstack_copy0 (obstack,
20520                                                  canon_name.c_str (),
20521                                                  canon_name.length ());
20522         }
20523     }
20524
20525   return name;
20526 }
20527
20528 /* Get name of a die, return NULL if not found.
20529    Anonymous namespaces are converted to their magic string.  */
20530
20531 static const char *
20532 dwarf2_name (struct die_info *die, struct dwarf2_cu *cu)
20533 {
20534   struct attribute *attr;
20535
20536   attr = dwarf2_attr (die, DW_AT_name, cu);
20537   if ((!attr || !DW_STRING (attr))
20538       && die->tag != DW_TAG_namespace
20539       && die->tag != DW_TAG_class_type
20540       && die->tag != DW_TAG_interface_type
20541       && die->tag != DW_TAG_structure_type
20542       && die->tag != DW_TAG_union_type)
20543     return NULL;
20544
20545   switch (die->tag)
20546     {
20547     case DW_TAG_compile_unit:
20548     case DW_TAG_partial_unit:
20549       /* Compilation units have a DW_AT_name that is a filename, not
20550          a source language identifier.  */
20551     case DW_TAG_enumeration_type:
20552     case DW_TAG_enumerator:
20553       /* These tags always have simple identifiers already; no need
20554          to canonicalize them.  */
20555       return DW_STRING (attr);
20556
20557     case DW_TAG_namespace:
20558       if (attr != NULL && DW_STRING (attr) != NULL)
20559         return DW_STRING (attr);
20560       return CP_ANONYMOUS_NAMESPACE_STR;
20561
20562     case DW_TAG_class_type:
20563     case DW_TAG_interface_type:
20564     case DW_TAG_structure_type:
20565     case DW_TAG_union_type:
20566       /* Some GCC versions emit spurious DW_AT_name attributes for unnamed
20567          structures or unions.  These were of the form "._%d" in GCC 4.1,
20568          or simply "<anonymous struct>" or "<anonymous union>" in GCC 4.3
20569          and GCC 4.4.  We work around this problem by ignoring these.  */
20570       if (attr && DW_STRING (attr)
20571           && (startswith (DW_STRING (attr), "._")
20572               || startswith (DW_STRING (attr), "<anonymous")))
20573         return NULL;
20574
20575       /* GCC might emit a nameless typedef that has a linkage name.  See
20576          http://gcc.gnu.org/bugzilla/show_bug.cgi?id=47510.  */
20577       if (!attr || DW_STRING (attr) == NULL)
20578         {
20579           char *demangled = NULL;
20580
20581           attr = dw2_linkage_name_attr (die, cu);
20582           if (attr == NULL || DW_STRING (attr) == NULL)
20583             return NULL;
20584
20585           /* Avoid demangling DW_STRING (attr) the second time on a second
20586              call for the same DIE.  */
20587           if (!DW_STRING_IS_CANONICAL (attr))
20588             demangled = gdb_demangle (DW_STRING (attr), DMGL_TYPES);
20589
20590           if (demangled)
20591             {
20592               const char *base;
20593
20594               /* FIXME: we already did this for the partial symbol... */
20595               DW_STRING (attr)
20596                 = ((const char *)
20597                    obstack_copy0 (&cu->objfile->per_bfd->storage_obstack,
20598                                   demangled, strlen (demangled)));
20599               DW_STRING_IS_CANONICAL (attr) = 1;
20600               xfree (demangled);
20601
20602               /* Strip any leading namespaces/classes, keep only the base name.
20603                  DW_AT_name for named DIEs does not contain the prefixes.  */
20604               base = strrchr (DW_STRING (attr), ':');
20605               if (base && base > DW_STRING (attr) && base[-1] == ':')
20606                 return &base[1];
20607               else
20608                 return DW_STRING (attr);
20609             }
20610         }
20611       break;
20612
20613     default:
20614       break;
20615     }
20616
20617   if (!DW_STRING_IS_CANONICAL (attr))
20618     {
20619       DW_STRING (attr)
20620         = dwarf2_canonicalize_name (DW_STRING (attr), cu,
20621                                     &cu->objfile->per_bfd->storage_obstack);
20622       DW_STRING_IS_CANONICAL (attr) = 1;
20623     }
20624   return DW_STRING (attr);
20625 }
20626
20627 /* Return the die that this die in an extension of, or NULL if there
20628    is none.  *EXT_CU is the CU containing DIE on input, and the CU
20629    containing the return value on output.  */
20630
20631 static struct die_info *
20632 dwarf2_extension (struct die_info *die, struct dwarf2_cu **ext_cu)
20633 {
20634   struct attribute *attr;
20635
20636   attr = dwarf2_attr (die, DW_AT_extension, *ext_cu);
20637   if (attr == NULL)
20638     return NULL;
20639
20640   return follow_die_ref (die, attr, ext_cu);
20641 }
20642
20643 /* Convert a DIE tag into its string name.  */
20644
20645 static const char *
20646 dwarf_tag_name (unsigned tag)
20647 {
20648   const char *name = get_DW_TAG_name (tag);
20649
20650   if (name == NULL)
20651     return "DW_TAG_<unknown>";
20652
20653   return name;
20654 }
20655
20656 /* Convert a DWARF attribute code into its string name.  */
20657
20658 static const char *
20659 dwarf_attr_name (unsigned attr)
20660 {
20661   const char *name;
20662
20663 #ifdef MIPS /* collides with DW_AT_HP_block_index */
20664   if (attr == DW_AT_MIPS_fde)
20665     return "DW_AT_MIPS_fde";
20666 #else
20667   if (attr == DW_AT_HP_block_index)
20668     return "DW_AT_HP_block_index";
20669 #endif
20670
20671   name = get_DW_AT_name (attr);
20672
20673   if (name == NULL)
20674     return "DW_AT_<unknown>";
20675
20676   return name;
20677 }
20678
20679 /* Convert a DWARF value form code into its string name.  */
20680
20681 static const char *
20682 dwarf_form_name (unsigned form)
20683 {
20684   const char *name = get_DW_FORM_name (form);
20685
20686   if (name == NULL)
20687     return "DW_FORM_<unknown>";
20688
20689   return name;
20690 }
20691
20692 static const char *
20693 dwarf_bool_name (unsigned mybool)
20694 {
20695   if (mybool)
20696     return "TRUE";
20697   else
20698     return "FALSE";
20699 }
20700
20701 /* Convert a DWARF type code into its string name.  */
20702
20703 static const char *
20704 dwarf_type_encoding_name (unsigned enc)
20705 {
20706   const char *name = get_DW_ATE_name (enc);
20707
20708   if (name == NULL)
20709     return "DW_ATE_<unknown>";
20710
20711   return name;
20712 }
20713
20714 static void
20715 dump_die_shallow (struct ui_file *f, int indent, struct die_info *die)
20716 {
20717   unsigned int i;
20718
20719   print_spaces (indent, f);
20720   fprintf_unfiltered (f, "Die: %s (abbrev %d, offset 0x%x)\n",
20721                       dwarf_tag_name (die->tag), die->abbrev,
20722                       to_underlying (die->sect_off));
20723
20724   if (die->parent != NULL)
20725     {
20726       print_spaces (indent, f);
20727       fprintf_unfiltered (f, "  parent at offset: 0x%x\n",
20728                           to_underlying (die->parent->sect_off));
20729     }
20730
20731   print_spaces (indent, f);
20732   fprintf_unfiltered (f, "  has children: %s\n",
20733            dwarf_bool_name (die->child != NULL));
20734
20735   print_spaces (indent, f);
20736   fprintf_unfiltered (f, "  attributes:\n");
20737
20738   for (i = 0; i < die->num_attrs; ++i)
20739     {
20740       print_spaces (indent, f);
20741       fprintf_unfiltered (f, "    %s (%s) ",
20742                dwarf_attr_name (die->attrs[i].name),
20743                dwarf_form_name (die->attrs[i].form));
20744
20745       switch (die->attrs[i].form)
20746         {
20747         case DW_FORM_addr:
20748         case DW_FORM_GNU_addr_index:
20749           fprintf_unfiltered (f, "address: ");
20750           fputs_filtered (hex_string (DW_ADDR (&die->attrs[i])), f);
20751           break;
20752         case DW_FORM_block2:
20753         case DW_FORM_block4:
20754         case DW_FORM_block:
20755         case DW_FORM_block1:
20756           fprintf_unfiltered (f, "block: size %s",
20757                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20758           break;
20759         case DW_FORM_exprloc:
20760           fprintf_unfiltered (f, "expression: size %s",
20761                               pulongest (DW_BLOCK (&die->attrs[i])->size));
20762           break;
20763         case DW_FORM_data16:
20764           fprintf_unfiltered (f, "constant of 16 bytes");
20765           break;
20766         case DW_FORM_ref_addr:
20767           fprintf_unfiltered (f, "ref address: ");
20768           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20769           break;
20770         case DW_FORM_GNU_ref_alt:
20771           fprintf_unfiltered (f, "alt ref address: ");
20772           fputs_filtered (hex_string (DW_UNSND (&die->attrs[i])), f);
20773           break;
20774         case DW_FORM_ref1:
20775         case DW_FORM_ref2:
20776         case DW_FORM_ref4:
20777         case DW_FORM_ref8:
20778         case DW_FORM_ref_udata:
20779           fprintf_unfiltered (f, "constant ref: 0x%lx (adjusted)",
20780                               (long) (DW_UNSND (&die->attrs[i])));
20781           break;
20782         case DW_FORM_data1:
20783         case DW_FORM_data2:
20784         case DW_FORM_data4:
20785         case DW_FORM_data8:
20786         case DW_FORM_udata:
20787         case DW_FORM_sdata:
20788           fprintf_unfiltered (f, "constant: %s",
20789                               pulongest (DW_UNSND (&die->attrs[i])));
20790           break;
20791         case DW_FORM_sec_offset:
20792           fprintf_unfiltered (f, "section offset: %s",
20793                               pulongest (DW_UNSND (&die->attrs[i])));
20794           break;
20795         case DW_FORM_ref_sig8:
20796           fprintf_unfiltered (f, "signature: %s",
20797                               hex_string (DW_SIGNATURE (&die->attrs[i])));
20798           break;
20799         case DW_FORM_string:
20800         case DW_FORM_strp:
20801         case DW_FORM_line_strp:
20802         case DW_FORM_GNU_str_index:
20803         case DW_FORM_GNU_strp_alt:
20804           fprintf_unfiltered (f, "string: \"%s\" (%s canonicalized)",
20805                    DW_STRING (&die->attrs[i])
20806                    ? DW_STRING (&die->attrs[i]) : "",
20807                    DW_STRING_IS_CANONICAL (&die->attrs[i]) ? "is" : "not");
20808           break;
20809         case DW_FORM_flag:
20810           if (DW_UNSND (&die->attrs[i]))
20811             fprintf_unfiltered (f, "flag: TRUE");
20812           else
20813             fprintf_unfiltered (f, "flag: FALSE");
20814           break;
20815         case DW_FORM_flag_present:
20816           fprintf_unfiltered (f, "flag: TRUE");
20817           break;
20818         case DW_FORM_indirect:
20819           /* The reader will have reduced the indirect form to
20820              the "base form" so this form should not occur.  */
20821           fprintf_unfiltered (f, 
20822                               "unexpected attribute form: DW_FORM_indirect");
20823           break;
20824         case DW_FORM_implicit_const:
20825           fprintf_unfiltered (f, "constant: %s",
20826                               plongest (DW_SND (&die->attrs[i])));
20827           break;
20828         default:
20829           fprintf_unfiltered (f, "unsupported attribute form: %d.",
20830                    die->attrs[i].form);
20831           break;
20832         }
20833       fprintf_unfiltered (f, "\n");
20834     }
20835 }
20836
20837 static void
20838 dump_die_for_error (struct die_info *die)
20839 {
20840   dump_die_shallow (gdb_stderr, 0, die);
20841 }
20842
20843 static void
20844 dump_die_1 (struct ui_file *f, int level, int max_level, struct die_info *die)
20845 {
20846   int indent = level * 4;
20847
20848   gdb_assert (die != NULL);
20849
20850   if (level >= max_level)
20851     return;
20852
20853   dump_die_shallow (f, indent, die);
20854
20855   if (die->child != NULL)
20856     {
20857       print_spaces (indent, f);
20858       fprintf_unfiltered (f, "  Children:");
20859       if (level + 1 < max_level)
20860         {
20861           fprintf_unfiltered (f, "\n");
20862           dump_die_1 (f, level + 1, max_level, die->child);
20863         }
20864       else
20865         {
20866           fprintf_unfiltered (f,
20867                               " [not printed, max nesting level reached]\n");
20868         }
20869     }
20870
20871   if (die->sibling != NULL && level > 0)
20872     {
20873       dump_die_1 (f, level, max_level, die->sibling);
20874     }
20875 }
20876
20877 /* This is called from the pdie macro in gdbinit.in.
20878    It's not static so gcc will keep a copy callable from gdb.  */
20879
20880 void
20881 dump_die (struct die_info *die, int max_level)
20882 {
20883   dump_die_1 (gdb_stdlog, 0, max_level, die);
20884 }
20885
20886 static void
20887 store_in_ref_table (struct die_info *die, struct dwarf2_cu *cu)
20888 {
20889   void **slot;
20890
20891   slot = htab_find_slot_with_hash (cu->die_hash, die,
20892                                    to_underlying (die->sect_off),
20893                                    INSERT);
20894
20895   *slot = die;
20896 }
20897
20898 /* Return DIE offset of ATTR.  Return 0 with complaint if ATTR is not of the
20899    required kind.  */
20900
20901 static sect_offset
20902 dwarf2_get_ref_die_offset (const struct attribute *attr)
20903 {
20904   if (attr_form_is_ref (attr))
20905     return (sect_offset) DW_UNSND (attr);
20906
20907   complaint (&symfile_complaints,
20908              _("unsupported die ref attribute form: '%s'"),
20909              dwarf_form_name (attr->form));
20910   return {};
20911 }
20912
20913 /* Return the constant value held by ATTR.  Return DEFAULT_VALUE if
20914  * the value held by the attribute is not constant.  */
20915
20916 static LONGEST
20917 dwarf2_get_attr_constant_value (const struct attribute *attr, int default_value)
20918 {
20919   if (attr->form == DW_FORM_sdata || attr->form == DW_FORM_implicit_const)
20920     return DW_SND (attr);
20921   else if (attr->form == DW_FORM_udata
20922            || attr->form == DW_FORM_data1
20923            || attr->form == DW_FORM_data2
20924            || attr->form == DW_FORM_data4
20925            || attr->form == DW_FORM_data8)
20926     return DW_UNSND (attr);
20927   else
20928     {
20929       /* For DW_FORM_data16 see attr_form_is_constant.  */
20930       complaint (&symfile_complaints,
20931                  _("Attribute value is not a constant (%s)"),
20932                  dwarf_form_name (attr->form));
20933       return default_value;
20934     }
20935 }
20936
20937 /* Follow reference or signature attribute ATTR of SRC_DIE.
20938    On entry *REF_CU is the CU of SRC_DIE.
20939    On exit *REF_CU is the CU of the result.  */
20940
20941 static struct die_info *
20942 follow_die_ref_or_sig (struct die_info *src_die, const struct attribute *attr,
20943                        struct dwarf2_cu **ref_cu)
20944 {
20945   struct die_info *die;
20946
20947   if (attr_form_is_ref (attr))
20948     die = follow_die_ref (src_die, attr, ref_cu);
20949   else if (attr->form == DW_FORM_ref_sig8)
20950     die = follow_die_sig (src_die, attr, ref_cu);
20951   else
20952     {
20953       dump_die_for_error (src_die);
20954       error (_("Dwarf Error: Expected reference attribute [in module %s]"),
20955              objfile_name ((*ref_cu)->objfile));
20956     }
20957
20958   return die;
20959 }
20960
20961 /* Follow reference OFFSET.
20962    On entry *REF_CU is the CU of the source die referencing OFFSET.
20963    On exit *REF_CU is the CU of the result.
20964    Returns NULL if OFFSET is invalid.  */
20965
20966 static struct die_info *
20967 follow_die_offset (sect_offset sect_off, int offset_in_dwz,
20968                    struct dwarf2_cu **ref_cu)
20969 {
20970   struct die_info temp_die;
20971   struct dwarf2_cu *target_cu, *cu = *ref_cu;
20972
20973   gdb_assert (cu->per_cu != NULL);
20974
20975   target_cu = cu;
20976
20977   if (cu->per_cu->is_debug_types)
20978     {
20979       /* .debug_types CUs cannot reference anything outside their CU.
20980          If they need to, they have to reference a signatured type via
20981          DW_FORM_ref_sig8.  */
20982       if (!offset_in_cu_p (&cu->header, sect_off))
20983         return NULL;
20984     }
20985   else if (offset_in_dwz != cu->per_cu->is_dwz
20986            || !offset_in_cu_p (&cu->header, sect_off))
20987     {
20988       struct dwarf2_per_cu_data *per_cu;
20989
20990       per_cu = dwarf2_find_containing_comp_unit (sect_off, offset_in_dwz,
20991                                                  cu->objfile);
20992
20993       /* If necessary, add it to the queue and load its DIEs.  */
20994       if (maybe_queue_comp_unit (cu, per_cu, cu->language))
20995         load_full_comp_unit (per_cu, cu->language);
20996
20997       target_cu = per_cu->cu;
20998     }
20999   else if (cu->dies == NULL)
21000     {
21001       /* We're loading full DIEs during partial symbol reading.  */
21002       gdb_assert (dwarf2_per_objfile->reading_partial_symbols);
21003       load_full_comp_unit (cu->per_cu, language_minimal);
21004     }
21005
21006   *ref_cu = target_cu;
21007   temp_die.sect_off = sect_off;
21008   return (struct die_info *) htab_find_with_hash (target_cu->die_hash,
21009                                                   &temp_die,
21010                                                   to_underlying (sect_off));
21011 }
21012
21013 /* Follow reference attribute ATTR of SRC_DIE.
21014    On entry *REF_CU is the CU of SRC_DIE.
21015    On exit *REF_CU is the CU of the result.  */
21016
21017 static struct die_info *
21018 follow_die_ref (struct die_info *src_die, const struct attribute *attr,
21019                 struct dwarf2_cu **ref_cu)
21020 {
21021   sect_offset sect_off = dwarf2_get_ref_die_offset (attr);
21022   struct dwarf2_cu *cu = *ref_cu;
21023   struct die_info *die;
21024
21025   die = follow_die_offset (sect_off,
21026                            (attr->form == DW_FORM_GNU_ref_alt
21027                             || cu->per_cu->is_dwz),
21028                            ref_cu);
21029   if (!die)
21030     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced from DIE "
21031            "at 0x%x [in module %s]"),
21032            to_underlying (sect_off), to_underlying (src_die->sect_off),
21033            objfile_name (cu->objfile));
21034
21035   return die;
21036 }
21037
21038 /* Return DWARF block referenced by DW_AT_location of DIE at SECT_OFF at PER_CU.
21039    Returned value is intended for DW_OP_call*.  Returned
21040    dwarf2_locexpr_baton->data has lifetime of PER_CU->OBJFILE.  */
21041
21042 struct dwarf2_locexpr_baton
21043 dwarf2_fetch_die_loc_sect_off (sect_offset sect_off,
21044                                struct dwarf2_per_cu_data *per_cu,
21045                                CORE_ADDR (*get_frame_pc) (void *baton),
21046                                void *baton)
21047 {
21048   struct dwarf2_cu *cu;
21049   struct die_info *die;
21050   struct attribute *attr;
21051   struct dwarf2_locexpr_baton retval;
21052
21053   dw2_setup (per_cu->objfile);
21054
21055   if (per_cu->cu == NULL)
21056     load_cu (per_cu);
21057   cu = per_cu->cu;
21058   if (cu == NULL)
21059     {
21060       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21061          Instead just throw an error, not much else we can do.  */
21062       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21063              to_underlying (sect_off), objfile_name (per_cu->objfile));
21064     }
21065
21066   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21067   if (!die)
21068     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21069            to_underlying (sect_off), objfile_name (per_cu->objfile));
21070
21071   attr = dwarf2_attr (die, DW_AT_location, cu);
21072   if (!attr)
21073     {
21074       /* DWARF: "If there is no such attribute, then there is no effect.".
21075          DATA is ignored if SIZE is 0.  */
21076
21077       retval.data = NULL;
21078       retval.size = 0;
21079     }
21080   else if (attr_form_is_section_offset (attr))
21081     {
21082       struct dwarf2_loclist_baton loclist_baton;
21083       CORE_ADDR pc = (*get_frame_pc) (baton);
21084       size_t size;
21085
21086       fill_in_loclist_baton (cu, &loclist_baton, attr);
21087
21088       retval.data = dwarf2_find_location_expression (&loclist_baton,
21089                                                      &size, pc);
21090       retval.size = size;
21091     }
21092   else
21093     {
21094       if (!attr_form_is_block (attr))
21095         error (_("Dwarf Error: DIE at 0x%x referenced in module %s "
21096                  "is neither DW_FORM_block* nor DW_FORM_exprloc"),
21097                to_underlying (sect_off), objfile_name (per_cu->objfile));
21098
21099       retval.data = DW_BLOCK (attr)->data;
21100       retval.size = DW_BLOCK (attr)->size;
21101     }
21102   retval.per_cu = cu->per_cu;
21103
21104   age_cached_comp_units ();
21105
21106   return retval;
21107 }
21108
21109 /* Like dwarf2_fetch_die_loc_sect_off, but take a CU
21110    offset.  */
21111
21112 struct dwarf2_locexpr_baton
21113 dwarf2_fetch_die_loc_cu_off (cu_offset offset_in_cu,
21114                              struct dwarf2_per_cu_data *per_cu,
21115                              CORE_ADDR (*get_frame_pc) (void *baton),
21116                              void *baton)
21117 {
21118   sect_offset sect_off = per_cu->sect_off + to_underlying (offset_in_cu);
21119
21120   return dwarf2_fetch_die_loc_sect_off (sect_off, per_cu, get_frame_pc, baton);
21121 }
21122
21123 /* Write a constant of a given type as target-ordered bytes into
21124    OBSTACK.  */
21125
21126 static const gdb_byte *
21127 write_constant_as_bytes (struct obstack *obstack,
21128                          enum bfd_endian byte_order,
21129                          struct type *type,
21130                          ULONGEST value,
21131                          LONGEST *len)
21132 {
21133   gdb_byte *result;
21134
21135   *len = TYPE_LENGTH (type);
21136   result = (gdb_byte *) obstack_alloc (obstack, *len);
21137   store_unsigned_integer (result, *len, byte_order, value);
21138
21139   return result;
21140 }
21141
21142 /* If the DIE at OFFSET in PER_CU has a DW_AT_const_value, return a
21143    pointer to the constant bytes and set LEN to the length of the
21144    data.  If memory is needed, allocate it on OBSTACK.  If the DIE
21145    does not have a DW_AT_const_value, return NULL.  */
21146
21147 const gdb_byte *
21148 dwarf2_fetch_constant_bytes (sect_offset sect_off,
21149                              struct dwarf2_per_cu_data *per_cu,
21150                              struct obstack *obstack,
21151                              LONGEST *len)
21152 {
21153   struct dwarf2_cu *cu;
21154   struct die_info *die;
21155   struct attribute *attr;
21156   const gdb_byte *result = NULL;
21157   struct type *type;
21158   LONGEST value;
21159   enum bfd_endian byte_order;
21160
21161   dw2_setup (per_cu->objfile);
21162
21163   if (per_cu->cu == NULL)
21164     load_cu (per_cu);
21165   cu = per_cu->cu;
21166   if (cu == NULL)
21167     {
21168       /* We shouldn't get here for a dummy CU, but don't crash on the user.
21169          Instead just throw an error, not much else we can do.  */
21170       error (_("Dwarf Error: Dummy CU at 0x%x referenced in module %s"),
21171              to_underlying (sect_off), objfile_name (per_cu->objfile));
21172     }
21173
21174   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21175   if (!die)
21176     error (_("Dwarf Error: Cannot find DIE at 0x%x referenced in module %s"),
21177            to_underlying (sect_off), objfile_name (per_cu->objfile));
21178
21179
21180   attr = dwarf2_attr (die, DW_AT_const_value, cu);
21181   if (attr == NULL)
21182     return NULL;
21183
21184   byte_order = (bfd_big_endian (per_cu->objfile->obfd)
21185                 ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
21186
21187   switch (attr->form)
21188     {
21189     case DW_FORM_addr:
21190     case DW_FORM_GNU_addr_index:
21191       {
21192         gdb_byte *tem;
21193
21194         *len = cu->header.addr_size;
21195         tem = (gdb_byte *) obstack_alloc (obstack, *len);
21196         store_unsigned_integer (tem, *len, byte_order, DW_ADDR (attr));
21197         result = tem;
21198       }
21199       break;
21200     case DW_FORM_string:
21201     case DW_FORM_strp:
21202     case DW_FORM_GNU_str_index:
21203     case DW_FORM_GNU_strp_alt:
21204       /* DW_STRING is already allocated on the objfile obstack, point
21205          directly to it.  */
21206       result = (const gdb_byte *) DW_STRING (attr);
21207       *len = strlen (DW_STRING (attr));
21208       break;
21209     case DW_FORM_block1:
21210     case DW_FORM_block2:
21211     case DW_FORM_block4:
21212     case DW_FORM_block:
21213     case DW_FORM_exprloc:
21214     case DW_FORM_data16:
21215       result = DW_BLOCK (attr)->data;
21216       *len = DW_BLOCK (attr)->size;
21217       break;
21218
21219       /* The DW_AT_const_value attributes are supposed to carry the
21220          symbol's value "represented as it would be on the target
21221          architecture."  By the time we get here, it's already been
21222          converted to host endianness, so we just need to sign- or
21223          zero-extend it as appropriate.  */
21224     case DW_FORM_data1:
21225       type = die_type (die, cu);
21226       result = dwarf2_const_value_data (attr, obstack, cu, &value, 8);
21227       if (result == NULL)
21228         result = write_constant_as_bytes (obstack, byte_order,
21229                                           type, value, len);
21230       break;
21231     case DW_FORM_data2:
21232       type = die_type (die, cu);
21233       result = dwarf2_const_value_data (attr, obstack, cu, &value, 16);
21234       if (result == NULL)
21235         result = write_constant_as_bytes (obstack, byte_order,
21236                                           type, value, len);
21237       break;
21238     case DW_FORM_data4:
21239       type = die_type (die, cu);
21240       result = dwarf2_const_value_data (attr, obstack, cu, &value, 32);
21241       if (result == NULL)
21242         result = write_constant_as_bytes (obstack, byte_order,
21243                                           type, value, len);
21244       break;
21245     case DW_FORM_data8:
21246       type = die_type (die, cu);
21247       result = dwarf2_const_value_data (attr, obstack, cu, &value, 64);
21248       if (result == NULL)
21249         result = write_constant_as_bytes (obstack, byte_order,
21250                                           type, value, len);
21251       break;
21252
21253     case DW_FORM_sdata:
21254     case DW_FORM_implicit_const:
21255       type = die_type (die, cu);
21256       result = write_constant_as_bytes (obstack, byte_order,
21257                                         type, DW_SND (attr), len);
21258       break;
21259
21260     case DW_FORM_udata:
21261       type = die_type (die, cu);
21262       result = write_constant_as_bytes (obstack, byte_order,
21263                                         type, DW_UNSND (attr), len);
21264       break;
21265
21266     default:
21267       complaint (&symfile_complaints,
21268                  _("unsupported const value attribute form: '%s'"),
21269                  dwarf_form_name (attr->form));
21270       break;
21271     }
21272
21273   return result;
21274 }
21275
21276 /* Return the type of the die at OFFSET in PER_CU.  Return NULL if no
21277    valid type for this die is found.  */
21278
21279 struct type *
21280 dwarf2_fetch_die_type_sect_off (sect_offset sect_off,
21281                                 struct dwarf2_per_cu_data *per_cu)
21282 {
21283   struct dwarf2_cu *cu;
21284   struct die_info *die;
21285
21286   dw2_setup (per_cu->objfile);
21287
21288   if (per_cu->cu == NULL)
21289     load_cu (per_cu);
21290   cu = per_cu->cu;
21291   if (!cu)
21292     return NULL;
21293
21294   die = follow_die_offset (sect_off, per_cu->is_dwz, &cu);
21295   if (!die)
21296     return NULL;
21297
21298   return die_type (die, cu);
21299 }
21300
21301 /* Return the type of the DIE at DIE_OFFSET in the CU named by
21302    PER_CU.  */
21303
21304 struct type *
21305 dwarf2_get_die_type (cu_offset die_offset,
21306                      struct dwarf2_per_cu_data *per_cu)
21307 {
21308   dw2_setup (per_cu->objfile);
21309
21310   sect_offset die_offset_sect = per_cu->sect_off + to_underlying (die_offset);
21311   return get_die_type_at_offset (die_offset_sect, per_cu);
21312 }
21313
21314 /* Follow type unit SIG_TYPE referenced by SRC_DIE.
21315    On entry *REF_CU is the CU of SRC_DIE.
21316    On exit *REF_CU is the CU of the result.
21317    Returns NULL if the referenced DIE isn't found.  */
21318
21319 static struct die_info *
21320 follow_die_sig_1 (struct die_info *src_die, struct signatured_type *sig_type,
21321                   struct dwarf2_cu **ref_cu)
21322 {
21323   struct die_info temp_die;
21324   struct dwarf2_cu *sig_cu;
21325   struct die_info *die;
21326
21327   /* While it might be nice to assert sig_type->type == NULL here,
21328      we can get here for DW_AT_imported_declaration where we need
21329      the DIE not the type.  */
21330
21331   /* If necessary, add it to the queue and load its DIEs.  */
21332
21333   if (maybe_queue_comp_unit (*ref_cu, &sig_type->per_cu, language_minimal))
21334     read_signatured_type (sig_type);
21335
21336   sig_cu = sig_type->per_cu.cu;
21337   gdb_assert (sig_cu != NULL);
21338   gdb_assert (to_underlying (sig_type->type_offset_in_section) != 0);
21339   temp_die.sect_off = sig_type->type_offset_in_section;
21340   die = (struct die_info *) htab_find_with_hash (sig_cu->die_hash, &temp_die,
21341                                                  to_underlying (temp_die.sect_off));
21342   if (die)
21343     {
21344       /* For .gdb_index version 7 keep track of included TUs.
21345          http://sourceware.org/bugzilla/show_bug.cgi?id=15021.  */
21346       if (dwarf2_per_objfile->index_table != NULL
21347           && dwarf2_per_objfile->index_table->version <= 7)
21348         {
21349           VEC_safe_push (dwarf2_per_cu_ptr,
21350                          (*ref_cu)->per_cu->imported_symtabs,
21351                          sig_cu->per_cu);
21352         }
21353
21354       *ref_cu = sig_cu;
21355       return die;
21356     }
21357
21358   return NULL;
21359 }
21360
21361 /* Follow signatured type referenced by ATTR in SRC_DIE.
21362    On entry *REF_CU is the CU of SRC_DIE.
21363    On exit *REF_CU is the CU of the result.
21364    The result is the DIE of the type.
21365    If the referenced type cannot be found an error is thrown.  */
21366
21367 static struct die_info *
21368 follow_die_sig (struct die_info *src_die, const struct attribute *attr,
21369                 struct dwarf2_cu **ref_cu)
21370 {
21371   ULONGEST signature = DW_SIGNATURE (attr);
21372   struct signatured_type *sig_type;
21373   struct die_info *die;
21374
21375   gdb_assert (attr->form == DW_FORM_ref_sig8);
21376
21377   sig_type = lookup_signatured_type (*ref_cu, signature);
21378   /* sig_type will be NULL if the signatured type is missing from
21379      the debug info.  */
21380   if (sig_type == NULL)
21381     {
21382       error (_("Dwarf Error: Cannot find signatured DIE %s referenced"
21383                " from DIE at 0x%x [in module %s]"),
21384              hex_string (signature), to_underlying (src_die->sect_off),
21385              objfile_name ((*ref_cu)->objfile));
21386     }
21387
21388   die = follow_die_sig_1 (src_die, sig_type, ref_cu);
21389   if (die == NULL)
21390     {
21391       dump_die_for_error (src_die);
21392       error (_("Dwarf Error: Problem reading signatured DIE %s referenced"
21393                " from DIE at 0x%x [in module %s]"),
21394              hex_string (signature), to_underlying (src_die->sect_off),
21395              objfile_name ((*ref_cu)->objfile));
21396     }
21397
21398   return die;
21399 }
21400
21401 /* Get the type specified by SIGNATURE referenced in DIE/CU,
21402    reading in and processing the type unit if necessary.  */
21403
21404 static struct type *
21405 get_signatured_type (struct die_info *die, ULONGEST signature,
21406                      struct dwarf2_cu *cu)
21407 {
21408   struct signatured_type *sig_type;
21409   struct dwarf2_cu *type_cu;
21410   struct die_info *type_die;
21411   struct type *type;
21412
21413   sig_type = lookup_signatured_type (cu, signature);
21414   /* sig_type will be NULL if the signatured type is missing from
21415      the debug info.  */
21416   if (sig_type == NULL)
21417     {
21418       complaint (&symfile_complaints,
21419                  _("Dwarf Error: Cannot find signatured DIE %s referenced"
21420                    " from DIE at 0x%x [in module %s]"),
21421                  hex_string (signature), to_underlying (die->sect_off),
21422                  objfile_name (dwarf2_per_objfile->objfile));
21423       return build_error_marker_type (cu, die);
21424     }
21425
21426   /* If we already know the type we're done.  */
21427   if (sig_type->type != NULL)
21428     return sig_type->type;
21429
21430   type_cu = cu;
21431   type_die = follow_die_sig_1 (die, sig_type, &type_cu);
21432   if (type_die != NULL)
21433     {
21434       /* N.B. We need to call get_die_type to ensure only one type for this DIE
21435          is created.  This is important, for example, because for c++ classes
21436          we need TYPE_NAME set which is only done by new_symbol.  Blech.  */
21437       type = read_type_die (type_die, type_cu);
21438       if (type == NULL)
21439         {
21440           complaint (&symfile_complaints,
21441                      _("Dwarf Error: Cannot build signatured type %s"
21442                        " referenced from DIE at 0x%x [in module %s]"),
21443                      hex_string (signature), to_underlying (die->sect_off),
21444                      objfile_name (dwarf2_per_objfile->objfile));
21445           type = build_error_marker_type (cu, die);
21446         }
21447     }
21448   else
21449     {
21450       complaint (&symfile_complaints,
21451                  _("Dwarf Error: Problem reading signatured DIE %s referenced"
21452                    " from DIE at 0x%x [in module %s]"),
21453                  hex_string (signature), to_underlying (die->sect_off),
21454                  objfile_name (dwarf2_per_objfile->objfile));
21455       type = build_error_marker_type (cu, die);
21456     }
21457   sig_type->type = type;
21458
21459   return type;
21460 }
21461
21462 /* Get the type specified by the DW_AT_signature ATTR in DIE/CU,
21463    reading in and processing the type unit if necessary.  */
21464
21465 static struct type *
21466 get_DW_AT_signature_type (struct die_info *die, const struct attribute *attr,
21467                           struct dwarf2_cu *cu) /* ARI: editCase function */
21468 {
21469   /* Yes, DW_AT_signature can use a non-ref_sig8 reference.  */
21470   if (attr_form_is_ref (attr))
21471     {
21472       struct dwarf2_cu *type_cu = cu;
21473       struct die_info *type_die = follow_die_ref (die, attr, &type_cu);
21474
21475       return read_type_die (type_die, type_cu);
21476     }
21477   else if (attr->form == DW_FORM_ref_sig8)
21478     {
21479       return get_signatured_type (die, DW_SIGNATURE (attr), cu);
21480     }
21481   else
21482     {
21483       complaint (&symfile_complaints,
21484                  _("Dwarf Error: DW_AT_signature has bad form %s in DIE"
21485                    " at 0x%x [in module %s]"),
21486                  dwarf_form_name (attr->form), to_underlying (die->sect_off),
21487                  objfile_name (dwarf2_per_objfile->objfile));
21488       return build_error_marker_type (cu, die);
21489     }
21490 }
21491
21492 /* Load the DIEs associated with type unit PER_CU into memory.  */
21493
21494 static void
21495 load_full_type_unit (struct dwarf2_per_cu_data *per_cu)
21496 {
21497   struct signatured_type *sig_type;
21498
21499   /* Caller is responsible for ensuring type_unit_groups don't get here.  */
21500   gdb_assert (! IS_TYPE_UNIT_GROUP (per_cu));
21501
21502   /* We have the per_cu, but we need the signatured_type.
21503      Fortunately this is an easy translation.  */
21504   gdb_assert (per_cu->is_debug_types);
21505   sig_type = (struct signatured_type *) per_cu;
21506
21507   gdb_assert (per_cu->cu == NULL);
21508
21509   read_signatured_type (sig_type);
21510
21511   gdb_assert (per_cu->cu != NULL);
21512 }
21513
21514 /* die_reader_func for read_signatured_type.
21515    This is identical to load_full_comp_unit_reader,
21516    but is kept separate for now.  */
21517
21518 static void
21519 read_signatured_type_reader (const struct die_reader_specs *reader,
21520                              const gdb_byte *info_ptr,
21521                              struct die_info *comp_unit_die,
21522                              int has_children,
21523                              void *data)
21524 {
21525   struct dwarf2_cu *cu = reader->cu;
21526
21527   gdb_assert (cu->die_hash == NULL);
21528   cu->die_hash =
21529     htab_create_alloc_ex (cu->header.length / 12,
21530                           die_hash,
21531                           die_eq,
21532                           NULL,
21533                           &cu->comp_unit_obstack,
21534                           hashtab_obstack_allocate,
21535                           dummy_obstack_deallocate);
21536
21537   if (has_children)
21538     comp_unit_die->child = read_die_and_siblings (reader, info_ptr,
21539                                                   &info_ptr, comp_unit_die);
21540   cu->dies = comp_unit_die;
21541   /* comp_unit_die is not stored in die_hash, no need.  */
21542
21543   /* We try not to read any attributes in this function, because not
21544      all CUs needed for references have been loaded yet, and symbol
21545      table processing isn't initialized.  But we have to set the CU language,
21546      or we won't be able to build types correctly.
21547      Similarly, if we do not read the producer, we can not apply
21548      producer-specific interpretation.  */
21549   prepare_one_comp_unit (cu, cu->dies, language_minimal);
21550 }
21551
21552 /* Read in a signatured type and build its CU and DIEs.
21553    If the type is a stub for the real type in a DWO file,
21554    read in the real type from the DWO file as well.  */
21555
21556 static void
21557 read_signatured_type (struct signatured_type *sig_type)
21558 {
21559   struct dwarf2_per_cu_data *per_cu = &sig_type->per_cu;
21560
21561   gdb_assert (per_cu->is_debug_types);
21562   gdb_assert (per_cu->cu == NULL);
21563
21564   init_cutu_and_read_dies (per_cu, NULL, 0, 1,
21565                            read_signatured_type_reader, NULL);
21566   sig_type->per_cu.tu_read = 1;
21567 }
21568
21569 /* Decode simple location descriptions.
21570    Given a pointer to a dwarf block that defines a location, compute
21571    the location and return the value.
21572
21573    NOTE drow/2003-11-18: This function is called in two situations
21574    now: for the address of static or global variables (partial symbols
21575    only) and for offsets into structures which are expected to be
21576    (more or less) constant.  The partial symbol case should go away,
21577    and only the constant case should remain.  That will let this
21578    function complain more accurately.  A few special modes are allowed
21579    without complaint for global variables (for instance, global
21580    register values and thread-local values).
21581
21582    A location description containing no operations indicates that the
21583    object is optimized out.  The return value is 0 for that case.
21584    FIXME drow/2003-11-16: No callers check for this case any more; soon all
21585    callers will only want a very basic result and this can become a
21586    complaint.
21587
21588    Note that stack[0] is unused except as a default error return.  */
21589
21590 static CORE_ADDR
21591 decode_locdesc (struct dwarf_block *blk, struct dwarf2_cu *cu)
21592 {
21593   struct objfile *objfile = cu->objfile;
21594   size_t i;
21595   size_t size = blk->size;
21596   const gdb_byte *data = blk->data;
21597   CORE_ADDR stack[64];
21598   int stacki;
21599   unsigned int bytes_read, unsnd;
21600   gdb_byte op;
21601
21602   i = 0;
21603   stacki = 0;
21604   stack[stacki] = 0;
21605   stack[++stacki] = 0;
21606
21607   while (i < size)
21608     {
21609       op = data[i++];
21610       switch (op)
21611         {
21612         case DW_OP_lit0:
21613         case DW_OP_lit1:
21614         case DW_OP_lit2:
21615         case DW_OP_lit3:
21616         case DW_OP_lit4:
21617         case DW_OP_lit5:
21618         case DW_OP_lit6:
21619         case DW_OP_lit7:
21620         case DW_OP_lit8:
21621         case DW_OP_lit9:
21622         case DW_OP_lit10:
21623         case DW_OP_lit11:
21624         case DW_OP_lit12:
21625         case DW_OP_lit13:
21626         case DW_OP_lit14:
21627         case DW_OP_lit15:
21628         case DW_OP_lit16:
21629         case DW_OP_lit17:
21630         case DW_OP_lit18:
21631         case DW_OP_lit19:
21632         case DW_OP_lit20:
21633         case DW_OP_lit21:
21634         case DW_OP_lit22:
21635         case DW_OP_lit23:
21636         case DW_OP_lit24:
21637         case DW_OP_lit25:
21638         case DW_OP_lit26:
21639         case DW_OP_lit27:
21640         case DW_OP_lit28:
21641         case DW_OP_lit29:
21642         case DW_OP_lit30:
21643         case DW_OP_lit31:
21644           stack[++stacki] = op - DW_OP_lit0;
21645           break;
21646
21647         case DW_OP_reg0:
21648         case DW_OP_reg1:
21649         case DW_OP_reg2:
21650         case DW_OP_reg3:
21651         case DW_OP_reg4:
21652         case DW_OP_reg5:
21653         case DW_OP_reg6:
21654         case DW_OP_reg7:
21655         case DW_OP_reg8:
21656         case DW_OP_reg9:
21657         case DW_OP_reg10:
21658         case DW_OP_reg11:
21659         case DW_OP_reg12:
21660         case DW_OP_reg13:
21661         case DW_OP_reg14:
21662         case DW_OP_reg15:
21663         case DW_OP_reg16:
21664         case DW_OP_reg17:
21665         case DW_OP_reg18:
21666         case DW_OP_reg19:
21667         case DW_OP_reg20:
21668         case DW_OP_reg21:
21669         case DW_OP_reg22:
21670         case DW_OP_reg23:
21671         case DW_OP_reg24:
21672         case DW_OP_reg25:
21673         case DW_OP_reg26:
21674         case DW_OP_reg27:
21675         case DW_OP_reg28:
21676         case DW_OP_reg29:
21677         case DW_OP_reg30:
21678         case DW_OP_reg31:
21679           stack[++stacki] = op - DW_OP_reg0;
21680           if (i < size)
21681             dwarf2_complex_location_expr_complaint ();
21682           break;
21683
21684         case DW_OP_regx:
21685           unsnd = read_unsigned_leb128 (NULL, (data + i), &bytes_read);
21686           i += bytes_read;
21687           stack[++stacki] = unsnd;
21688           if (i < size)
21689             dwarf2_complex_location_expr_complaint ();
21690           break;
21691
21692         case DW_OP_addr:
21693           stack[++stacki] = read_address (objfile->obfd, &data[i],
21694                                           cu, &bytes_read);
21695           i += bytes_read;
21696           break;
21697
21698         case DW_OP_const1u:
21699           stack[++stacki] = read_1_byte (objfile->obfd, &data[i]);
21700           i += 1;
21701           break;
21702
21703         case DW_OP_const1s:
21704           stack[++stacki] = read_1_signed_byte (objfile->obfd, &data[i]);
21705           i += 1;
21706           break;
21707
21708         case DW_OP_const2u:
21709           stack[++stacki] = read_2_bytes (objfile->obfd, &data[i]);
21710           i += 2;
21711           break;
21712
21713         case DW_OP_const2s:
21714           stack[++stacki] = read_2_signed_bytes (objfile->obfd, &data[i]);
21715           i += 2;
21716           break;
21717
21718         case DW_OP_const4u:
21719           stack[++stacki] = read_4_bytes (objfile->obfd, &data[i]);
21720           i += 4;
21721           break;
21722
21723         case DW_OP_const4s:
21724           stack[++stacki] = read_4_signed_bytes (objfile->obfd, &data[i]);
21725           i += 4;
21726           break;
21727
21728         case DW_OP_const8u:
21729           stack[++stacki] = read_8_bytes (objfile->obfd, &data[i]);
21730           i += 8;
21731           break;
21732
21733         case DW_OP_constu:
21734           stack[++stacki] = read_unsigned_leb128 (NULL, (data + i),
21735                                                   &bytes_read);
21736           i += bytes_read;
21737           break;
21738
21739         case DW_OP_consts:
21740           stack[++stacki] = read_signed_leb128 (NULL, (data + i), &bytes_read);
21741           i += bytes_read;
21742           break;
21743
21744         case DW_OP_dup:
21745           stack[stacki + 1] = stack[stacki];
21746           stacki++;
21747           break;
21748
21749         case DW_OP_plus:
21750           stack[stacki - 1] += stack[stacki];
21751           stacki--;
21752           break;
21753
21754         case DW_OP_plus_uconst:
21755           stack[stacki] += read_unsigned_leb128 (NULL, (data + i),
21756                                                  &bytes_read);
21757           i += bytes_read;
21758           break;
21759
21760         case DW_OP_minus:
21761           stack[stacki - 1] -= stack[stacki];
21762           stacki--;
21763           break;
21764
21765         case DW_OP_deref:
21766           /* If we're not the last op, then we definitely can't encode
21767              this using GDB's address_class enum.  This is valid for partial
21768              global symbols, although the variable's address will be bogus
21769              in the psymtab.  */
21770           if (i < size)
21771             dwarf2_complex_location_expr_complaint ();
21772           break;
21773
21774         case DW_OP_GNU_push_tls_address:
21775         case DW_OP_form_tls_address:
21776           /* The top of the stack has the offset from the beginning
21777              of the thread control block at which the variable is located.  */
21778           /* Nothing should follow this operator, so the top of stack would
21779              be returned.  */
21780           /* This is valid for partial global symbols, but the variable's
21781              address will be bogus in the psymtab.  Make it always at least
21782              non-zero to not look as a variable garbage collected by linker
21783              which have DW_OP_addr 0.  */
21784           if (i < size)
21785             dwarf2_complex_location_expr_complaint ();
21786           stack[stacki]++;
21787           break;
21788
21789         case DW_OP_GNU_uninit:
21790           break;
21791
21792         case DW_OP_GNU_addr_index:
21793         case DW_OP_GNU_const_index:
21794           stack[++stacki] = read_addr_index_from_leb128 (cu, &data[i],
21795                                                          &bytes_read);
21796           i += bytes_read;
21797           break;
21798
21799         default:
21800           {
21801             const char *name = get_DW_OP_name (op);
21802
21803             if (name)
21804               complaint (&symfile_complaints, _("unsupported stack op: '%s'"),
21805                          name);
21806             else
21807               complaint (&symfile_complaints, _("unsupported stack op: '%02x'"),
21808                          op);
21809           }
21810
21811           return (stack[stacki]);
21812         }
21813
21814       /* Enforce maximum stack depth of SIZE-1 to avoid writing
21815          outside of the allocated space.  Also enforce minimum>0.  */
21816       if (stacki >= ARRAY_SIZE (stack) - 1)
21817         {
21818           complaint (&symfile_complaints,
21819                      _("location description stack overflow"));
21820           return 0;
21821         }
21822
21823       if (stacki <= 0)
21824         {
21825           complaint (&symfile_complaints,
21826                      _("location description stack underflow"));
21827           return 0;
21828         }
21829     }
21830   return (stack[stacki]);
21831 }
21832
21833 /* memory allocation interface */
21834
21835 static struct dwarf_block *
21836 dwarf_alloc_block (struct dwarf2_cu *cu)
21837 {
21838   return XOBNEW (&cu->comp_unit_obstack, struct dwarf_block);
21839 }
21840
21841 static struct die_info *
21842 dwarf_alloc_die (struct dwarf2_cu *cu, int num_attrs)
21843 {
21844   struct die_info *die;
21845   size_t size = sizeof (struct die_info);
21846
21847   if (num_attrs > 1)
21848     size += (num_attrs - 1) * sizeof (struct attribute);
21849
21850   die = (struct die_info *) obstack_alloc (&cu->comp_unit_obstack, size);
21851   memset (die, 0, sizeof (struct die_info));
21852   return (die);
21853 }
21854
21855 \f
21856 /* Macro support.  */
21857
21858 /* Return file name relative to the compilation directory of file number I in
21859    *LH's file name table.  The result is allocated using xmalloc; the caller is
21860    responsible for freeing it.  */
21861
21862 static char *
21863 file_file_name (int file, struct line_header *lh)
21864 {
21865   /* Is the file number a valid index into the line header's file name
21866      table?  Remember that file numbers start with one, not zero.  */
21867   if (1 <= file && file <= lh->file_names.size ())
21868     {
21869       const file_entry &fe = lh->file_names[file - 1];
21870
21871       if (!IS_ABSOLUTE_PATH (fe.name))
21872         {
21873           const char *dir = fe.include_dir (lh);
21874           if (dir != NULL)
21875             return concat (dir, SLASH_STRING, fe.name, (char *) NULL);
21876         }
21877       return xstrdup (fe.name);
21878     }
21879   else
21880     {
21881       /* The compiler produced a bogus file number.  We can at least
21882          record the macro definitions made in the file, even if we
21883          won't be able to find the file by name.  */
21884       char fake_name[80];
21885
21886       xsnprintf (fake_name, sizeof (fake_name),
21887                  "<bad macro file number %d>", file);
21888
21889       complaint (&symfile_complaints,
21890                  _("bad file number in macro information (%d)"),
21891                  file);
21892
21893       return xstrdup (fake_name);
21894     }
21895 }
21896
21897 /* Return the full name of file number I in *LH's file name table.
21898    Use COMP_DIR as the name of the current directory of the
21899    compilation.  The result is allocated using xmalloc; the caller is
21900    responsible for freeing it.  */
21901 static char *
21902 file_full_name (int file, struct line_header *lh, const char *comp_dir)
21903 {
21904   /* Is the file number a valid index into the line header's file name
21905      table?  Remember that file numbers start with one, not zero.  */
21906   if (1 <= file && file <= lh->file_names.size ())
21907     {
21908       char *relative = file_file_name (file, lh);
21909
21910       if (IS_ABSOLUTE_PATH (relative) || comp_dir == NULL)
21911         return relative;
21912       return reconcat (relative, comp_dir, SLASH_STRING,
21913                        relative, (char *) NULL);
21914     }
21915   else
21916     return file_file_name (file, lh);
21917 }
21918
21919
21920 static struct macro_source_file *
21921 macro_start_file (int file, int line,
21922                   struct macro_source_file *current_file,
21923                   struct line_header *lh)
21924 {
21925   /* File name relative to the compilation directory of this source file.  */
21926   char *file_name = file_file_name (file, lh);
21927
21928   if (! current_file)
21929     {
21930       /* Note: We don't create a macro table for this compilation unit
21931          at all until we actually get a filename.  */
21932       struct macro_table *macro_table = get_macro_table ();
21933
21934       /* If we have no current file, then this must be the start_file
21935          directive for the compilation unit's main source file.  */
21936       current_file = macro_set_main (macro_table, file_name);
21937       macro_define_special (macro_table);
21938     }
21939   else
21940     current_file = macro_include (current_file, line, file_name);
21941
21942   xfree (file_name);
21943
21944   return current_file;
21945 }
21946
21947 static const char *
21948 consume_improper_spaces (const char *p, const char *body)
21949 {
21950   if (*p == ' ')
21951     {
21952       complaint (&symfile_complaints,
21953                  _("macro definition contains spaces "
21954                    "in formal argument list:\n`%s'"),
21955                  body);
21956
21957       while (*p == ' ')
21958         p++;
21959     }
21960
21961   return p;
21962 }
21963
21964
21965 static void
21966 parse_macro_definition (struct macro_source_file *file, int line,
21967                         const char *body)
21968 {
21969   const char *p;
21970
21971   /* The body string takes one of two forms.  For object-like macro
21972      definitions, it should be:
21973
21974         <macro name> " " <definition>
21975
21976      For function-like macro definitions, it should be:
21977
21978         <macro name> "() " <definition>
21979      or
21980         <macro name> "(" <arg name> ( "," <arg name> ) * ") " <definition>
21981
21982      Spaces may appear only where explicitly indicated, and in the
21983      <definition>.
21984
21985      The Dwarf 2 spec says that an object-like macro's name is always
21986      followed by a space, but versions of GCC around March 2002 omit
21987      the space when the macro's definition is the empty string.
21988
21989      The Dwarf 2 spec says that there should be no spaces between the
21990      formal arguments in a function-like macro's formal argument list,
21991      but versions of GCC around March 2002 include spaces after the
21992      commas.  */
21993
21994
21995   /* Find the extent of the macro name.  The macro name is terminated
21996      by either a space or null character (for an object-like macro) or
21997      an opening paren (for a function-like macro).  */
21998   for (p = body; *p; p++)
21999     if (*p == ' ' || *p == '(')
22000       break;
22001
22002   if (*p == ' ' || *p == '\0')
22003     {
22004       /* It's an object-like macro.  */
22005       int name_len = p - body;
22006       char *name = savestring (body, name_len);
22007       const char *replacement;
22008
22009       if (*p == ' ')
22010         replacement = body + name_len + 1;
22011       else
22012         {
22013           dwarf2_macro_malformed_definition_complaint (body);
22014           replacement = body + name_len;
22015         }
22016
22017       macro_define_object (file, line, name, replacement);
22018
22019       xfree (name);
22020     }
22021   else if (*p == '(')
22022     {
22023       /* It's a function-like macro.  */
22024       char *name = savestring (body, p - body);
22025       int argc = 0;
22026       int argv_size = 1;
22027       char **argv = XNEWVEC (char *, argv_size);
22028
22029       p++;
22030
22031       p = consume_improper_spaces (p, body);
22032
22033       /* Parse the formal argument list.  */
22034       while (*p && *p != ')')
22035         {
22036           /* Find the extent of the current argument name.  */
22037           const char *arg_start = p;
22038
22039           while (*p && *p != ',' && *p != ')' && *p != ' ')
22040             p++;
22041
22042           if (! *p || p == arg_start)
22043             dwarf2_macro_malformed_definition_complaint (body);
22044           else
22045             {
22046               /* Make sure argv has room for the new argument.  */
22047               if (argc >= argv_size)
22048                 {
22049                   argv_size *= 2;
22050                   argv = XRESIZEVEC (char *, argv, argv_size);
22051                 }
22052
22053               argv[argc++] = savestring (arg_start, p - arg_start);
22054             }
22055
22056           p = consume_improper_spaces (p, body);
22057
22058           /* Consume the comma, if present.  */
22059           if (*p == ',')
22060             {
22061               p++;
22062
22063               p = consume_improper_spaces (p, body);
22064             }
22065         }
22066
22067       if (*p == ')')
22068         {
22069           p++;
22070
22071           if (*p == ' ')
22072             /* Perfectly formed definition, no complaints.  */
22073             macro_define_function (file, line, name,
22074                                    argc, (const char **) argv,
22075                                    p + 1);
22076           else if (*p == '\0')
22077             {
22078               /* Complain, but do define it.  */
22079               dwarf2_macro_malformed_definition_complaint (body);
22080               macro_define_function (file, line, name,
22081                                      argc, (const char **) argv,
22082                                      p);
22083             }
22084           else
22085             /* Just complain.  */
22086             dwarf2_macro_malformed_definition_complaint (body);
22087         }
22088       else
22089         /* Just complain.  */
22090         dwarf2_macro_malformed_definition_complaint (body);
22091
22092       xfree (name);
22093       {
22094         int i;
22095
22096         for (i = 0; i < argc; i++)
22097           xfree (argv[i]);
22098       }
22099       xfree (argv);
22100     }
22101   else
22102     dwarf2_macro_malformed_definition_complaint (body);
22103 }
22104
22105 /* Skip some bytes from BYTES according to the form given in FORM.
22106    Returns the new pointer.  */
22107
22108 static const gdb_byte *
22109 skip_form_bytes (bfd *abfd, const gdb_byte *bytes, const gdb_byte *buffer_end,
22110                  enum dwarf_form form,
22111                  unsigned int offset_size,
22112                  struct dwarf2_section_info *section)
22113 {
22114   unsigned int bytes_read;
22115
22116   switch (form)
22117     {
22118     case DW_FORM_data1:
22119     case DW_FORM_flag:
22120       ++bytes;
22121       break;
22122
22123     case DW_FORM_data2:
22124       bytes += 2;
22125       break;
22126
22127     case DW_FORM_data4:
22128       bytes += 4;
22129       break;
22130
22131     case DW_FORM_data8:
22132       bytes += 8;
22133       break;
22134
22135     case DW_FORM_data16:
22136       bytes += 16;
22137       break;
22138
22139     case DW_FORM_string:
22140       read_direct_string (abfd, bytes, &bytes_read);
22141       bytes += bytes_read;
22142       break;
22143
22144     case DW_FORM_sec_offset:
22145     case DW_FORM_strp:
22146     case DW_FORM_GNU_strp_alt:
22147       bytes += offset_size;
22148       break;
22149
22150     case DW_FORM_block:
22151       bytes += read_unsigned_leb128 (abfd, bytes, &bytes_read);
22152       bytes += bytes_read;
22153       break;
22154
22155     case DW_FORM_block1:
22156       bytes += 1 + read_1_byte (abfd, bytes);
22157       break;
22158     case DW_FORM_block2:
22159       bytes += 2 + read_2_bytes (abfd, bytes);
22160       break;
22161     case DW_FORM_block4:
22162       bytes += 4 + read_4_bytes (abfd, bytes);
22163       break;
22164
22165     case DW_FORM_sdata:
22166     case DW_FORM_udata:
22167     case DW_FORM_GNU_addr_index:
22168     case DW_FORM_GNU_str_index:
22169       bytes = gdb_skip_leb128 (bytes, buffer_end);
22170       if (bytes == NULL)
22171         {
22172           dwarf2_section_buffer_overflow_complaint (section);
22173           return NULL;
22174         }
22175       break;
22176
22177     case DW_FORM_implicit_const:
22178       break;
22179
22180     default:
22181       {
22182       complain:
22183         complaint (&symfile_complaints,
22184                    _("invalid form 0x%x in `%s'"),
22185                    form, get_section_name (section));
22186         return NULL;
22187       }
22188     }
22189
22190   return bytes;
22191 }
22192
22193 /* A helper for dwarf_decode_macros that handles skipping an unknown
22194    opcode.  Returns an updated pointer to the macro data buffer; or,
22195    on error, issues a complaint and returns NULL.  */
22196
22197 static const gdb_byte *
22198 skip_unknown_opcode (unsigned int opcode,
22199                      const gdb_byte **opcode_definitions,
22200                      const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22201                      bfd *abfd,
22202                      unsigned int offset_size,
22203                      struct dwarf2_section_info *section)
22204 {
22205   unsigned int bytes_read, i;
22206   unsigned long arg;
22207   const gdb_byte *defn;
22208
22209   if (opcode_definitions[opcode] == NULL)
22210     {
22211       complaint (&symfile_complaints,
22212                  _("unrecognized DW_MACFINO opcode 0x%x"),
22213                  opcode);
22214       return NULL;
22215     }
22216
22217   defn = opcode_definitions[opcode];
22218   arg = read_unsigned_leb128 (abfd, defn, &bytes_read);
22219   defn += bytes_read;
22220
22221   for (i = 0; i < arg; ++i)
22222     {
22223       mac_ptr = skip_form_bytes (abfd, mac_ptr, mac_end,
22224                                  (enum dwarf_form) defn[i], offset_size,
22225                                  section);
22226       if (mac_ptr == NULL)
22227         {
22228           /* skip_form_bytes already issued the complaint.  */
22229           return NULL;
22230         }
22231     }
22232
22233   return mac_ptr;
22234 }
22235
22236 /* A helper function which parses the header of a macro section.
22237    If the macro section is the extended (for now called "GNU") type,
22238    then this updates *OFFSET_SIZE.  Returns a pointer to just after
22239    the header, or issues a complaint and returns NULL on error.  */
22240
22241 static const gdb_byte *
22242 dwarf_parse_macro_header (const gdb_byte **opcode_definitions,
22243                           bfd *abfd,
22244                           const gdb_byte *mac_ptr,
22245                           unsigned int *offset_size,
22246                           int section_is_gnu)
22247 {
22248   memset (opcode_definitions, 0, 256 * sizeof (gdb_byte *));
22249
22250   if (section_is_gnu)
22251     {
22252       unsigned int version, flags;
22253
22254       version = read_2_bytes (abfd, mac_ptr);
22255       if (version != 4 && version != 5)
22256         {
22257           complaint (&symfile_complaints,
22258                      _("unrecognized version `%d' in .debug_macro section"),
22259                      version);
22260           return NULL;
22261         }
22262       mac_ptr += 2;
22263
22264       flags = read_1_byte (abfd, mac_ptr);
22265       ++mac_ptr;
22266       *offset_size = (flags & 1) ? 8 : 4;
22267
22268       if ((flags & 2) != 0)
22269         /* We don't need the line table offset.  */
22270         mac_ptr += *offset_size;
22271
22272       /* Vendor opcode descriptions.  */
22273       if ((flags & 4) != 0)
22274         {
22275           unsigned int i, count;
22276
22277           count = read_1_byte (abfd, mac_ptr);
22278           ++mac_ptr;
22279           for (i = 0; i < count; ++i)
22280             {
22281               unsigned int opcode, bytes_read;
22282               unsigned long arg;
22283
22284               opcode = read_1_byte (abfd, mac_ptr);
22285               ++mac_ptr;
22286               opcode_definitions[opcode] = mac_ptr;
22287               arg = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22288               mac_ptr += bytes_read;
22289               mac_ptr += arg;
22290             }
22291         }
22292     }
22293
22294   return mac_ptr;
22295 }
22296
22297 /* A helper for dwarf_decode_macros that handles the GNU extensions,
22298    including DW_MACRO_import.  */
22299
22300 static void
22301 dwarf_decode_macro_bytes (bfd *abfd,
22302                           const gdb_byte *mac_ptr, const gdb_byte *mac_end,
22303                           struct macro_source_file *current_file,
22304                           struct line_header *lh,
22305                           struct dwarf2_section_info *section,
22306                           int section_is_gnu, int section_is_dwz,
22307                           unsigned int offset_size,
22308                           htab_t include_hash)
22309 {
22310   struct objfile *objfile = dwarf2_per_objfile->objfile;
22311   enum dwarf_macro_record_type macinfo_type;
22312   int at_commandline;
22313   const gdb_byte *opcode_definitions[256];
22314
22315   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22316                                       &offset_size, section_is_gnu);
22317   if (mac_ptr == NULL)
22318     {
22319       /* We already issued a complaint.  */
22320       return;
22321     }
22322
22323   /* Determines if GDB is still before first DW_MACINFO_start_file.  If true
22324      GDB is still reading the definitions from command line.  First
22325      DW_MACINFO_start_file will need to be ignored as it was already executed
22326      to create CURRENT_FILE for the main source holding also the command line
22327      definitions.  On first met DW_MACINFO_start_file this flag is reset to
22328      normally execute all the remaining DW_MACINFO_start_file macinfos.  */
22329
22330   at_commandline = 1;
22331
22332   do
22333     {
22334       /* Do we at least have room for a macinfo type byte?  */
22335       if (mac_ptr >= mac_end)
22336         {
22337           dwarf2_section_buffer_overflow_complaint (section);
22338           break;
22339         }
22340
22341       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22342       mac_ptr++;
22343
22344       /* Note that we rely on the fact that the corresponding GNU and
22345          DWARF constants are the same.  */
22346       switch (macinfo_type)
22347         {
22348           /* A zero macinfo type indicates the end of the macro
22349              information.  */
22350         case 0:
22351           break;
22352
22353         case DW_MACRO_define:
22354         case DW_MACRO_undef:
22355         case DW_MACRO_define_strp:
22356         case DW_MACRO_undef_strp:
22357         case DW_MACRO_define_sup:
22358         case DW_MACRO_undef_sup:
22359           {
22360             unsigned int bytes_read;
22361             int line;
22362             const char *body;
22363             int is_define;
22364
22365             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22366             mac_ptr += bytes_read;
22367
22368             if (macinfo_type == DW_MACRO_define
22369                 || macinfo_type == DW_MACRO_undef)
22370               {
22371                 body = read_direct_string (abfd, mac_ptr, &bytes_read);
22372                 mac_ptr += bytes_read;
22373               }
22374             else
22375               {
22376                 LONGEST str_offset;
22377
22378                 str_offset = read_offset_1 (abfd, mac_ptr, offset_size);
22379                 mac_ptr += offset_size;
22380
22381                 if (macinfo_type == DW_MACRO_define_sup
22382                     || macinfo_type == DW_MACRO_undef_sup
22383                     || section_is_dwz)
22384                   {
22385                     struct dwz_file *dwz = dwarf2_get_dwz_file ();
22386
22387                     body = read_indirect_string_from_dwz (dwz, str_offset);
22388                   }
22389                 else
22390                   body = read_indirect_string_at_offset (abfd, str_offset);
22391               }
22392
22393             is_define = (macinfo_type == DW_MACRO_define
22394                          || macinfo_type == DW_MACRO_define_strp
22395                          || macinfo_type == DW_MACRO_define_sup);
22396             if (! current_file)
22397               {
22398                 /* DWARF violation as no main source is present.  */
22399                 complaint (&symfile_complaints,
22400                            _("debug info with no main source gives macro %s "
22401                              "on line %d: %s"),
22402                            is_define ? _("definition") : _("undefinition"),
22403                            line, body);
22404                 break;
22405               }
22406             if ((line == 0 && !at_commandline)
22407                 || (line != 0 && at_commandline))
22408               complaint (&symfile_complaints,
22409                          _("debug info gives %s macro %s with %s line %d: %s"),
22410                          at_commandline ? _("command-line") : _("in-file"),
22411                          is_define ? _("definition") : _("undefinition"),
22412                          line == 0 ? _("zero") : _("non-zero"), line, body);
22413
22414             if (is_define)
22415               parse_macro_definition (current_file, line, body);
22416             else
22417               {
22418                 gdb_assert (macinfo_type == DW_MACRO_undef
22419                             || macinfo_type == DW_MACRO_undef_strp
22420                             || macinfo_type == DW_MACRO_undef_sup);
22421                 macro_undef (current_file, line, body);
22422               }
22423           }
22424           break;
22425
22426         case DW_MACRO_start_file:
22427           {
22428             unsigned int bytes_read;
22429             int line, file;
22430
22431             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22432             mac_ptr += bytes_read;
22433             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22434             mac_ptr += bytes_read;
22435
22436             if ((line == 0 && !at_commandline)
22437                 || (line != 0 && at_commandline))
22438               complaint (&symfile_complaints,
22439                          _("debug info gives source %d included "
22440                            "from %s at %s line %d"),
22441                          file, at_commandline ? _("command-line") : _("file"),
22442                          line == 0 ? _("zero") : _("non-zero"), line);
22443
22444             if (at_commandline)
22445               {
22446                 /* This DW_MACRO_start_file was executed in the
22447                    pass one.  */
22448                 at_commandline = 0;
22449               }
22450             else
22451               current_file = macro_start_file (file, line, current_file, lh);
22452           }
22453           break;
22454
22455         case DW_MACRO_end_file:
22456           if (! current_file)
22457             complaint (&symfile_complaints,
22458                        _("macro debug info has an unmatched "
22459                          "`close_file' directive"));
22460           else
22461             {
22462               current_file = current_file->included_by;
22463               if (! current_file)
22464                 {
22465                   enum dwarf_macro_record_type next_type;
22466
22467                   /* GCC circa March 2002 doesn't produce the zero
22468                      type byte marking the end of the compilation
22469                      unit.  Complain if it's not there, but exit no
22470                      matter what.  */
22471
22472                   /* Do we at least have room for a macinfo type byte?  */
22473                   if (mac_ptr >= mac_end)
22474                     {
22475                       dwarf2_section_buffer_overflow_complaint (section);
22476                       return;
22477                     }
22478
22479                   /* We don't increment mac_ptr here, so this is just
22480                      a look-ahead.  */
22481                   next_type
22482                     = (enum dwarf_macro_record_type) read_1_byte (abfd,
22483                                                                   mac_ptr);
22484                   if (next_type != 0)
22485                     complaint (&symfile_complaints,
22486                                _("no terminating 0-type entry for "
22487                                  "macros in `.debug_macinfo' section"));
22488
22489                   return;
22490                 }
22491             }
22492           break;
22493
22494         case DW_MACRO_import:
22495         case DW_MACRO_import_sup:
22496           {
22497             LONGEST offset;
22498             void **slot;
22499             bfd *include_bfd = abfd;
22500             struct dwarf2_section_info *include_section = section;
22501             const gdb_byte *include_mac_end = mac_end;
22502             int is_dwz = section_is_dwz;
22503             const gdb_byte *new_mac_ptr;
22504
22505             offset = read_offset_1 (abfd, mac_ptr, offset_size);
22506             mac_ptr += offset_size;
22507
22508             if (macinfo_type == DW_MACRO_import_sup)
22509               {
22510                 struct dwz_file *dwz = dwarf2_get_dwz_file ();
22511
22512                 dwarf2_read_section (objfile, &dwz->macro);
22513
22514                 include_section = &dwz->macro;
22515                 include_bfd = get_section_bfd_owner (include_section);
22516                 include_mac_end = dwz->macro.buffer + dwz->macro.size;
22517                 is_dwz = 1;
22518               }
22519
22520             new_mac_ptr = include_section->buffer + offset;
22521             slot = htab_find_slot (include_hash, new_mac_ptr, INSERT);
22522
22523             if (*slot != NULL)
22524               {
22525                 /* This has actually happened; see
22526                    http://sourceware.org/bugzilla/show_bug.cgi?id=13568.  */
22527                 complaint (&symfile_complaints,
22528                            _("recursive DW_MACRO_import in "
22529                              ".debug_macro section"));
22530               }
22531             else
22532               {
22533                 *slot = (void *) new_mac_ptr;
22534
22535                 dwarf_decode_macro_bytes (include_bfd, new_mac_ptr,
22536                                           include_mac_end, current_file, lh,
22537                                           section, section_is_gnu, is_dwz,
22538                                           offset_size, include_hash);
22539
22540                 htab_remove_elt (include_hash, (void *) new_mac_ptr);
22541               }
22542           }
22543           break;
22544
22545         case DW_MACINFO_vendor_ext:
22546           if (!section_is_gnu)
22547             {
22548               unsigned int bytes_read;
22549
22550               /* This reads the constant, but since we don't recognize
22551                  any vendor extensions, we ignore it.  */
22552               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22553               mac_ptr += bytes_read;
22554               read_direct_string (abfd, mac_ptr, &bytes_read);
22555               mac_ptr += bytes_read;
22556
22557               /* We don't recognize any vendor extensions.  */
22558               break;
22559             }
22560           /* FALLTHROUGH */
22561
22562         default:
22563           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22564                                          mac_ptr, mac_end, abfd, offset_size,
22565                                          section);
22566           if (mac_ptr == NULL)
22567             return;
22568           break;
22569         }
22570     } while (macinfo_type != 0);
22571 }
22572
22573 static void
22574 dwarf_decode_macros (struct dwarf2_cu *cu, unsigned int offset,
22575                      int section_is_gnu)
22576 {
22577   struct objfile *objfile = dwarf2_per_objfile->objfile;
22578   struct line_header *lh = cu->line_header;
22579   bfd *abfd;
22580   const gdb_byte *mac_ptr, *mac_end;
22581   struct macro_source_file *current_file = 0;
22582   enum dwarf_macro_record_type macinfo_type;
22583   unsigned int offset_size = cu->header.offset_size;
22584   const gdb_byte *opcode_definitions[256];
22585   void **slot;
22586   struct dwarf2_section_info *section;
22587   const char *section_name;
22588
22589   if (cu->dwo_unit != NULL)
22590     {
22591       if (section_is_gnu)
22592         {
22593           section = &cu->dwo_unit->dwo_file->sections.macro;
22594           section_name = ".debug_macro.dwo";
22595         }
22596       else
22597         {
22598           section = &cu->dwo_unit->dwo_file->sections.macinfo;
22599           section_name = ".debug_macinfo.dwo";
22600         }
22601     }
22602   else
22603     {
22604       if (section_is_gnu)
22605         {
22606           section = &dwarf2_per_objfile->macro;
22607           section_name = ".debug_macro";
22608         }
22609       else
22610         {
22611           section = &dwarf2_per_objfile->macinfo;
22612           section_name = ".debug_macinfo";
22613         }
22614     }
22615
22616   dwarf2_read_section (objfile, section);
22617   if (section->buffer == NULL)
22618     {
22619       complaint (&symfile_complaints, _("missing %s section"), section_name);
22620       return;
22621     }
22622   abfd = get_section_bfd_owner (section);
22623
22624   /* First pass: Find the name of the base filename.
22625      This filename is needed in order to process all macros whose definition
22626      (or undefinition) comes from the command line.  These macros are defined
22627      before the first DW_MACINFO_start_file entry, and yet still need to be
22628      associated to the base file.
22629
22630      To determine the base file name, we scan the macro definitions until we
22631      reach the first DW_MACINFO_start_file entry.  We then initialize
22632      CURRENT_FILE accordingly so that any macro definition found before the
22633      first DW_MACINFO_start_file can still be associated to the base file.  */
22634
22635   mac_ptr = section->buffer + offset;
22636   mac_end = section->buffer + section->size;
22637
22638   mac_ptr = dwarf_parse_macro_header (opcode_definitions, abfd, mac_ptr,
22639                                       &offset_size, section_is_gnu);
22640   if (mac_ptr == NULL)
22641     {
22642       /* We already issued a complaint.  */
22643       return;
22644     }
22645
22646   do
22647     {
22648       /* Do we at least have room for a macinfo type byte?  */
22649       if (mac_ptr >= mac_end)
22650         {
22651           /* Complaint is printed during the second pass as GDB will probably
22652              stop the first pass earlier upon finding
22653              DW_MACINFO_start_file.  */
22654           break;
22655         }
22656
22657       macinfo_type = (enum dwarf_macro_record_type) read_1_byte (abfd, mac_ptr);
22658       mac_ptr++;
22659
22660       /* Note that we rely on the fact that the corresponding GNU and
22661          DWARF constants are the same.  */
22662       switch (macinfo_type)
22663         {
22664           /* A zero macinfo type indicates the end of the macro
22665              information.  */
22666         case 0:
22667           break;
22668
22669         case DW_MACRO_define:
22670         case DW_MACRO_undef:
22671           /* Only skip the data by MAC_PTR.  */
22672           {
22673             unsigned int bytes_read;
22674
22675             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22676             mac_ptr += bytes_read;
22677             read_direct_string (abfd, mac_ptr, &bytes_read);
22678             mac_ptr += bytes_read;
22679           }
22680           break;
22681
22682         case DW_MACRO_start_file:
22683           {
22684             unsigned int bytes_read;
22685             int line, file;
22686
22687             line = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22688             mac_ptr += bytes_read;
22689             file = read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22690             mac_ptr += bytes_read;
22691
22692             current_file = macro_start_file (file, line, current_file, lh);
22693           }
22694           break;
22695
22696         case DW_MACRO_end_file:
22697           /* No data to skip by MAC_PTR.  */
22698           break;
22699
22700         case DW_MACRO_define_strp:
22701         case DW_MACRO_undef_strp:
22702         case DW_MACRO_define_sup:
22703         case DW_MACRO_undef_sup:
22704           {
22705             unsigned int bytes_read;
22706
22707             read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22708             mac_ptr += bytes_read;
22709             mac_ptr += offset_size;
22710           }
22711           break;
22712
22713         case DW_MACRO_import:
22714         case DW_MACRO_import_sup:
22715           /* Note that, according to the spec, a transparent include
22716              chain cannot call DW_MACRO_start_file.  So, we can just
22717              skip this opcode.  */
22718           mac_ptr += offset_size;
22719           break;
22720
22721         case DW_MACINFO_vendor_ext:
22722           /* Only skip the data by MAC_PTR.  */
22723           if (!section_is_gnu)
22724             {
22725               unsigned int bytes_read;
22726
22727               read_unsigned_leb128 (abfd, mac_ptr, &bytes_read);
22728               mac_ptr += bytes_read;
22729               read_direct_string (abfd, mac_ptr, &bytes_read);
22730               mac_ptr += bytes_read;
22731             }
22732           /* FALLTHROUGH */
22733
22734         default:
22735           mac_ptr = skip_unknown_opcode (macinfo_type, opcode_definitions,
22736                                          mac_ptr, mac_end, abfd, offset_size,
22737                                          section);
22738           if (mac_ptr == NULL)
22739             return;
22740           break;
22741         }
22742     } while (macinfo_type != 0 && current_file == NULL);
22743
22744   /* Second pass: Process all entries.
22745
22746      Use the AT_COMMAND_LINE flag to determine whether we are still processing
22747      command-line macro definitions/undefinitions.  This flag is unset when we
22748      reach the first DW_MACINFO_start_file entry.  */
22749
22750   htab_up include_hash (htab_create_alloc (1, htab_hash_pointer,
22751                                            htab_eq_pointer,
22752                                            NULL, xcalloc, xfree));
22753   mac_ptr = section->buffer + offset;
22754   slot = htab_find_slot (include_hash.get (), mac_ptr, INSERT);
22755   *slot = (void *) mac_ptr;
22756   dwarf_decode_macro_bytes (abfd, mac_ptr, mac_end,
22757                             current_file, lh, section,
22758                             section_is_gnu, 0, offset_size,
22759                             include_hash.get ());
22760 }
22761
22762 /* Check if the attribute's form is a DW_FORM_block*
22763    if so return true else false.  */
22764
22765 static int
22766 attr_form_is_block (const struct attribute *attr)
22767 {
22768   return (attr == NULL ? 0 :
22769       attr->form == DW_FORM_block1
22770       || attr->form == DW_FORM_block2
22771       || attr->form == DW_FORM_block4
22772       || attr->form == DW_FORM_block
22773       || attr->form == DW_FORM_exprloc);
22774 }
22775
22776 /* Return non-zero if ATTR's value is a section offset --- classes
22777    lineptr, loclistptr, macptr or rangelistptr --- or zero, otherwise.
22778    You may use DW_UNSND (attr) to retrieve such offsets.
22779
22780    Section 7.5.4, "Attribute Encodings", explains that no attribute
22781    may have a value that belongs to more than one of these classes; it
22782    would be ambiguous if we did, because we use the same forms for all
22783    of them.  */
22784
22785 static int
22786 attr_form_is_section_offset (const struct attribute *attr)
22787 {
22788   return (attr->form == DW_FORM_data4
22789           || attr->form == DW_FORM_data8
22790           || attr->form == DW_FORM_sec_offset);
22791 }
22792
22793 /* Return non-zero if ATTR's value falls in the 'constant' class, or
22794    zero otherwise.  When this function returns true, you can apply
22795    dwarf2_get_attr_constant_value to it.
22796
22797    However, note that for some attributes you must check
22798    attr_form_is_section_offset before using this test.  DW_FORM_data4
22799    and DW_FORM_data8 are members of both the constant class, and of
22800    the classes that contain offsets into other debug sections
22801    (lineptr, loclistptr, macptr or rangelistptr).  The DWARF spec says
22802    that, if an attribute's can be either a constant or one of the
22803    section offset classes, DW_FORM_data4 and DW_FORM_data8 should be
22804    taken as section offsets, not constants.
22805
22806    DW_FORM_data16 is not considered as dwarf2_get_attr_constant_value
22807    cannot handle that.  */
22808
22809 static int
22810 attr_form_is_constant (const struct attribute *attr)
22811 {
22812   switch (attr->form)
22813     {
22814     case DW_FORM_sdata:
22815     case DW_FORM_udata:
22816     case DW_FORM_data1:
22817     case DW_FORM_data2:
22818     case DW_FORM_data4:
22819     case DW_FORM_data8:
22820     case DW_FORM_implicit_const:
22821       return 1;
22822     default:
22823       return 0;
22824     }
22825 }
22826
22827
22828 /* DW_ADDR is always stored already as sect_offset; despite for the forms
22829    besides DW_FORM_ref_addr it is stored as cu_offset in the DWARF file.  */
22830
22831 static int
22832 attr_form_is_ref (const struct attribute *attr)
22833 {
22834   switch (attr->form)
22835     {
22836     case DW_FORM_ref_addr:
22837     case DW_FORM_ref1:
22838     case DW_FORM_ref2:
22839     case DW_FORM_ref4:
22840     case DW_FORM_ref8:
22841     case DW_FORM_ref_udata:
22842     case DW_FORM_GNU_ref_alt:
22843       return 1;
22844     default:
22845       return 0;
22846     }
22847 }
22848
22849 /* Return the .debug_loc section to use for CU.
22850    For DWO files use .debug_loc.dwo.  */
22851
22852 static struct dwarf2_section_info *
22853 cu_debug_loc_section (struct dwarf2_cu *cu)
22854 {
22855   if (cu->dwo_unit)
22856     {
22857       struct dwo_sections *sections = &cu->dwo_unit->dwo_file->sections;
22858       
22859       return cu->header.version >= 5 ? &sections->loclists : &sections->loc;
22860     }
22861   return (cu->header.version >= 5 ? &dwarf2_per_objfile->loclists
22862                                   : &dwarf2_per_objfile->loc);
22863 }
22864
22865 /* A helper function that fills in a dwarf2_loclist_baton.  */
22866
22867 static void
22868 fill_in_loclist_baton (struct dwarf2_cu *cu,
22869                        struct dwarf2_loclist_baton *baton,
22870                        const struct attribute *attr)
22871 {
22872   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22873
22874   dwarf2_read_section (dwarf2_per_objfile->objfile, section);
22875
22876   baton->per_cu = cu->per_cu;
22877   gdb_assert (baton->per_cu);
22878   /* We don't know how long the location list is, but make sure we
22879      don't run off the edge of the section.  */
22880   baton->size = section->size - DW_UNSND (attr);
22881   baton->data = section->buffer + DW_UNSND (attr);
22882   baton->base_address = cu->base_address;
22883   baton->from_dwo = cu->dwo_unit != NULL;
22884 }
22885
22886 static void
22887 dwarf2_symbol_mark_computed (const struct attribute *attr, struct symbol *sym,
22888                              struct dwarf2_cu *cu, int is_block)
22889 {
22890   struct objfile *objfile = dwarf2_per_objfile->objfile;
22891   struct dwarf2_section_info *section = cu_debug_loc_section (cu);
22892
22893   if (attr_form_is_section_offset (attr)
22894       /* .debug_loc{,.dwo} may not exist at all, or the offset may be outside
22895          the section.  If so, fall through to the complaint in the
22896          other branch.  */
22897       && DW_UNSND (attr) < dwarf2_section_size (objfile, section))
22898     {
22899       struct dwarf2_loclist_baton *baton;
22900
22901       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_loclist_baton);
22902
22903       fill_in_loclist_baton (cu, baton, attr);
22904
22905       if (cu->base_known == 0)
22906         complaint (&symfile_complaints,
22907                    _("Location list used without "
22908                      "specifying the CU base address."));
22909
22910       SYMBOL_ACLASS_INDEX (sym) = (is_block
22911                                    ? dwarf2_loclist_block_index
22912                                    : dwarf2_loclist_index);
22913       SYMBOL_LOCATION_BATON (sym) = baton;
22914     }
22915   else
22916     {
22917       struct dwarf2_locexpr_baton *baton;
22918
22919       baton = XOBNEW (&objfile->objfile_obstack, struct dwarf2_locexpr_baton);
22920       baton->per_cu = cu->per_cu;
22921       gdb_assert (baton->per_cu);
22922
22923       if (attr_form_is_block (attr))
22924         {
22925           /* Note that we're just copying the block's data pointer
22926              here, not the actual data.  We're still pointing into the
22927              info_buffer for SYM's objfile; right now we never release
22928              that buffer, but when we do clean up properly this may
22929              need to change.  */
22930           baton->size = DW_BLOCK (attr)->size;
22931           baton->data = DW_BLOCK (attr)->data;
22932         }
22933       else
22934         {
22935           dwarf2_invalid_attrib_class_complaint ("location description",
22936                                                  SYMBOL_NATURAL_NAME (sym));
22937           baton->size = 0;
22938         }
22939
22940       SYMBOL_ACLASS_INDEX (sym) = (is_block
22941                                    ? dwarf2_locexpr_block_index
22942                                    : dwarf2_locexpr_index);
22943       SYMBOL_LOCATION_BATON (sym) = baton;
22944     }
22945 }
22946
22947 /* Return the OBJFILE associated with the compilation unit CU.  If CU
22948    came from a separate debuginfo file, then the master objfile is
22949    returned.  */
22950
22951 struct objfile *
22952 dwarf2_per_cu_objfile (struct dwarf2_per_cu_data *per_cu)
22953 {
22954   struct objfile *objfile = per_cu->objfile;
22955
22956   /* Return the master objfile, so that we can report and look up the
22957      correct file containing this variable.  */
22958   if (objfile->separate_debug_objfile_backlink)
22959     objfile = objfile->separate_debug_objfile_backlink;
22960
22961   return objfile;
22962 }
22963
22964 /* Return comp_unit_head for PER_CU, either already available in PER_CU->CU
22965    (CU_HEADERP is unused in such case) or prepare a temporary copy at
22966    CU_HEADERP first.  */
22967
22968 static const struct comp_unit_head *
22969 per_cu_header_read_in (struct comp_unit_head *cu_headerp,
22970                        struct dwarf2_per_cu_data *per_cu)
22971 {
22972   const gdb_byte *info_ptr;
22973
22974   if (per_cu->cu)
22975     return &per_cu->cu->header;
22976
22977   info_ptr = per_cu->section->buffer + to_underlying (per_cu->sect_off);
22978
22979   memset (cu_headerp, 0, sizeof (*cu_headerp));
22980   read_comp_unit_head (cu_headerp, info_ptr, per_cu->section,
22981                        rcuh_kind::COMPILE);
22982
22983   return cu_headerp;
22984 }
22985
22986 /* Return the address size given in the compilation unit header for CU.  */
22987
22988 int
22989 dwarf2_per_cu_addr_size (struct dwarf2_per_cu_data *per_cu)
22990 {
22991   struct comp_unit_head cu_header_local;
22992   const struct comp_unit_head *cu_headerp;
22993
22994   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
22995
22996   return cu_headerp->addr_size;
22997 }
22998
22999 /* Return the offset size given in the compilation unit header for CU.  */
23000
23001 int
23002 dwarf2_per_cu_offset_size (struct dwarf2_per_cu_data *per_cu)
23003 {
23004   struct comp_unit_head cu_header_local;
23005   const struct comp_unit_head *cu_headerp;
23006
23007   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23008
23009   return cu_headerp->offset_size;
23010 }
23011
23012 /* See its dwarf2loc.h declaration.  */
23013
23014 int
23015 dwarf2_per_cu_ref_addr_size (struct dwarf2_per_cu_data *per_cu)
23016 {
23017   struct comp_unit_head cu_header_local;
23018   const struct comp_unit_head *cu_headerp;
23019
23020   cu_headerp = per_cu_header_read_in (&cu_header_local, per_cu);
23021
23022   if (cu_headerp->version == 2)
23023     return cu_headerp->addr_size;
23024   else
23025     return cu_headerp->offset_size;
23026 }
23027
23028 /* Return the text offset of the CU.  The returned offset comes from
23029    this CU's objfile.  If this objfile came from a separate debuginfo
23030    file, then the offset may be different from the corresponding
23031    offset in the parent objfile.  */
23032
23033 CORE_ADDR
23034 dwarf2_per_cu_text_offset (struct dwarf2_per_cu_data *per_cu)
23035 {
23036   struct objfile *objfile = per_cu->objfile;
23037
23038   return ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23039 }
23040
23041 /* Return DWARF version number of PER_CU.  */
23042
23043 short
23044 dwarf2_version (struct dwarf2_per_cu_data *per_cu)
23045 {
23046   return per_cu->dwarf_version;
23047 }
23048
23049 /* Locate the .debug_info compilation unit from CU's objfile which contains
23050    the DIE at OFFSET.  Raises an error on failure.  */
23051
23052 static struct dwarf2_per_cu_data *
23053 dwarf2_find_containing_comp_unit (sect_offset sect_off,
23054                                   unsigned int offset_in_dwz,
23055                                   struct objfile *objfile)
23056 {
23057   struct dwarf2_per_cu_data *this_cu;
23058   int low, high;
23059   const sect_offset *cu_off;
23060
23061   low = 0;
23062   high = dwarf2_per_objfile->n_comp_units - 1;
23063   while (high > low)
23064     {
23065       struct dwarf2_per_cu_data *mid_cu;
23066       int mid = low + (high - low) / 2;
23067
23068       mid_cu = dwarf2_per_objfile->all_comp_units[mid];
23069       cu_off = &mid_cu->sect_off;
23070       if (mid_cu->is_dwz > offset_in_dwz
23071           || (mid_cu->is_dwz == offset_in_dwz && *cu_off >= sect_off))
23072         high = mid;
23073       else
23074         low = mid + 1;
23075     }
23076   gdb_assert (low == high);
23077   this_cu = dwarf2_per_objfile->all_comp_units[low];
23078   cu_off = &this_cu->sect_off;
23079   if (this_cu->is_dwz != offset_in_dwz || *cu_off > sect_off)
23080     {
23081       if (low == 0 || this_cu->is_dwz != offset_in_dwz)
23082         error (_("Dwarf Error: could not find partial DIE containing "
23083                "offset 0x%x [in module %s]"),
23084                to_underlying (sect_off), bfd_get_filename (objfile->obfd));
23085
23086       gdb_assert (dwarf2_per_objfile->all_comp_units[low-1]->sect_off
23087                   <= sect_off);
23088       return dwarf2_per_objfile->all_comp_units[low-1];
23089     }
23090   else
23091     {
23092       this_cu = dwarf2_per_objfile->all_comp_units[low];
23093       if (low == dwarf2_per_objfile->n_comp_units - 1
23094           && sect_off >= this_cu->sect_off + this_cu->length)
23095         error (_("invalid dwarf2 offset %u"), to_underlying (sect_off));
23096       gdb_assert (sect_off < this_cu->sect_off + this_cu->length);
23097       return this_cu;
23098     }
23099 }
23100
23101 /* Initialize dwarf2_cu CU, owned by PER_CU.  */
23102
23103 static void
23104 init_one_comp_unit (struct dwarf2_cu *cu, struct dwarf2_per_cu_data *per_cu)
23105 {
23106   memset (cu, 0, sizeof (*cu));
23107   per_cu->cu = cu;
23108   cu->per_cu = per_cu;
23109   cu->objfile = per_cu->objfile;
23110   obstack_init (&cu->comp_unit_obstack);
23111 }
23112
23113 /* Initialize basic fields of dwarf_cu CU according to DIE COMP_UNIT_DIE.  */
23114
23115 static void
23116 prepare_one_comp_unit (struct dwarf2_cu *cu, struct die_info *comp_unit_die,
23117                        enum language pretend_language)
23118 {
23119   struct attribute *attr;
23120
23121   /* Set the language we're debugging.  */
23122   attr = dwarf2_attr (comp_unit_die, DW_AT_language, cu);
23123   if (attr)
23124     set_cu_language (DW_UNSND (attr), cu);
23125   else
23126     {
23127       cu->language = pretend_language;
23128       cu->language_defn = language_def (cu->language);
23129     }
23130
23131   cu->producer = dwarf2_string_attr (comp_unit_die, DW_AT_producer, cu);
23132 }
23133
23134 /* Release one cached compilation unit, CU.  We unlink it from the tree
23135    of compilation units, but we don't remove it from the read_in_chain;
23136    the caller is responsible for that.
23137    NOTE: DATA is a void * because this function is also used as a
23138    cleanup routine.  */
23139
23140 static void
23141 free_heap_comp_unit (void *data)
23142 {
23143   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23144
23145   gdb_assert (cu->per_cu != NULL);
23146   cu->per_cu->cu = NULL;
23147   cu->per_cu = NULL;
23148
23149   obstack_free (&cu->comp_unit_obstack, NULL);
23150
23151   xfree (cu);
23152 }
23153
23154 /* This cleanup function is passed the address of a dwarf2_cu on the stack
23155    when we're finished with it.  We can't free the pointer itself, but be
23156    sure to unlink it from the cache.  Also release any associated storage.  */
23157
23158 static void
23159 free_stack_comp_unit (void *data)
23160 {
23161   struct dwarf2_cu *cu = (struct dwarf2_cu *) data;
23162
23163   gdb_assert (cu->per_cu != NULL);
23164   cu->per_cu->cu = NULL;
23165   cu->per_cu = NULL;
23166
23167   obstack_free (&cu->comp_unit_obstack, NULL);
23168   cu->partial_dies = NULL;
23169 }
23170
23171 /* Free all cached compilation units.  */
23172
23173 static void
23174 free_cached_comp_units (void *data)
23175 {
23176   dwarf2_per_objfile->free_cached_comp_units ();
23177 }
23178
23179 /* Increase the age counter on each cached compilation unit, and free
23180    any that are too old.  */
23181
23182 static void
23183 age_cached_comp_units (void)
23184 {
23185   struct dwarf2_per_cu_data *per_cu, **last_chain;
23186
23187   dwarf2_clear_marks (dwarf2_per_objfile->read_in_chain);
23188   per_cu = dwarf2_per_objfile->read_in_chain;
23189   while (per_cu != NULL)
23190     {
23191       per_cu->cu->last_used ++;
23192       if (per_cu->cu->last_used <= dwarf_max_cache_age)
23193         dwarf2_mark (per_cu->cu);
23194       per_cu = per_cu->cu->read_in_chain;
23195     }
23196
23197   per_cu = dwarf2_per_objfile->read_in_chain;
23198   last_chain = &dwarf2_per_objfile->read_in_chain;
23199   while (per_cu != NULL)
23200     {
23201       struct dwarf2_per_cu_data *next_cu;
23202
23203       next_cu = per_cu->cu->read_in_chain;
23204
23205       if (!per_cu->cu->mark)
23206         {
23207           free_heap_comp_unit (per_cu->cu);
23208           *last_chain = next_cu;
23209         }
23210       else
23211         last_chain = &per_cu->cu->read_in_chain;
23212
23213       per_cu = next_cu;
23214     }
23215 }
23216
23217 /* Remove a single compilation unit from the cache.  */
23218
23219 static void
23220 free_one_cached_comp_unit (struct dwarf2_per_cu_data *target_per_cu)
23221 {
23222   struct dwarf2_per_cu_data *per_cu, **last_chain;
23223
23224   per_cu = dwarf2_per_objfile->read_in_chain;
23225   last_chain = &dwarf2_per_objfile->read_in_chain;
23226   while (per_cu != NULL)
23227     {
23228       struct dwarf2_per_cu_data *next_cu;
23229
23230       next_cu = per_cu->cu->read_in_chain;
23231
23232       if (per_cu == target_per_cu)
23233         {
23234           free_heap_comp_unit (per_cu->cu);
23235           per_cu->cu = NULL;
23236           *last_chain = next_cu;
23237           break;
23238         }
23239       else
23240         last_chain = &per_cu->cu->read_in_chain;
23241
23242       per_cu = next_cu;
23243     }
23244 }
23245
23246 /* Release all extra memory associated with OBJFILE.  */
23247
23248 void
23249 dwarf2_free_objfile (struct objfile *objfile)
23250 {
23251   dwarf2_per_objfile
23252     = (struct dwarf2_per_objfile *) objfile_data (objfile,
23253                                                   dwarf2_objfile_data_key);
23254
23255   if (dwarf2_per_objfile == NULL)
23256     return;
23257
23258   dwarf2_per_objfile->~dwarf2_per_objfile ();
23259 }
23260
23261 /* A set of CU "per_cu" pointer, DIE offset, and GDB type pointer.
23262    We store these in a hash table separate from the DIEs, and preserve them
23263    when the DIEs are flushed out of cache.
23264
23265    The CU "per_cu" pointer is needed because offset alone is not enough to
23266    uniquely identify the type.  A file may have multiple .debug_types sections,
23267    or the type may come from a DWO file.  Furthermore, while it's more logical
23268    to use per_cu->section+offset, with Fission the section with the data is in
23269    the DWO file but we don't know that section at the point we need it.
23270    We have to use something in dwarf2_per_cu_data (or the pointer to it)
23271    because we can enter the lookup routine, get_die_type_at_offset, from
23272    outside this file, and thus won't necessarily have PER_CU->cu.
23273    Fortunately, PER_CU is stable for the life of the objfile.  */
23274
23275 struct dwarf2_per_cu_offset_and_type
23276 {
23277   const struct dwarf2_per_cu_data *per_cu;
23278   sect_offset sect_off;
23279   struct type *type;
23280 };
23281
23282 /* Hash function for a dwarf2_per_cu_offset_and_type.  */
23283
23284 static hashval_t
23285 per_cu_offset_and_type_hash (const void *item)
23286 {
23287   const struct dwarf2_per_cu_offset_and_type *ofs
23288     = (const struct dwarf2_per_cu_offset_and_type *) item;
23289
23290   return (uintptr_t) ofs->per_cu + to_underlying (ofs->sect_off);
23291 }
23292
23293 /* Equality function for a dwarf2_per_cu_offset_and_type.  */
23294
23295 static int
23296 per_cu_offset_and_type_eq (const void *item_lhs, const void *item_rhs)
23297 {
23298   const struct dwarf2_per_cu_offset_and_type *ofs_lhs
23299     = (const struct dwarf2_per_cu_offset_and_type *) item_lhs;
23300   const struct dwarf2_per_cu_offset_and_type *ofs_rhs
23301     = (const struct dwarf2_per_cu_offset_and_type *) item_rhs;
23302
23303   return (ofs_lhs->per_cu == ofs_rhs->per_cu
23304           && ofs_lhs->sect_off == ofs_rhs->sect_off);
23305 }
23306
23307 /* Set the type associated with DIE to TYPE.  Save it in CU's hash
23308    table if necessary.  For convenience, return TYPE.
23309
23310    The DIEs reading must have careful ordering to:
23311     * Not cause infite loops trying to read in DIEs as a prerequisite for
23312       reading current DIE.
23313     * Not trying to dereference contents of still incompletely read in types
23314       while reading in other DIEs.
23315     * Enable referencing still incompletely read in types just by a pointer to
23316       the type without accessing its fields.
23317
23318    Therefore caller should follow these rules:
23319      * Try to fetch any prerequisite types we may need to build this DIE type
23320        before building the type and calling set_die_type.
23321      * After building type call set_die_type for current DIE as soon as
23322        possible before fetching more types to complete the current type.
23323      * Make the type as complete as possible before fetching more types.  */
23324
23325 static struct type *
23326 set_die_type (struct die_info *die, struct type *type, struct dwarf2_cu *cu)
23327 {
23328   struct dwarf2_per_cu_offset_and_type **slot, ofs;
23329   struct objfile *objfile = cu->objfile;
23330   struct attribute *attr;
23331   struct dynamic_prop prop;
23332
23333   /* For Ada types, make sure that the gnat-specific data is always
23334      initialized (if not already set).  There are a few types where
23335      we should not be doing so, because the type-specific area is
23336      already used to hold some other piece of info (eg: TYPE_CODE_FLT
23337      where the type-specific area is used to store the floatformat).
23338      But this is not a problem, because the gnat-specific information
23339      is actually not needed for these types.  */
23340   if (need_gnat_info (cu)
23341       && TYPE_CODE (type) != TYPE_CODE_FUNC
23342       && TYPE_CODE (type) != TYPE_CODE_FLT
23343       && TYPE_CODE (type) != TYPE_CODE_METHODPTR
23344       && TYPE_CODE (type) != TYPE_CODE_MEMBERPTR
23345       && TYPE_CODE (type) != TYPE_CODE_METHOD
23346       && !HAVE_GNAT_AUX_INFO (type))
23347     INIT_GNAT_SPECIFIC (type);
23348
23349   /* Read DW_AT_allocated and set in type.  */
23350   attr = dwarf2_attr (die, DW_AT_allocated, cu);
23351   if (attr_form_is_block (attr))
23352     {
23353       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23354         add_dyn_prop (DYN_PROP_ALLOCATED, prop, type, objfile);
23355     }
23356   else if (attr != NULL)
23357     {
23358       complaint (&symfile_complaints,
23359                  _("DW_AT_allocated has the wrong form (%s) at DIE 0x%x"),
23360                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23361                  to_underlying (die->sect_off));
23362     }
23363
23364   /* Read DW_AT_associated and set in type.  */
23365   attr = dwarf2_attr (die, DW_AT_associated, cu);
23366   if (attr_form_is_block (attr))
23367     {
23368       if (attr_to_dynamic_prop (attr, die, cu, &prop))
23369         add_dyn_prop (DYN_PROP_ASSOCIATED, prop, type, objfile);
23370     }
23371   else if (attr != NULL)
23372     {
23373       complaint (&symfile_complaints,
23374                  _("DW_AT_associated has the wrong form (%s) at DIE 0x%x"),
23375                  (attr != NULL ? dwarf_form_name (attr->form) : "n/a"),
23376                  to_underlying (die->sect_off));
23377     }
23378
23379   /* Read DW_AT_data_location and set in type.  */
23380   attr = dwarf2_attr (die, DW_AT_data_location, cu);
23381   if (attr_to_dynamic_prop (attr, die, cu, &prop))
23382     add_dyn_prop (DYN_PROP_DATA_LOCATION, prop, type, objfile);
23383
23384   if (dwarf2_per_objfile->die_type_hash == NULL)
23385     {
23386       dwarf2_per_objfile->die_type_hash =
23387         htab_create_alloc_ex (127,
23388                               per_cu_offset_and_type_hash,
23389                               per_cu_offset_and_type_eq,
23390                               NULL,
23391                               &objfile->objfile_obstack,
23392                               hashtab_obstack_allocate,
23393                               dummy_obstack_deallocate);
23394     }
23395
23396   ofs.per_cu = cu->per_cu;
23397   ofs.sect_off = die->sect_off;
23398   ofs.type = type;
23399   slot = (struct dwarf2_per_cu_offset_and_type **)
23400     htab_find_slot (dwarf2_per_objfile->die_type_hash, &ofs, INSERT);
23401   if (*slot)
23402     complaint (&symfile_complaints,
23403                _("A problem internal to GDB: DIE 0x%x has type already set"),
23404                to_underlying (die->sect_off));
23405   *slot = XOBNEW (&objfile->objfile_obstack,
23406                   struct dwarf2_per_cu_offset_and_type);
23407   **slot = ofs;
23408   return type;
23409 }
23410
23411 /* Look up the type for the die at SECT_OFF in PER_CU in die_type_hash,
23412    or return NULL if the die does not have a saved type.  */
23413
23414 static struct type *
23415 get_die_type_at_offset (sect_offset sect_off,
23416                         struct dwarf2_per_cu_data *per_cu)
23417 {
23418   struct dwarf2_per_cu_offset_and_type *slot, ofs;
23419
23420   if (dwarf2_per_objfile->die_type_hash == NULL)
23421     return NULL;
23422
23423   ofs.per_cu = per_cu;
23424   ofs.sect_off = sect_off;
23425   slot = ((struct dwarf2_per_cu_offset_and_type *)
23426           htab_find (dwarf2_per_objfile->die_type_hash, &ofs));
23427   if (slot)
23428     return slot->type;
23429   else
23430     return NULL;
23431 }
23432
23433 /* Look up the type for DIE in CU in die_type_hash,
23434    or return NULL if DIE does not have a saved type.  */
23435
23436 static struct type *
23437 get_die_type (struct die_info *die, struct dwarf2_cu *cu)
23438 {
23439   return get_die_type_at_offset (die->sect_off, cu->per_cu);
23440 }
23441
23442 /* Add a dependence relationship from CU to REF_PER_CU.  */
23443
23444 static void
23445 dwarf2_add_dependence (struct dwarf2_cu *cu,
23446                        struct dwarf2_per_cu_data *ref_per_cu)
23447 {
23448   void **slot;
23449
23450   if (cu->dependencies == NULL)
23451     cu->dependencies
23452       = htab_create_alloc_ex (5, htab_hash_pointer, htab_eq_pointer,
23453                               NULL, &cu->comp_unit_obstack,
23454                               hashtab_obstack_allocate,
23455                               dummy_obstack_deallocate);
23456
23457   slot = htab_find_slot (cu->dependencies, ref_per_cu, INSERT);
23458   if (*slot == NULL)
23459     *slot = ref_per_cu;
23460 }
23461
23462 /* Subroutine of dwarf2_mark to pass to htab_traverse.
23463    Set the mark field in every compilation unit in the
23464    cache that we must keep because we are keeping CU.  */
23465
23466 static int
23467 dwarf2_mark_helper (void **slot, void *data)
23468 {
23469   struct dwarf2_per_cu_data *per_cu;
23470
23471   per_cu = (struct dwarf2_per_cu_data *) *slot;
23472
23473   /* cu->dependencies references may not yet have been ever read if QUIT aborts
23474      reading of the chain.  As such dependencies remain valid it is not much
23475      useful to track and undo them during QUIT cleanups.  */
23476   if (per_cu->cu == NULL)
23477     return 1;
23478
23479   if (per_cu->cu->mark)
23480     return 1;
23481   per_cu->cu->mark = 1;
23482
23483   if (per_cu->cu->dependencies != NULL)
23484     htab_traverse (per_cu->cu->dependencies, dwarf2_mark_helper, NULL);
23485
23486   return 1;
23487 }
23488
23489 /* Set the mark field in CU and in every other compilation unit in the
23490    cache that we must keep because we are keeping CU.  */
23491
23492 static void
23493 dwarf2_mark (struct dwarf2_cu *cu)
23494 {
23495   if (cu->mark)
23496     return;
23497   cu->mark = 1;
23498   if (cu->dependencies != NULL)
23499     htab_traverse (cu->dependencies, dwarf2_mark_helper, NULL);
23500 }
23501
23502 static void
23503 dwarf2_clear_marks (struct dwarf2_per_cu_data *per_cu)
23504 {
23505   while (per_cu)
23506     {
23507       per_cu->cu->mark = 0;
23508       per_cu = per_cu->cu->read_in_chain;
23509     }
23510 }
23511
23512 /* Trivial hash function for partial_die_info: the hash value of a DIE
23513    is its offset in .debug_info for this objfile.  */
23514
23515 static hashval_t
23516 partial_die_hash (const void *item)
23517 {
23518   const struct partial_die_info *part_die
23519     = (const struct partial_die_info *) item;
23520
23521   return to_underlying (part_die->sect_off);
23522 }
23523
23524 /* Trivial comparison function for partial_die_info structures: two DIEs
23525    are equal if they have the same offset.  */
23526
23527 static int
23528 partial_die_eq (const void *item_lhs, const void *item_rhs)
23529 {
23530   const struct partial_die_info *part_die_lhs
23531     = (const struct partial_die_info *) item_lhs;
23532   const struct partial_die_info *part_die_rhs
23533     = (const struct partial_die_info *) item_rhs;
23534
23535   return part_die_lhs->sect_off == part_die_rhs->sect_off;
23536 }
23537
23538 static struct cmd_list_element *set_dwarf_cmdlist;
23539 static struct cmd_list_element *show_dwarf_cmdlist;
23540
23541 static void
23542 set_dwarf_cmd (const char *args, int from_tty)
23543 {
23544   help_list (set_dwarf_cmdlist, "maintenance set dwarf ", all_commands,
23545              gdb_stdout);
23546 }
23547
23548 static void
23549 show_dwarf_cmd (const char *args, int from_tty)
23550 {
23551   cmd_show_list (show_dwarf_cmdlist, from_tty, "");
23552 }
23553
23554 /* Free data associated with OBJFILE, if necessary.  */
23555
23556 static void
23557 dwarf2_per_objfile_free (struct objfile *objfile, void *d)
23558 {
23559   struct dwarf2_per_objfile *data = (struct dwarf2_per_objfile *) d;
23560   int ix;
23561
23562   /* Make sure we don't accidentally use dwarf2_per_objfile while
23563      cleaning up.  */
23564   dwarf2_per_objfile = NULL;
23565
23566   for (ix = 0; ix < data->n_comp_units; ++ix)
23567    VEC_free (dwarf2_per_cu_ptr, data->all_comp_units[ix]->imported_symtabs);
23568
23569   for (ix = 0; ix < data->n_type_units; ++ix)
23570     VEC_free (dwarf2_per_cu_ptr,
23571               data->all_type_units[ix]->per_cu.imported_symtabs);
23572   xfree (data->all_type_units);
23573
23574   VEC_free (dwarf2_section_info_def, data->types);
23575
23576   if (data->dwo_files)
23577     free_dwo_files (data->dwo_files, objfile);
23578   if (data->dwp_file)
23579     gdb_bfd_unref (data->dwp_file->dbfd);
23580
23581   if (data->dwz_file && data->dwz_file->dwz_bfd)
23582     gdb_bfd_unref (data->dwz_file->dwz_bfd);
23583
23584   if (data->index_table != NULL)
23585     data->index_table->~mapped_index ();
23586 }
23587
23588 \f
23589 /* The "save gdb-index" command.  */
23590
23591 /* In-memory buffer to prepare data to be written later to a file.  */
23592 class data_buf
23593 {
23594 public:
23595   /* Copy DATA to the end of the buffer.  */
23596   template<typename T>
23597   void append_data (const T &data)
23598   {
23599     std::copy (reinterpret_cast<const gdb_byte *> (&data),
23600                reinterpret_cast<const gdb_byte *> (&data + 1),
23601                grow (sizeof (data)));
23602   }
23603
23604   /* Copy CSTR (a zero-terminated string) to the end of buffer.  The
23605      terminating zero is appended too.  */
23606   void append_cstr0 (const char *cstr)
23607   {
23608     const size_t size = strlen (cstr) + 1;
23609     std::copy (cstr, cstr + size, grow (size));
23610   }
23611
23612   /* Accept a host-format integer in VAL and append it to the buffer
23613      as a target-format integer which is LEN bytes long.  */
23614   void append_uint (size_t len, bfd_endian byte_order, ULONGEST val)
23615   {
23616     ::store_unsigned_integer (grow (len), len, byte_order, val);
23617   }
23618
23619   /* Return the size of the buffer.  */
23620   size_t size () const
23621   {
23622     return m_vec.size ();
23623   }
23624
23625   /* Write the buffer to FILE.  */
23626   void file_write (FILE *file) const
23627   {
23628     if (::fwrite (m_vec.data (), 1, m_vec.size (), file) != m_vec.size ())
23629       error (_("couldn't write data to file"));
23630   }
23631
23632 private:
23633   /* Grow SIZE bytes at the end of the buffer.  Returns a pointer to
23634      the start of the new block.  */
23635   gdb_byte *grow (size_t size)
23636   {
23637     m_vec.resize (m_vec.size () + size);
23638     return &*m_vec.end () - size;
23639   }
23640
23641   gdb::byte_vector m_vec;
23642 };
23643
23644 /* An entry in the symbol table.  */
23645 struct symtab_index_entry
23646 {
23647   /* The name of the symbol.  */
23648   const char *name;
23649   /* The offset of the name in the constant pool.  */
23650   offset_type index_offset;
23651   /* A sorted vector of the indices of all the CUs that hold an object
23652      of this name.  */
23653   std::vector<offset_type> cu_indices;
23654 };
23655
23656 /* The symbol table.  This is a power-of-2-sized hash table.  */
23657 struct mapped_symtab
23658 {
23659   mapped_symtab ()
23660   {
23661     data.resize (1024);
23662   }
23663
23664   offset_type n_elements = 0;
23665   std::vector<symtab_index_entry> data;
23666 };
23667
23668 /* Find a slot in SYMTAB for the symbol NAME.  Returns a reference to
23669    the slot.
23670    
23671    Function is used only during write_hash_table so no index format backward
23672    compatibility is needed.  */
23673
23674 static symtab_index_entry &
23675 find_slot (struct mapped_symtab *symtab, const char *name)
23676 {
23677   offset_type index, step, hash = mapped_index_string_hash (INT_MAX, name);
23678
23679   index = hash & (symtab->data.size () - 1);
23680   step = ((hash * 17) & (symtab->data.size () - 1)) | 1;
23681
23682   for (;;)
23683     {
23684       if (symtab->data[index].name == NULL
23685           || strcmp (name, symtab->data[index].name) == 0)
23686         return symtab->data[index];
23687       index = (index + step) & (symtab->data.size () - 1);
23688     }
23689 }
23690
23691 /* Expand SYMTAB's hash table.  */
23692
23693 static void
23694 hash_expand (struct mapped_symtab *symtab)
23695 {
23696   auto old_entries = std::move (symtab->data);
23697
23698   symtab->data.clear ();
23699   symtab->data.resize (old_entries.size () * 2);
23700
23701   for (auto &it : old_entries)
23702     if (it.name != NULL)
23703       {
23704         auto &ref = find_slot (symtab, it.name);
23705         ref = std::move (it);
23706       }
23707 }
23708
23709 /* Add an entry to SYMTAB.  NAME is the name of the symbol.
23710    CU_INDEX is the index of the CU in which the symbol appears.
23711    IS_STATIC is one if the symbol is static, otherwise zero (global).  */
23712
23713 static void
23714 add_index_entry (struct mapped_symtab *symtab, const char *name,
23715                  int is_static, gdb_index_symbol_kind kind,
23716                  offset_type cu_index)
23717 {
23718   offset_type cu_index_and_attrs;
23719
23720   ++symtab->n_elements;
23721   if (4 * symtab->n_elements / 3 >= symtab->data.size ())
23722     hash_expand (symtab);
23723
23724   symtab_index_entry &slot = find_slot (symtab, name);
23725   if (slot.name == NULL)
23726     {
23727       slot.name = name;
23728       /* index_offset is set later.  */
23729     }
23730
23731   cu_index_and_attrs = 0;
23732   DW2_GDB_INDEX_CU_SET_VALUE (cu_index_and_attrs, cu_index);
23733   DW2_GDB_INDEX_SYMBOL_STATIC_SET_VALUE (cu_index_and_attrs, is_static);
23734   DW2_GDB_INDEX_SYMBOL_KIND_SET_VALUE (cu_index_and_attrs, kind);
23735
23736   /* We don't want to record an index value twice as we want to avoid the
23737      duplication.
23738      We process all global symbols and then all static symbols
23739      (which would allow us to avoid the duplication by only having to check
23740      the last entry pushed), but a symbol could have multiple kinds in one CU.
23741      To keep things simple we don't worry about the duplication here and
23742      sort and uniqufy the list after we've processed all symbols.  */
23743   slot.cu_indices.push_back (cu_index_and_attrs);
23744 }
23745
23746 /* Sort and remove duplicates of all symbols' cu_indices lists.  */
23747
23748 static void
23749 uniquify_cu_indices (struct mapped_symtab *symtab)
23750 {
23751   for (auto &entry : symtab->data)
23752     {
23753       if (entry.name != NULL && !entry.cu_indices.empty ())
23754         {
23755           auto &cu_indices = entry.cu_indices;
23756           std::sort (cu_indices.begin (), cu_indices.end ());
23757           auto from = std::unique (cu_indices.begin (), cu_indices.end ());
23758           cu_indices.erase (from, cu_indices.end ());
23759         }
23760     }
23761 }
23762
23763 /* A form of 'const char *' suitable for container keys.  Only the
23764    pointer is stored.  The strings themselves are compared, not the
23765    pointers.  */
23766 class c_str_view
23767 {
23768 public:
23769   c_str_view (const char *cstr)
23770     : m_cstr (cstr)
23771   {}
23772
23773   bool operator== (const c_str_view &other) const
23774   {
23775     return strcmp (m_cstr, other.m_cstr) == 0;
23776   }
23777
23778 private:
23779   friend class c_str_view_hasher;
23780   const char *const m_cstr;
23781 };
23782
23783 /* A std::unordered_map::hasher for c_str_view that uses the right
23784    hash function for strings in a mapped index.  */
23785 class c_str_view_hasher
23786 {
23787 public:
23788   size_t operator () (const c_str_view &x) const
23789   {
23790     return mapped_index_string_hash (INT_MAX, x.m_cstr);
23791   }
23792 };
23793
23794 /* A std::unordered_map::hasher for std::vector<>.  */
23795 template<typename T>
23796 class vector_hasher
23797 {
23798 public:
23799   size_t operator () (const std::vector<T> &key) const
23800   {
23801     return iterative_hash (key.data (),
23802                            sizeof (key.front ()) * key.size (), 0);
23803   }
23804 };
23805
23806 /* Write the mapped hash table SYMTAB to the data buffer OUTPUT, with
23807    constant pool entries going into the data buffer CPOOL.  */
23808
23809 static void
23810 write_hash_table (mapped_symtab *symtab, data_buf &output, data_buf &cpool)
23811 {
23812   {
23813     /* Elements are sorted vectors of the indices of all the CUs that
23814        hold an object of this name.  */
23815     std::unordered_map<std::vector<offset_type>, offset_type,
23816                        vector_hasher<offset_type>>
23817       symbol_hash_table;
23818
23819     /* We add all the index vectors to the constant pool first, to
23820        ensure alignment is ok.  */
23821     for (symtab_index_entry &entry : symtab->data)
23822       {
23823         if (entry.name == NULL)
23824           continue;
23825         gdb_assert (entry.index_offset == 0);
23826
23827         /* Finding before inserting is faster than always trying to
23828            insert, because inserting always allocates a node, does the
23829            lookup, and then destroys the new node if another node
23830            already had the same key.  C++17 try_emplace will avoid
23831            this.  */
23832         const auto found
23833           = symbol_hash_table.find (entry.cu_indices);
23834         if (found != symbol_hash_table.end ())
23835           {
23836             entry.index_offset = found->second;
23837             continue;
23838           }
23839
23840         symbol_hash_table.emplace (entry.cu_indices, cpool.size ());
23841         entry.index_offset = cpool.size ();
23842         cpool.append_data (MAYBE_SWAP (entry.cu_indices.size ()));
23843         for (const auto index : entry.cu_indices)
23844           cpool.append_data (MAYBE_SWAP (index));
23845       }
23846   }
23847
23848   /* Now write out the hash table.  */
23849   std::unordered_map<c_str_view, offset_type, c_str_view_hasher> str_table;
23850   for (const auto &entry : symtab->data)
23851     {
23852       offset_type str_off, vec_off;
23853
23854       if (entry.name != NULL)
23855         {
23856           const auto insertpair = str_table.emplace (entry.name, cpool.size ());
23857           if (insertpair.second)
23858             cpool.append_cstr0 (entry.name);
23859           str_off = insertpair.first->second;
23860           vec_off = entry.index_offset;
23861         }
23862       else
23863         {
23864           /* While 0 is a valid constant pool index, it is not valid
23865              to have 0 for both offsets.  */
23866           str_off = 0;
23867           vec_off = 0;
23868         }
23869
23870       output.append_data (MAYBE_SWAP (str_off));
23871       output.append_data (MAYBE_SWAP (vec_off));
23872     }
23873 }
23874
23875 typedef std::unordered_map<partial_symtab *, unsigned int> psym_index_map;
23876
23877 /* Helper struct for building the address table.  */
23878 struct addrmap_index_data
23879 {
23880   addrmap_index_data (data_buf &addr_vec_, psym_index_map &cu_index_htab_)
23881     : addr_vec (addr_vec_), cu_index_htab (cu_index_htab_)
23882   {}
23883
23884   struct objfile *objfile;
23885   data_buf &addr_vec;
23886   psym_index_map &cu_index_htab;
23887
23888   /* Non-zero if the previous_* fields are valid.
23889      We can't write an entry until we see the next entry (since it is only then
23890      that we know the end of the entry).  */
23891   int previous_valid;
23892   /* Index of the CU in the table of all CUs in the index file.  */
23893   unsigned int previous_cu_index;
23894   /* Start address of the CU.  */
23895   CORE_ADDR previous_cu_start;
23896 };
23897
23898 /* Write an address entry to ADDR_VEC.  */
23899
23900 static void
23901 add_address_entry (struct objfile *objfile, data_buf &addr_vec,
23902                    CORE_ADDR start, CORE_ADDR end, unsigned int cu_index)
23903 {
23904   CORE_ADDR baseaddr;
23905
23906   baseaddr = ANOFFSET (objfile->section_offsets, SECT_OFF_TEXT (objfile));
23907
23908   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, start - baseaddr);
23909   addr_vec.append_uint (8, BFD_ENDIAN_LITTLE, end - baseaddr);
23910   addr_vec.append_data (MAYBE_SWAP (cu_index));
23911 }
23912
23913 /* Worker function for traversing an addrmap to build the address table.  */
23914
23915 static int
23916 add_address_entry_worker (void *datap, CORE_ADDR start_addr, void *obj)
23917 {
23918   struct addrmap_index_data *data = (struct addrmap_index_data *) datap;
23919   struct partial_symtab *pst = (struct partial_symtab *) obj;
23920
23921   if (data->previous_valid)
23922     add_address_entry (data->objfile, data->addr_vec,
23923                        data->previous_cu_start, start_addr,
23924                        data->previous_cu_index);
23925
23926   data->previous_cu_start = start_addr;
23927   if (pst != NULL)
23928     {
23929       const auto it = data->cu_index_htab.find (pst);
23930       gdb_assert (it != data->cu_index_htab.cend ());
23931       data->previous_cu_index = it->second;
23932       data->previous_valid = 1;
23933     }
23934   else
23935     data->previous_valid = 0;
23936
23937   return 0;
23938 }
23939
23940 /* Write OBJFILE's address map to ADDR_VEC.
23941    CU_INDEX_HTAB is used to map addrmap entries to their CU indices
23942    in the index file.  */
23943
23944 static void
23945 write_address_map (struct objfile *objfile, data_buf &addr_vec,
23946                    psym_index_map &cu_index_htab)
23947 {
23948   struct addrmap_index_data addrmap_index_data (addr_vec, cu_index_htab);
23949
23950   /* When writing the address table, we have to cope with the fact that
23951      the addrmap iterator only provides the start of a region; we have to
23952      wait until the next invocation to get the start of the next region.  */
23953
23954   addrmap_index_data.objfile = objfile;
23955   addrmap_index_data.previous_valid = 0;
23956
23957   addrmap_foreach (objfile->psymtabs_addrmap, add_address_entry_worker,
23958                    &addrmap_index_data);
23959
23960   /* It's highly unlikely the last entry (end address = 0xff...ff)
23961      is valid, but we should still handle it.
23962      The end address is recorded as the start of the next region, but that
23963      doesn't work here.  To cope we pass 0xff...ff, this is a rare situation
23964      anyway.  */
23965   if (addrmap_index_data.previous_valid)
23966     add_address_entry (objfile, addr_vec,
23967                        addrmap_index_data.previous_cu_start, (CORE_ADDR) -1,
23968                        addrmap_index_data.previous_cu_index);
23969 }
23970
23971 /* Return the symbol kind of PSYM.  */
23972
23973 static gdb_index_symbol_kind
23974 symbol_kind (struct partial_symbol *psym)
23975 {
23976   domain_enum domain = PSYMBOL_DOMAIN (psym);
23977   enum address_class aclass = PSYMBOL_CLASS (psym);
23978
23979   switch (domain)
23980     {
23981     case VAR_DOMAIN:
23982       switch (aclass)
23983         {
23984         case LOC_BLOCK:
23985           return GDB_INDEX_SYMBOL_KIND_FUNCTION;
23986         case LOC_TYPEDEF:
23987           return GDB_INDEX_SYMBOL_KIND_TYPE;
23988         case LOC_COMPUTED:
23989         case LOC_CONST_BYTES:
23990         case LOC_OPTIMIZED_OUT:
23991         case LOC_STATIC:
23992           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23993         case LOC_CONST:
23994           /* Note: It's currently impossible to recognize psyms as enum values
23995              short of reading the type info.  For now punt.  */
23996           return GDB_INDEX_SYMBOL_KIND_VARIABLE;
23997         default:
23998           /* There are other LOC_FOO values that one might want to classify
23999              as variables, but dwarf2read.c doesn't currently use them.  */
24000           return GDB_INDEX_SYMBOL_KIND_OTHER;
24001         }
24002     case STRUCT_DOMAIN:
24003       return GDB_INDEX_SYMBOL_KIND_TYPE;
24004     default:
24005       return GDB_INDEX_SYMBOL_KIND_OTHER;
24006     }
24007 }
24008
24009 /* Add a list of partial symbols to SYMTAB.  */
24010
24011 static void
24012 write_psymbols (struct mapped_symtab *symtab,
24013                 std::unordered_set<partial_symbol *> &psyms_seen,
24014                 struct partial_symbol **psymp,
24015                 int count,
24016                 offset_type cu_index,
24017                 int is_static)
24018 {
24019   for (; count-- > 0; ++psymp)
24020     {
24021       struct partial_symbol *psym = *psymp;
24022
24023       if (SYMBOL_LANGUAGE (psym) == language_ada)
24024         error (_("Ada is not currently supported by the index"));
24025
24026       /* Only add a given psymbol once.  */
24027       if (psyms_seen.insert (psym).second)
24028         {
24029           gdb_index_symbol_kind kind = symbol_kind (psym);
24030
24031           add_index_entry (symtab, SYMBOL_SEARCH_NAME (psym),
24032                            is_static, kind, cu_index);
24033         }
24034     }
24035 }
24036
24037 /* A helper struct used when iterating over debug_types.  */
24038 struct signatured_type_index_data
24039 {
24040   signatured_type_index_data (data_buf &types_list_,
24041                               std::unordered_set<partial_symbol *> &psyms_seen_)
24042     : types_list (types_list_), psyms_seen (psyms_seen_)
24043   {}
24044
24045   struct objfile *objfile;
24046   struct mapped_symtab *symtab;
24047   data_buf &types_list;
24048   std::unordered_set<partial_symbol *> &psyms_seen;
24049   int cu_index;
24050 };
24051
24052 /* A helper function that writes a single signatured_type to an
24053    obstack.  */
24054
24055 static int
24056 write_one_signatured_type (void **slot, void *d)
24057 {
24058   struct signatured_type_index_data *info
24059     = (struct signatured_type_index_data *) d;
24060   struct signatured_type *entry = (struct signatured_type *) *slot;
24061   struct partial_symtab *psymtab = entry->per_cu.v.psymtab;
24062
24063   write_psymbols (info->symtab,
24064                   info->psyms_seen,
24065                   &info->objfile->global_psymbols[psymtab->globals_offset],
24066                   psymtab->n_global_syms, info->cu_index,
24067                   0);
24068   write_psymbols (info->symtab,
24069                   info->psyms_seen,
24070                   &info->objfile->static_psymbols[psymtab->statics_offset],
24071                   psymtab->n_static_syms, info->cu_index,
24072                   1);
24073
24074   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24075                                 to_underlying (entry->per_cu.sect_off));
24076   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE,
24077                                 to_underlying (entry->type_offset_in_tu));
24078   info->types_list.append_uint (8, BFD_ENDIAN_LITTLE, entry->signature);
24079
24080   ++info->cu_index;
24081
24082   return 1;
24083 }
24084
24085 /* Recurse into all "included" dependencies and count their symbols as
24086    if they appeared in this psymtab.  */
24087
24088 static void
24089 recursively_count_psymbols (struct partial_symtab *psymtab,
24090                             size_t &psyms_seen)
24091 {
24092   for (int i = 0; i < psymtab->number_of_dependencies; ++i)
24093     if (psymtab->dependencies[i]->user != NULL)
24094       recursively_count_psymbols (psymtab->dependencies[i],
24095                                   psyms_seen);
24096
24097   psyms_seen += psymtab->n_global_syms;
24098   psyms_seen += psymtab->n_static_syms;
24099 }
24100
24101 /* Recurse into all "included" dependencies and write their symbols as
24102    if they appeared in this psymtab.  */
24103
24104 static void
24105 recursively_write_psymbols (struct objfile *objfile,
24106                             struct partial_symtab *psymtab,
24107                             struct mapped_symtab *symtab,
24108                             std::unordered_set<partial_symbol *> &psyms_seen,
24109                             offset_type cu_index)
24110 {
24111   int i;
24112
24113   for (i = 0; i < psymtab->number_of_dependencies; ++i)
24114     if (psymtab->dependencies[i]->user != NULL)
24115       recursively_write_psymbols (objfile, psymtab->dependencies[i],
24116                                   symtab, psyms_seen, cu_index);
24117
24118   write_psymbols (symtab,
24119                   psyms_seen,
24120                   &objfile->global_psymbols[psymtab->globals_offset],
24121                   psymtab->n_global_syms, cu_index,
24122                   0);
24123   write_psymbols (symtab,
24124                   psyms_seen,
24125                   &objfile->static_psymbols[psymtab->statics_offset],
24126                   psymtab->n_static_syms, cu_index,
24127                   1);
24128 }
24129
24130 /* Create an index file for OBJFILE in the directory DIR.  */
24131
24132 static void
24133 write_psymtabs_to_index (struct objfile *objfile, const char *dir)
24134 {
24135   if (dwarf2_per_objfile->using_index)
24136     error (_("Cannot use an index to create the index"));
24137
24138   if (VEC_length (dwarf2_section_info_def, dwarf2_per_objfile->types) > 1)
24139     error (_("Cannot make an index when the file has multiple .debug_types sections"));
24140
24141   if (!objfile->psymtabs || !objfile->psymtabs_addrmap)
24142     return;
24143
24144   struct stat st;
24145   if (stat (objfile_name (objfile), &st) < 0)
24146     perror_with_name (objfile_name (objfile));
24147
24148   std::string filename (std::string (dir) + SLASH_STRING
24149                         + lbasename (objfile_name (objfile)) + INDEX_SUFFIX);
24150
24151   FILE *out_file = gdb_fopen_cloexec (filename.c_str (), "wb").release ();
24152   if (!out_file)
24153     error (_("Can't open `%s' for writing"), filename.c_str ());
24154
24155   /* Order matters here; we want FILE to be closed before FILENAME is
24156      unlinked, because on MS-Windows one cannot delete a file that is
24157      still open.  (Don't call anything here that might throw until
24158      file_closer is created.)  */
24159   gdb::unlinker unlink_file (filename.c_str ());
24160   gdb_file_up close_out_file (out_file);
24161
24162   mapped_symtab symtab;
24163   data_buf cu_list;
24164
24165   /* While we're scanning CU's create a table that maps a psymtab pointer
24166      (which is what addrmap records) to its index (which is what is recorded
24167      in the index file).  This will later be needed to write the address
24168      table.  */
24169   psym_index_map cu_index_htab;
24170   cu_index_htab.reserve (dwarf2_per_objfile->n_comp_units);
24171
24172   /* The CU list is already sorted, so we don't need to do additional
24173      work here.  Also, the debug_types entries do not appear in
24174      all_comp_units, but only in their own hash table.  */
24175
24176   /* The psyms_seen set is potentially going to be largish (~40k
24177      elements when indexing a -g3 build of GDB itself).  Estimate the
24178      number of elements in order to avoid too many rehashes, which
24179      require rebuilding buckets and thus many trips to
24180      malloc/free.  */
24181   size_t psyms_count = 0;
24182   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24183     {
24184       struct dwarf2_per_cu_data *per_cu
24185         = dwarf2_per_objfile->all_comp_units[i];
24186       struct partial_symtab *psymtab = per_cu->v.psymtab;
24187
24188       if (psymtab != NULL && psymtab->user == NULL)
24189         recursively_count_psymbols (psymtab, psyms_count);
24190     }
24191   /* Generating an index for gdb itself shows a ratio of
24192      TOTAL_SEEN_SYMS/UNIQUE_SYMS or ~5.  4 seems like a good bet.  */
24193   std::unordered_set<partial_symbol *> psyms_seen (psyms_count / 4);
24194   for (int i = 0; i < dwarf2_per_objfile->n_comp_units; ++i)
24195     {
24196       struct dwarf2_per_cu_data *per_cu
24197         = dwarf2_per_objfile->all_comp_units[i];
24198       struct partial_symtab *psymtab = per_cu->v.psymtab;
24199
24200       /* CU of a shared file from 'dwz -m' may be unused by this main file.
24201          It may be referenced from a local scope but in such case it does not
24202          need to be present in .gdb_index.  */
24203       if (psymtab == NULL)
24204         continue;
24205
24206       if (psymtab->user == NULL)
24207         recursively_write_psymbols (objfile, psymtab, &symtab,
24208                                     psyms_seen, i);
24209
24210       const auto insertpair = cu_index_htab.emplace (psymtab, i);
24211       gdb_assert (insertpair.second);
24212
24213       cu_list.append_uint (8, BFD_ENDIAN_LITTLE,
24214                            to_underlying (per_cu->sect_off));
24215       cu_list.append_uint (8, BFD_ENDIAN_LITTLE, per_cu->length);
24216     }
24217
24218   /* Dump the address map.  */
24219   data_buf addr_vec;
24220   write_address_map (objfile, addr_vec, cu_index_htab);
24221
24222   /* Write out the .debug_type entries, if any.  */
24223   data_buf types_cu_list;
24224   if (dwarf2_per_objfile->signatured_types)
24225     {
24226       signatured_type_index_data sig_data (types_cu_list,
24227                                            psyms_seen);
24228
24229       sig_data.objfile = objfile;
24230       sig_data.symtab = &symtab;
24231       sig_data.cu_index = dwarf2_per_objfile->n_comp_units;
24232       htab_traverse_noresize (dwarf2_per_objfile->signatured_types,
24233                               write_one_signatured_type, &sig_data);
24234     }
24235
24236   /* Now that we've processed all symbols we can shrink their cu_indices
24237      lists.  */
24238   uniquify_cu_indices (&symtab);
24239
24240   data_buf symtab_vec, constant_pool;
24241   write_hash_table (&symtab, symtab_vec, constant_pool);
24242
24243   data_buf contents;
24244   const offset_type size_of_contents = 6 * sizeof (offset_type);
24245   offset_type total_len = size_of_contents;
24246
24247   /* The version number.  */
24248   contents.append_data (MAYBE_SWAP (8));
24249
24250   /* The offset of the CU list from the start of the file.  */
24251   contents.append_data (MAYBE_SWAP (total_len));
24252   total_len += cu_list.size ();
24253
24254   /* The offset of the types CU list from the start of the file.  */
24255   contents.append_data (MAYBE_SWAP (total_len));
24256   total_len += types_cu_list.size ();
24257
24258   /* The offset of the address table from the start of the file.  */
24259   contents.append_data (MAYBE_SWAP (total_len));
24260   total_len += addr_vec.size ();
24261
24262   /* The offset of the symbol table from the start of the file.  */
24263   contents.append_data (MAYBE_SWAP (total_len));
24264   total_len += symtab_vec.size ();
24265
24266   /* The offset of the constant pool from the start of the file.  */
24267   contents.append_data (MAYBE_SWAP (total_len));
24268   total_len += constant_pool.size ();
24269
24270   gdb_assert (contents.size () == size_of_contents);
24271
24272   contents.file_write (out_file);
24273   cu_list.file_write (out_file);
24274   types_cu_list.file_write (out_file);
24275   addr_vec.file_write (out_file);
24276   symtab_vec.file_write (out_file);
24277   constant_pool.file_write (out_file);
24278
24279   /* We want to keep the file.  */
24280   unlink_file.keep ();
24281 }
24282
24283 /* Implementation of the `save gdb-index' command.
24284    
24285    Note that the file format used by this command is documented in the
24286    GDB manual.  Any changes here must be documented there.  */
24287
24288 static void
24289 save_gdb_index_command (const char *arg, int from_tty)
24290 {
24291   struct objfile *objfile;
24292
24293   if (!arg || !*arg)
24294     error (_("usage: save gdb-index DIRECTORY"));
24295
24296   ALL_OBJFILES (objfile)
24297   {
24298     struct stat st;
24299
24300     /* If the objfile does not correspond to an actual file, skip it.  */
24301     if (stat (objfile_name (objfile), &st) < 0)
24302       continue;
24303
24304     dwarf2_per_objfile
24305       = (struct dwarf2_per_objfile *) objfile_data (objfile,
24306                                                     dwarf2_objfile_data_key);
24307     if (dwarf2_per_objfile)
24308       {
24309
24310         TRY
24311           {
24312             write_psymtabs_to_index (objfile, arg);
24313           }
24314         CATCH (except, RETURN_MASK_ERROR)
24315           {
24316             exception_fprintf (gdb_stderr, except,
24317                                _("Error while writing index for `%s': "),
24318                                objfile_name (objfile));
24319           }
24320         END_CATCH
24321       }
24322   }
24323 }
24324
24325 \f
24326
24327 int dwarf_always_disassemble;
24328
24329 static void
24330 show_dwarf_always_disassemble (struct ui_file *file, int from_tty,
24331                                struct cmd_list_element *c, const char *value)
24332 {
24333   fprintf_filtered (file,
24334                     _("Whether to always disassemble "
24335                       "DWARF expressions is %s.\n"),
24336                     value);
24337 }
24338
24339 static void
24340 show_check_physname (struct ui_file *file, int from_tty,
24341                      struct cmd_list_element *c, const char *value)
24342 {
24343   fprintf_filtered (file,
24344                     _("Whether to check \"physname\" is %s.\n"),
24345                     value);
24346 }
24347
24348 void
24349 _initialize_dwarf2_read (void)
24350 {
24351   struct cmd_list_element *c;
24352
24353   dwarf2_objfile_data_key
24354     = register_objfile_data_with_cleanup (NULL, dwarf2_per_objfile_free);
24355
24356   add_prefix_cmd ("dwarf", class_maintenance, set_dwarf_cmd, _("\
24357 Set DWARF specific variables.\n\
24358 Configure DWARF variables such as the cache size"),
24359                   &set_dwarf_cmdlist, "maintenance set dwarf ",
24360                   0/*allow-unknown*/, &maintenance_set_cmdlist);
24361
24362   add_prefix_cmd ("dwarf", class_maintenance, show_dwarf_cmd, _("\
24363 Show DWARF specific variables\n\
24364 Show DWARF variables such as the cache size"),
24365                   &show_dwarf_cmdlist, "maintenance show dwarf ",
24366                   0/*allow-unknown*/, &maintenance_show_cmdlist);
24367
24368   add_setshow_zinteger_cmd ("max-cache-age", class_obscure,
24369                             &dwarf_max_cache_age, _("\
24370 Set the upper bound on the age of cached DWARF compilation units."), _("\
24371 Show the upper bound on the age of cached DWARF compilation units."), _("\
24372 A higher limit means that cached compilation units will be stored\n\
24373 in memory longer, and more total memory will be used.  Zero disables\n\
24374 caching, which can slow down startup."),
24375                             NULL,
24376                             show_dwarf_max_cache_age,
24377                             &set_dwarf_cmdlist,
24378                             &show_dwarf_cmdlist);
24379
24380   add_setshow_boolean_cmd ("always-disassemble", class_obscure,
24381                            &dwarf_always_disassemble, _("\
24382 Set whether `info address' always disassembles DWARF expressions."), _("\
24383 Show whether `info address' always disassembles DWARF expressions."), _("\
24384 When enabled, DWARF expressions are always printed in an assembly-like\n\
24385 syntax.  When disabled, expressions will be printed in a more\n\
24386 conversational style, when possible."),
24387                            NULL,
24388                            show_dwarf_always_disassemble,
24389                            &set_dwarf_cmdlist,
24390                            &show_dwarf_cmdlist);
24391
24392   add_setshow_zuinteger_cmd ("dwarf-read", no_class, &dwarf_read_debug, _("\
24393 Set debugging of the DWARF reader."), _("\
24394 Show debugging of the DWARF reader."), _("\
24395 When enabled (non-zero), debugging messages are printed during DWARF\n\
24396 reading and symtab expansion.  A value of 1 (one) provides basic\n\
24397 information.  A value greater than 1 provides more verbose information."),
24398                             NULL,
24399                             NULL,
24400                             &setdebuglist, &showdebuglist);
24401
24402   add_setshow_zuinteger_cmd ("dwarf-die", no_class, &dwarf_die_debug, _("\
24403 Set debugging of the DWARF DIE reader."), _("\
24404 Show debugging of the DWARF DIE reader."), _("\
24405 When enabled (non-zero), DIEs are dumped after they are read in.\n\
24406 The value is the maximum depth to print."),
24407                              NULL,
24408                              NULL,
24409                              &setdebuglist, &showdebuglist);
24410
24411   add_setshow_zuinteger_cmd ("dwarf-line", no_class, &dwarf_line_debug, _("\
24412 Set debugging of the dwarf line reader."), _("\
24413 Show debugging of the dwarf line reader."), _("\
24414 When enabled (non-zero), line number entries are dumped as they are read in.\n\
24415 A value of 1 (one) provides basic information.\n\
24416 A value greater than 1 provides more verbose information."),
24417                              NULL,
24418                              NULL,
24419                              &setdebuglist, &showdebuglist);
24420
24421   add_setshow_boolean_cmd ("check-physname", no_class, &check_physname, _("\
24422 Set cross-checking of \"physname\" code against demangler."), _("\
24423 Show cross-checking of \"physname\" code against demangler."), _("\
24424 When enabled, GDB's internal \"physname\" code is checked against\n\
24425 the demangler."),
24426                            NULL, show_check_physname,
24427                            &setdebuglist, &showdebuglist);
24428
24429   add_setshow_boolean_cmd ("use-deprecated-index-sections",
24430                            no_class, &use_deprecated_index_sections, _("\
24431 Set whether to use deprecated gdb_index sections."), _("\
24432 Show whether to use deprecated gdb_index sections."), _("\
24433 When enabled, deprecated .gdb_index sections are used anyway.\n\
24434 Normally they are ignored either because of a missing feature or\n\
24435 performance issue.\n\
24436 Warning: This option must be enabled before gdb reads the file."),
24437                            NULL,
24438                            NULL,
24439                            &setlist, &showlist);
24440
24441   c = add_cmd ("gdb-index", class_files, save_gdb_index_command,
24442                _("\
24443 Save a gdb-index file.\n\
24444 Usage: save gdb-index DIRECTORY"),
24445                &save_cmdlist);
24446   set_cmd_completer (c, filename_completer);
24447
24448   dwarf2_locexpr_index = register_symbol_computed_impl (LOC_COMPUTED,
24449                                                         &dwarf2_locexpr_funcs);
24450   dwarf2_loclist_index = register_symbol_computed_impl (LOC_COMPUTED,
24451                                                         &dwarf2_loclist_funcs);
24452
24453   dwarf2_locexpr_block_index = register_symbol_block_impl (LOC_BLOCK,
24454                                         &dwarf2_block_frame_base_locexpr_funcs);
24455   dwarf2_loclist_block_index = register_symbol_block_impl (LOC_BLOCK,
24456                                         &dwarf2_block_frame_base_loclist_funcs);
24457 }